Tuesday, May 3, 2011

determine if a wpf dependencyproperty value is inherited

Does anyone know how to determine if the value of a WPF property is inherited? In particular, I'm trying to determine if the DataContext of a FrameworkElement was inherited from the parent or set directly on the element itself.

Thanks, - Mike

From stackoverflow
  • Updated after more digging

    There is a ReadLocalValue method which is stupidly Read instead of Get so hard to spot in intellisense. (I think Apress' WPF book had a note about this actually.) It will return UnsetValue if the value hasn't been set.

    if (ReadLocalValue(Control.DataContextProperty) != 
        DependencyProperty.UnsetValue)
    {
        // Data context was set locally.
    }
    

    If you for some reason need to get all locally set properties, you can use LocalValueEnumerator.

    LocalValueEnumerator enumerator = GetLocalValueEnumerator();
    while (enumerator.MoveNext())
    {
        if (enumerator.Current.Property == Control.DataContextProperty)
        {
            // DataContext was set locally
        }
    }
    

    And these two methods really make me wonder. Read instead of Get in the ReadLocalValue and a collection which you cannot iterate with foreach in GetLocalValueEnumerator. It's like .Net has these nice standard things which the WPF team just decided to ignore.

  • DependencyPropertyHelper.GetValueSource will give you a ValueSource, which includes a property for retrieving the BaseValueSource. The BaseValueSource enumeration tells you where the DependencyProperty is getting its value from, such as inherited from parent, set via a style or set locally.

    HTH, Kent

  • an enumerator is standard, they just didn't provide a collection that uses that enumerator as the result of it's GetEnumerator method (which is what makes For Each work). also, from my experience, it is generally easier to write hierarchial algorithms in terms of enumerators rather than collections, so it does not surprise me they wouldn't provide this.

SubSonic 'Generate Enums from Lookup Tables'

I was asked by a fellow developer if I could code in some enums into SubSonic as he was needing them and he pointed out a post on the old SubSonic forums.

If anyone is interested in this functionality then an issue has been opened at http://code.google.com/p/subsonicproject/issues/detail?id=81 if you'd like to place some comments and feed back

Cheers

From stackoverflow

Enum ToString

My enum consists of the following values:

private enum PublishStatusses{
 NotCompleted,
 Completed,
 Error
};

I want to be able to output these values in a user friendly way though.
In this SO post, there is a lot of code that I can't seem to compile..
I don't need to be able to go from string to value again.
Why is it not compiling at my machine? How can I get such a result?

From stackoverflow
  • I use the Description attribute from the System.ComponentModel namespace. Simply decorate the enum and then use this code to retrieve it:

    public static string GetDescription<T>(this object enumerationValue)
                where T : struct
            {
                Type type = enumerationValue.GetType();
                if (!type.IsEnum)
                {
                    throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
                }
    
                //Tries to find a DescriptionAttribute for a potential friendly name
                //for the enum
                MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
                if (memberInfo != null && memberInfo.Length > 0)
                {
                    object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
    
                    if (attrs != null && attrs.Length > 0)
                    {
                        //Pull out the description value
                        return ((DescriptionAttribute)attrs[0]).Description;
                    }
                }
                //If we have no description attribute, just return the ToString of the enum
                return enumerationValue.ToString();
    
            }
    
    borisCallens : Nice, I will put that in my helper lib :) Thx
    Will : Extension methods are quicker to code, use, and support than metadata-based methods.
  • If you want something completely customizable, try out my solution here:

    http://www.kevinwilliampang.com/post/Mapping-Enums-To-Strings-and-Strings-to-Enums-in-NET.aspx

    Basically, the post outlines how to attach Description attributes to each of your enums and provides a generic way to map from enum to description.

  • foreach( PublishStatusses p in Enum.GetValues (typeof(PublishStatusses)) )
    {
       Console.WriteLine (p);
    }
    
    borisCallens : How does that answer my question exactly?
    Frederik Gheysels : It allows you to get all your enum values, and output them. That's what you wanted ?
    borisCallens : "I want to be able to output these values in a user friendly way"
  • That other post is Java. You can't put methods in Enums in C#.

    just do something like this:

    PublishStatusses status = ...
    String s = status.ToString();
    

    If you want to use different display values for your enum values, you could use Attributes and Reflection.

    borisCallens : HA! Silly me. I'm becoming to C#centric lately :P
    annakata : toString is not safe in all cases - an enum with multiple entries with the same value (say for integer enums) will return the key of the first matching value, not the key of the item tested, this is why Enum.GetName is preferred
    Lemmy : Well it was the easiest solution for his specific enum
  • The easiest solution here is to use a custom extension method (in .NET 3.5 at least - you can just convert it into a static helper method for earlier framework versions).

    public static string ToCustomString(this PublishStatusses value)
    {
        switch(value)
        {
            // Return string depending on value.
        }
        return null;
    }
    

    I am assuming here that you want to return something other than the actual name of the enum value (which you can get by simply calling ToString).

    borisCallens : Although valid, I like the attribute way more. That way I can put my toSTring method in a seperate library, whilst putting the custom string representation with the enum itself
    Lemmy : Hey that's a neat trick
    Noldorin : Fair enough. I suppose one advantage of this method is that you can include an argument with the method specifying some state variable, and then change what string representation is returned depending on this.
    borisCallens : Yes, it all depends on the scope of the method I guess. While the Attribute way is more generic, your solution is more localized.. It's all about needs in the end.
    Will : You can put extension methods anywhere you want. You just have to reference it where you want to use them.
    borisCallens : Yes, but this would mean that this one extention method should be rewritten every time you introduce a new enum you want to have a friendly name for. This would also mean that ALL your applications would carry around friendly names for ALL your other applications...
  • Maybe I'm missing something, but what's wrong with Enum.GetName?

    public string GetName(PublishStatusses value)
    {
      return Enum.GetName(typeof(PublishStatusses), value)
    }
    

    edit: for user-friendly strings, you need to go through a .resource to get internationalisation/localisation done, and it would arguably be better to use a fixed key based on the enum key than a decorator attribute on the same.

    borisCallens : I returns the literal value of the enum, not some user friendly one.
    annakata : oic - well there's a pretty big case that you have to go through a string resource library based on this value then, because the alternative (decorator attribs) won't support I18N
    borisCallens : In case of I18N I would make the GetDescription() method search in the resource lib for a translated string and fall back to the description and then fall back to the literal.
  • I do this with extension methods:

    public enum ErrorLevel
    {
      None,
      Low,
      High,
      SoylentGreen
    }
    
    public static class ErrorLevelExtensions
    {
      public static string ToFriendlyString(this ErrorLevel me)
      {
        switch(me)
        {
          case ErrorLevel.None:
            return "Everything is OK";
          case ErrorLevel.Low:
            return "SNAFU, if you know what I mean.";
          case ErrorLevel.High:
            return "Reaching TARFU levels";
          case ErrorLevel.SoylentGreen:
            return "ITS PEOPLE!!!!";
        }
      }
    }
    
    Will : dangit, noldorim snuck in on me. Giving him an upvote.
    borisCallens : yes, thanks for the input though. I put some remarks in noldorim's post regarding this solution.
    Noldorin : Why, thank you Will.
    Andrew Backer : This is quite nice, actually. Very helpful.
    JustLooking : I love this so much I want to marry it.
  • With respect to Ray Booysen, there is a bug in the code: http://stackoverflow.com/questions/479410/enum-tostring/479417#479417

    You need to account for multiple attributes on the enum values.

    public static string GetDescription<T>(this object enumerationValue)
                where T : struct
        {
            Type type = enumerationValue.GetType();
            if (!type.IsEnum)
            {
                throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
            }
    
            //Tries to find a DescriptionAttribute for a potential friendly name
            //for the enum
            MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
            if (memberInfo != null && memberInfo.Length > 0)
            {
                object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
    
                if (attrs != null && attrs.Length > 0 && attrs.Where(t => t.GetType() == typeof(DescriptionAttribute)).FirstOrDefault() != null)
                {
                    //Pull out the description value
                    return ((DescriptionAttribute)attrs.Where(t=>t.GetType() == typeof(DescriptionAttribute)).FirstOrDefault()).Description;
                }
            }
            //If we have no description attribute, just return the ToString of the enum
            return enumerationValue.ToString();
    

Save documents as folders, like Pages, Numbers, etc...

What's the right way to go about saving data like Pages, Numbers and other OSX applications do? That is, it looks like a file to the user, but is in fact a directory (a bundle?) containing a variety of stuff. I have some fairly complex data that I'd like to store in the same way; in particular, some sensor data that needs to be associated with video files.

From stackoverflow
  • The Apple official docs on the topic are probably a good starting point.

    From the Pages Info.plist file:

    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeExtensions</key>
            <array>
                <string>pages</string>
            </array>
            [...]
            <key>LSTypeIsPackage</key>
            <true/>
            [...]
        </dict>
    </array>
    

    seem to be what does the trick.

    Dan : Ahh, that's it! A remarkably difficult topic to search upon without knowing what it's called!
  • It also looks like NSFileWrapper may be part of the answer: Document-Based Applications Overview FAQ.

Any benefit in using WEXITSTATUS macro in C over division by 256 on exit() status?

I was doing an exercise for university where I had to return a value with exit, that value was actually a count of something. This could be above 255 (which exit() can't handle) but the teacher suggested to use test data where the count could never go above that value.

After all this, I needed to handle this count value, the exit status, I got this value in the main process by using waitpid(). To my surprise, if the child process returned 1, the "real" value in the main process was 256, 2 was 512 and so on...

I needed to print this value so I simply divided it by 256 and it was done. However, if I use the WEXITSTATUS() macro, I'll also get this value the way I want it...

I looked at C source code and this is what I found out:

#define __WEXITSTATUS(status) (((status) & 0xff00) >> 8)

I understand what's happening here, for instance, 512 in binary is 10 0000 0000, shifting 8 o the right will give 00 0000 0010, which is 2 in decimal. What I don't understand in this macro is that & operator and the fact that 0xff00 seems a random number (it probably isn't, where does it come from though?). What does this do exactly, why is there "& 0xff00" in the macro? Wouldn't it work with out it?

And the real question in this topic, is the same thing to call this macro in my code as dividing by 256?

From stackoverflow
  • Here 0xff00 is a binary mask (link text). ANDing it with a value sets all bits to zero, except the second byte (counting from the right).

    You should only use WEXITSTATUS on a process which is known to have exited normally. This information is given by the WIFEXITED macro.

    And the real question in this topic, is the same thing to call this macro in my code as dividing by 256?

    The macro makes the code more readable, and it's guaranted to work on any Posix-compliant implementation. As far as I know Posix doesn't specify the format of the status, so you can't expect your code to work everywhere.

  • And the real question in this topic, is the same thing to call this macro in my code as dividing by 256?

    It will probably always work in the cases where the child process terminates normally (i.e., by calling exit(), not by a segmentation fault, assertion failure, etc.).

    The status stored by waitpid() encodes both the reason that the child process was terminated and the exit code. The reason is stored in the least-significant byte (obtained by status & 0xff), and the exit code is stored in the next byte (masked by status & 0xff00 and extracted by WEXITSTATUS()). When the process terminates normally, the reason is 0 and so WEXITSTATUS is just equivalent to shifting by 8 (or dividing by 256). However, if the process is killed by a signal (such as SIGSEGV), there is no exit code, and you have to use WTERMSIG to extract the signal number from the reason byte.

  • If the status variable is a signed 16-bit integer (a 'short') on a machine where 'int' is a 32-bit quantity, and if the exit status is in the range 128..255, then WEXITSTATUS() still gives you a correct value where dividing by 256 or simply shifting right will give you an incorrect value.

    This is because the short will be sign extended to 32-bits, and the masking undoes the the sign extension, leaving the correct (positive) value in the result.

    If the machine used 16-bit integers, then the code in WEXITSTATUS() would probably do shift then mask to ensure similar behaviour:

    #define WEXITSTATUS(status) (((status)>>8) & 0xFF)
    

    It is because the implementation takes care of such details for you that you should use the WEXITSTATUS() macro.

make a windows highlight search in c#

Hi there! Would it be possible through c# to actually do a windows search (the one you find in Vista from the menu with higlighting (e.g you write 'fire' and get 'firefox')).

Thanks :)

From stackoverflow
  • Windows search uses an index to achieve the results by querying the index as the text in the search field is updated. In order for this to work the engine must be capable of returning results very quickly so a collection which is very efficient for lookups is a good idea.

    You would then query the hashtable when the text in the search box changes.

  • Yes, this is possible with the Windows Desktop Search (WDS) API. You'll need the SDK, which even provides a .Net assembly if I recall correctly. Then look at the documentation to learn how to query the WDS index. It's quite simple, here's the C# example they provide:

    OleDbConnection conn = new OleDbConnection(
        "Data Source=(local);Initial Catalog=Search.CollatorDSO;Integrated Security=SSPI;User ID=<username>;Password=<password>");
    
    OleDbDataReader rdr = null;
    
    conn.Open();
    
    OleDbCommand cmd = new OleDbCommand("SELECT Top 5 System.ItemPathDisplay FROM SYSTEMINDEX", conn);
    
    rdr = cmd.ExecuteReader();
    
    while (rdr.Read())
    {
        Console.WriteLine(rdr[0]);
    }
    
    rdr.Close();
    conn.Close();
    

    When I used this in a project awhile back, the query string I used was built something like this:

    CSearchManager SearchManager = new CSearchManager();
    CSearchCatalogManager CatalogManager = SearchManager.GetCatalog("SystemIndex");
    CSearchQueryHelper QueryHelper = CatalogManager.GetQueryHelper();
    string connection_string = QueryHelper.ConnectionString;
    

    Then to do a simple file search:

    QueryHelper.QueryWhereRestrictions = "AND scope='file:'";
    QueryHelper.QuerySorting = "System.ItemNameDisplay ASC";
    string sqlQuery = QueryHelper.GenerateSQLFromUserQuery(Filename);
    

    From the documentation you can see how to build queries that get you the results you need.

    Now, a quick note. I was able to build a Vista Start Search clone, however, I did it by first scanning link files in the places where Vista stores Start Menu links (%appdata%\Microsoft\Windows\Start Menu & C:\ProgramData\Microsoft\Windows\Start Menu), then asynchronously loading WDS results in the background, which replicates Start Search behavior better than relying solely on WDS.

    Johannes : Thanks :) I just wonder what is the field: User ID=;Password=. My username and password on my system/windows-account? Thx

What is the correct way to deal with css browser compatibility?

Is it better to have a different CSS file for each user-agent or is it better to use CSS Hacks that only certain browsers can see?

From stackoverflow
  • Neither.

    The best is to write code that works in all browsers without the need of browser specific code or css hacks. It's of course not quite as easy to accomplish, which is why many people use the other methods.

    The key is to avoid things that some browsers (very often Internet Explorer) has problems with. One such thing is to use padding rather than margin, because IE doesn't handle margin collapsing correctly.

    Some methods that is in the border line of being hacks is using code that doesn't affect browsers that work correctly, but fixes problems for a specific browser. That could be things like specifying a height for an element that normally shouldn't need one, or specifying display:inline on a floating element.

    The page Position is everything has examples of some bugs and suggested fixes. (Often the fix is some kind of hack, so you should of course also consider if you can avoid the problem altogether.)

    Chris Lively : Most of the problems you outlined boils down to setting the doctype. If you don't do that then yes, you will have radical differences between the browsers. Doctype with a css reset solves just about everything under normal usage.
    Guffa : No, what I have outlined applies even when you have a proper doctype and valid code. Without it you are a lot worse off.
  • Neither if possible. Now that the old Netscape, IE <= 6 etc. are not longer really that much in use, I try to use features which work in all those browsers (e.g. FF >= 2, IE >= 7, Chrome, Opera).

    marcgg : IE6 is still widely used, it's something between 15 and 20% of the market share depending on the source.
  • It's better to do neither.

    A good css-reset and css that works the same cross-browser is a much better solution.

    If your design absolutely precludes that, then (and only then) would I try hacks or IE conditional comments.

    I haven't yet seen the need for mutliple css files (beyond a few IE6 corrections addressed via a conditional comment).

  • Conditional comments for issues with Internet Explorer appear to be the norm. Combined with a little bit of JavaScript, like Dean Edward's ie7.js you can mitigate most cross browser issues without resorting to hacks within your CSS files.

  • its better to use a different css files for Internet Explorer 6-7 (include them via conditional comments), and a hacks for other browsers.

  • A sort of follow up is how to develop the single file that works.

    The best approach that I've seen work is to start from nothing, slowly building it up and checking change by change that it's still compatible across your core browsers (especially the problematic ones).

    When you get it fully working with one browser and then say "time to convert it" is when the pain really starts and where you have to start hacking.

  • My approach using a PHP class to detect os, browser and browser version. You can target any version of almost any browser on any operating system.

debugging a rails controller making too many queries

Hi All,

I have a rails application that about 3 years old, and I'm having a problem with my pages making too many queries. Every page that loads has several lines that look like this:

ReqTdsLink Columns (1.0ms)   SHOW FIELDS FROM `req_tds_links`

what sort of method call would cause this output in the log? I can't find any before filters, or anything else in the application controller that could be causing this, but I have yet to check all the views (which are astronomical in number) I'd like to have something specific to look for before i start manually scanning each file for something that might cause this.

thanks,

-C

From stackoverflow
  • This is called by ActiveRecord reading the attributes of a model from your database. It won't happen multiple times in production, but in development mode, Rails queries the table each time to pick up on any changes that may have occurred.

  • This line actually comes from calling the model, i had an array in the application controller that looked like [Model1, Model2, Model3] and I changed it to look like ['Model1','Model2', 'Model3'] and that fixed all the extra calls.

  • Are you running in development or production mode?

    SHOW FIELDS FROM foo is done by your model, as you noted, so it knows which accessor methods to generate.

    In development mode, this is done every request so you don't need to reload your webserver so often, but in production mode this information should be cached, even if you're running a three year old version of Rails.

    Mike Woodhouse : This is certainly true in Rails 2.1.2, which is where I am right now.
  • If you have this kind of problem again and need to track down how a query is being called I would suggest the Query Trace plugin: http://github.com/ntalbott/query_trace/tree/master. It adds a stack trace to the log for every SQL query. Very handy.

How do I compile assembly routines for use with a C program (GNU assembler)?

Hello!

I have a set of assembly function which I want to use in C programs by creating a header file. For instance, if I have asm_functions.s which defines the actual assembly routines and asm_functions.h which has prototypes for the functions as well as some standard #define's I needed. My goal is to use a C program, say test_asm.c to call the assembly functions.

asm__functions.h:


 #define ASM_CONST_1    0x80
 #define ASM_CONST_2    0xaf

uint8_t asm_foo( int, int, int );

asm__functions.s:


 /* dont need this: #include "asm_functions.h" */

.section .text .type asm_foo, @function asm__foo: /* asm code with proper stack manipulation for C calling conventions */ ret

test__asm.c:


 #include "asm_foo.h"

int main() { uint8_t res = asm_foo( 1, 2, 3); return 0; }

In a situation like this what would be the proper way to compile a link the program? I was trying something like this:


gas -o asm_foo.o asm_foo.s
gcc -o test_asm test_asm.c

But I still get a linker error from GCC saying that my assembly routine is undefined. I hope this contrived example is good enough to explain the situation.

Thanks!

EDIT:

Here is a snippet of output when I compile with a single command:


tja@tja-desktop:~/RIT/SP2/latest$ gcc -o test_pci pci_config.s test_pci.c
/tmp/ccY0SmMN.o: In function _pci_bios_read_byte':
(.text+0x8): undefined reference to PCI_FUNCTION_ID'
/tmp/ccY0SmMN.o: In function _pci_bios_read_byte':
(.text+0xa): undefined reference to READ_CONFIG_BYTE'
/tmp/ccY0SmMN.o: In function _pci_bios_read_byte':
(.text+0x18): undefined reference to PCI_BIOS_FUNCTION_INT'
/tmp/ccY0SmMN.o: In function _pci_bios_read_byte':
(.text+0x1b): undefined reference to BAD_REGISTER_NUMBER'
/tmp/ccY0SmMN.o: In function _pci_bios_read_word':
(.text+0x30): undefined reference to PCI_FUNCTION_ID'
...

All of those, such as PCI_FUNCTION_ID, are defined in my header file, which is included by the C program. When I compile the assembly code by itself there are no errors.

From stackoverflow
  • Have you considered using inline assembly? It would be much easier than using an assembler file.

    Edit: Also, the reason you are getting linker errors is probably because the C compiler adds a leading underscore on identifiers for the actual symbols. Try adding an underscore in your assembly file.

    TURBOxSPOOL : Yes, I considered it, but I am writing device level code which I wanted to create assembly routines directed. I thought in the end it would be cleaner than a ton of asm() calls.
    TURBOxSPOOL : Heh, in my actual assembly file and header file they are indeed defined with underscores: uint8_t _pci_bios_read_word( int, int int );
    Zifre : No, you shouldn't define it with underscores in the header file (that will give you double underscores). You only need the underscores in the assembly file.
  • Based on the files in your question, I managed to compile it. I've changed both the file names and the file contents.

    asm_const.h :

    #define ASM_CONST_1    0x80
    #define ASM_CONST_2    0xaf
    

    asm_functions.h :

    #include "asm_const.h"
    unsigned char asm_foo( int, int, int );
    

    asm_functions.S (the trailing S must be capital! #include needs it) :

    #include "asm_const.h"
    .section .text
    .globl asm_foo
    .type asm_foo, @function
    asm_foo:
      mov ASM_CONST_1, %eax
      /* asm code with proper stack manipulation for C calling conventions */
      ret
    

    test_asm.c :

    #include "asm_functions.h"
    int main() {
      return asm_foo( 1, 2, 3);
    }
    

    Please note that you need the the assembly file extension .S with capital S. With .s, the .s file wouldn't be run through the preprocessor, thus #include wouldn't work, and you wouldn't be able to use ASM_CONST_1 in the .s file.

    Compile with a single command:

    gcc -o test_asm asm_functions.S test_asm.c
    

    Or, as an alternative, compile with multiple commands, creating .o files:

    gcc -c asm_functions.S
    gcc -c test_asm.c
    gcc -o test_asm asm_functions.o test_asm.o
    

    The single-command gcc takes care of compiling the .S file using gas, the .c file with GCC's C compiler, and linking the resulting temporary .o files together using ld. gcc runs all those commands with the appropriate flags by default.

    On some systems (but not on Linux with the default GCC installation) you have to prepend an underscore to the names of exported functions in the .S file (but not in the .c or .h files). So all instances of asm_foo would become _asm_foo only in the .S file.

    TURBOxSPOOL : I am still having a problem with the preprocessor it seems. In my header file I have a bunch of #defines. When I try to compile everything from source with a single command I get a bunch of undefined references for the #defines in the header file.
    TURBOxSPOOL : But I thought that was the point? I created the .h file as if it were going to be linked with C code. But I just implemented the functions in assembly...I took the #include out of the assembly file, but I obviously still need it in the C program. So in the end I want the C program to include the header which has prototypes/constants for the assembly functions. Thanks!
    TURBOxSPOOL : Hmm, after adding the .globl I am still having the errors. I should have posted my code directly but I was leaning toward brevity...
    pts : I've just updated, extended and fixed my answer. Please have a look again.
    pts : Please rename pci_config.s to pci_config.S . This should fix your problem.
    TURBOxSPOOL : Thanks! Excellent post!

Amending a Git commit to a shared repo

Hey everyone,

I have a local git repo which I recently made a commit to, then pushed to a shared repo. Only after I pushed it to the shared repo did I realize I made an ugly mistake. I amended it locally no problem after I fixed my source with:

git commit -C HEAD -a --amend

After that, I tried another git push origin and I get the following error:

! [rejected]        mybranch -> mybranch (non-fast forward)

What's the best way to rectify this situation?

From stackoverflow
  • How about git reset?

  • git doesn't (by default) allow you to push to a branch anything that "rewinds" the branch tip. In other words, if the current branch head is not a direct parent or ancestor of the branch tip then the push will be refused.

    You can try to push anyway by using the -f option to git push or by using a refspec with a leading '+', e.g. git push origin +mybranch:mybranch .

    Usually remote repositories will still not let this happen because you risk losing commits if different people can indiscriminately push branch tips that don't include commits that they don't have locally.

    You can override this behaviour by changing the configuration parameter receive.denyNonFastForwards on the remote repository (assuming that you have the appropraite access to the remote repository).

    If you don't have such access you may be able to achieve this by deleting the remote branch and recreating it.

    e.g.

    git push origin :mybranch
    git push origin mybranch
    

    Note that more recent versions of git include a configuration parameter receive.denyDeletes that will, if set, prevent this potentially dangerous workaround from working.

    araqnid : Nice, I didn't know about denyNonFastForwards: I'd assumed you needed a hook to enforce that.
  • If you want to force the push, you can ... ehm ... pass --force to push.

    However, it is generally considered bad form to rewrite history on a public repository.

  • Assuming your shared repo allows, just prefix the branch name with a plus sign to force the non-fast-forward push:

    git push origin +mybranch
    
  • In this case it's probably best just to make a second commit with the fix. Since you've already altered the original first commit in your local repository, you'll probably want to pull it from the shared repository and move HEAD so that your altered commit can be garbage-collected.

How do I find the owner of a given database?

Using .NET's DbConnection.GetSchema(), how do I find the owner of a given database?

Alternatively, if you have another solution that is not coupled to a specific impelementation of SQL, I'd like to hear that as well.

From stackoverflow
  • The GetSchema call of DbConnection unfortunately doesn't retrieve the DB owner for you :-(

    But you can try this on SQL Server:

    select 
        db.name, db.database_id, l.name, l.type 
    from 
        sys.databases db
    inner join
        sys.login_token l on db.owner_sid = l.sid
    

    If you want to connect to SQL Server from .NET, you could use the SMO (SQL Management Objects) and find your owner like this:

        Server server = new Server("Your Server");
    
        Database db = server.Databases["Your Database"];
    
        Console.WriteLine("Database owner is: " + db.Owner);
    

    Marc

    Esteban Araya : Would you happen to have a query that works against Oracle, MySQL, etc.?
    marc_s : No, sorry, I'm not familiar with those database systems. And unfortunately, there really doesn't seem to be a universal database-agnostic catalog view (INFORMATION_SCHEMA) that shows the owner.
  • I don't believe that the SQL-92 standard specifies that a Catalog (a database) must have an owner. As such, I don't know that you can get a non-implementation-specific way of doing this.

asp.net continuous string wrap

Okay, so it seems, for some reason (I might be doing it wrong, obviously), that I have some problem wrapping continuous lines, using Asp.net.

Let's say I have 800 pixels worth of the "m" character, well, my table cell gets extended to that length. I don't want that, I want the cell to automatically break the continuous line after 300px.

To do that, I tried to apply the word-wrap:break-word css style. Didn't work. Now what?

Do I parse the line, to insert explicit linebreaks after a certain number of characters? That doesn't seem very clean to me. Any ideas?

From stackoverflow
  • Do you really have 800px of "m" or is that just test data? If that is real data then yes you will have to create some whitespace in there somewhere. HTML parsers don't wrap text that overflows an element unless that text has spaces in it that allow the text to be wrapped.

    If the m's are a test string and do not reflect real data I would suggest you use some dummy text (like Lorem Ipsum) to test with as it has spacing more akin to regular text.

    MrZombie : Actually, it's not "my" test data. My boss tests fields in such a way that he tries to break my application, to test the limits of stuff.I guess I could impose a conditional linebreak after an average length of non-breaky character stuff. Thanks for your help though. I was wondering whether it was possible or not to force that linebreak, as the "word-wrap" does. And somehow it works in IE7 on a div, but not on a TD... Might just try something, for the heck of it.
    MrZombie : After a trial: No, I can't do that either. Tried to insert the "wordwrap:break-word" inside the style of a div, but it dislikes that too. Why does it work in a simple page but not embedded in a table?
  • You can insert a <wbr> (little known html element) every few m's. It's not 100% compatible with everything, but it works in most browsers:

    <wbr> (word break) means: "The browser may insert a line break here, if it wishes." It the browser does not think a line break necessary nothing happens.

    So you would do something like this:

    mmmmmmmmm<wbr>mmmmmmmmmm<wbr>mmmmmmmmmmm<wbr> (etc.)
    

    Here's some more info: http://www.quirksmode.org/oddsandends/wbr.html

    MrZombie : I think "­" should work too, in theory... I'll try that.
    Keltex : ­ will also work, but it comes out as a hyphen whereever a break occurs. So as long as you don't mind that...
    Chris Lively : +1 because I had never heard of that tag before.

How to grab attachment programmatically (C#) from a POP3 mail?

Is there any C# API for this task? Any suggestions?

From stackoverflow
  • Here is a sample project that may provide what you need.

    MarlonRibunal : not much about grabbing the attachment ;-)
  • I've used /n Software in the past with success. Not free, but hey, you get to blame someone else if it doesn't work! (in other words, you get tech support from the company)

    They have a free trial as well.

Cookies in ASP.NET

I'm looking for a good example of storing data in a cookie using ASP.NET. Could someone show me an example?

From stackoverflow
  • Google says "How to Write a Cookie"

  • check this out

    Save Form Data With Cookies

    Chris Lively : Exactly what part of that link had anything at all to do with .Net?
  • MSDN is quite your friend : http://msdn.microsoft.com/en-us/library/78c837bd.aspx

    Until then :

    C#:  
    Response.Cookie["cookie_name"] = "value";
    
    VB:  
    Response.Cookie("cookie_name") = "value";
    
    rick schott : Please update answer with this link, http://msdn.microsoft.com/en-us/library/78c837bd.aspx. Site is only in en-US right now.
  • How to Create a cookie

    HttpCookie mycookie = new HttpCookie("mycookie");
    mycookie.Value = "chocolate chip please.";
    Response.Cookies.Add(mycookie);
    

    How to Read a cookie

    HttpCookie mycookie = Request.Cookies["mycookie"];
    Response.Write("Your cookie is: " + mycookie.Value);
    

dataset in html

Hi,

I am using asp.net and i would like to define the elements of a dataset in my html code. The problem is when i attempt to use:

<%@Using namespace="System.Data" %>

this is giving me an error

also

I am using

foreach (DataRow row in ds.Tables[0].Rows)
          {.....}

DataSet ds is obtained from an sql query. I don't believe to have any tables so is the above code ok?

Thank you so much!!

From stackoverflow
  • If ds was defined in the code-behind for it to be available in the .aspx side of things you must declare it as protected, rather than private.

  • If you want to import a namespace in the aspx page, try this:

    <%@ Import Namespace="System.Data" %>
    

    If you're more specific about your error, we can help you there too!

    Lily : actually thats what i really needed :) thanks

Combine two (or more) PDF's

Background: I need to provide a weekly report package for my sales staff. This package contains several (5-10) crystal reports.

Problem: I would like to allow a user to run all reports and also just run a single report. I was thinking I could do this by creating the reports and then doing:

List<ReportClass> reports = new List<ReportClass>();
reports.Add(new WeeklyReport1());
reports.Add(new WeeklyReport2());
reports.Add(new WeeklyReport3());
<snip>

foreach (ReportClass report in reports)
{
    report.ExportToDisk(ExportFormatType.PortableDocFormat, @"c:\reports\" + report.ResourceName + ".pdf");
}

This would provide me a folder full of the reports, but I would like to email everyone a single PDF with all the weekly reports. So I need to combine them.

Is there an easy way to do this without install any more third party controls? I already have DevExpress & CrystalReports and I'd prefer not to add too many more.

Would it be best to combine them in the foreach loop or in a seperate loop? (or an alternate way)

Thanks

From stackoverflow
  • PDFsharp seems to allow merging multiple PDF documents into one.

    And the same is also possible with ITextSharp.

  • I had to solve a similar problem and what I ended up doing was creating a small pdfmerge utility that uses the PDFSharp project which is essentially MIT licensed.

    The code is dead simple, I needed a cmdline utility so I have more code dedicated to parsing the arguments than I do for the PDF merging:

    using (PdfDocument one = PdfReader.Open("file1.pdf", PdfDocumentOpenMode.Import))
    using (PdfDocument two = PdfReader.Open("file2.pdf", PdfDocumentOpenMode.Import))
    using (PdfDocument outPdf = new PdfDocument())
    {                
        CopyPages(one, outPdf);
        CopyPages(two, outPdf);
    
        outPdf.Save("file1and2.pdf");
    }
    
    void CopyPages(PdfDocument from, PdfDocument to)
    {
        for (int i = 0; i < from.PageCount; i++)
        {
            to.AddPage(from.Pages[i]);
        }
    }
    
    Andrew Burns : Ah looks like Martin beat me to it, I am saying it was because I was diging up my code sample :)
  • Here is a link to an example using PDFSharp and ConcatenateDocuments

  • Here the solution http://www.wacdesigns.com/2008/10/03/merge-pdf-files-using-c It use free open source iTextSharp library http://sourceforge.net/projects/itextsharp

  • I've done this with PDFBox. I suppose it works similarly to iTextSharp.

  • You could try pdf-shuffler gtk-apps.org

  • I know a lot of people have recommended PDF Sharp, however it doesn't look like that project has been updated since june of 2008. Further, source isn't available.

    Personally, I've been playing with iTextSharp which has been pretty easy to work with.

  • There's some good answers here already, but I thought I might mention that pdftk might be useful for this task. Instead of producing one PDF directly, you could produce each PDF you need and then combine them together as a post-process with pdftk. This could even be done from within your program using a system() or ShellExecute() call.

Jquery fade <IMAGE background> on hover?

There is a link, with no background, and a css rule, which changes background on hover.

Parent bg is white, link on hover - .png background image.

How can I do a hover effect slowly, from white to my background image?

Thanks.


li a {} li a:hover { background: url(image.png) 0 0 no-repeat; }

From stackoverflow
  • One thing that comes to mind is strategically placing layers with backgroundimage set and layers with solid color on top of each other, and on hover, animating the Opacity property of the right thing (if the thing on top becomes transparent, the thing on bottom comes through).

  • CSS

    li {
      background: #FFF;
    }
    
    li a {
      opacity: 0;
      display:block;
      height:200px; /* Image height */
      width:200px; /* Image width */
      background:transparent url(image.png) top left no-repeat;
    }
    

    JavaScript

    $(function(){
      $("li a").hover(function(){
        $(this).stop();
        $(this).animate({"opacity":1}, "slow");
      }, function(){
        $(this).stop();
        $(this).animate({"opacity":0}, "slow");
      });
    });
    

    See http://docs.jquery.com/Effects

    jakemcgraw : If your anchors contain text, then the text will fade in and out with the background. You'll have to use a different HTML layout, like
  • Text
  • , and then position the span absolutely.

What are the elements of a team development suite?

For small-to-large teams developing software together, what tools are used to form a comprehensive team development framework?

Specifically, I'm looking for a comprehensive list of all the individual functions involved (e.g. source control, bug management, testing tools, project management), not specific product recommendations. I'm also not restricting the list to a particular methodology (e.g. Scrum).

From stackoverflow
  • You've hit the major ones in your post:

    • IDE (Integrated Development Environment)
    • Coding Guidelines (sometimes looked over, but it still helps tremendously)
    • Source Control
    • Testing Suite (Unit Testing, Test Case/Test Script Management and Tracking)
    • Issue Tracking/Bug Reporting
    • Build Management

    ...I'm sure I'm missing something obvious, but somebody around here will correct me.

    And the one I missed...

    • Diagraming software (I.E. Rational Software Modeler, etc.)
    • Source control (obviously) including branch management
    • Issue tracking (features and bugs), possibly with task reassignment and forwarding, and often things like screen recording
    • Individual task management, sometimes integrated with the issue tracking system
    • Communication software. Some teams use emails and IMs even within the same building or tweets. There are some tools that integrated within the code so you could "chat around a piece of code". Screen and application sharing are also useful.
    • Good build tool.
    • Distributed pair programming tools if applicable, shared editors otherwise.
    • Similar support in case tools.

    Less commonly used but promising tools (from academic background), some now have IDE based versions.

    Uri : glad I could help. Let me know if you need any more info.
  • A few more:

    • Requirements management software
    • Code review software
    • Continuous integration tool
    • Documentation repository - e.g. Wiki

How do I tell if a button is being held down in OpenGL/Glut? (linux)

This is a similar problem: Link
Which was solved by calling GetAsyncKeyState(). While all fine and dandy, I need a Linux alternative. I need to know if a button is being held down, not just being pressed (because of the keyboard buffer delay).

Does anything like this exist in the OpenGL/Glut libraries, or will I have to look elsewhere?

From stackoverflow
  • You can detect when a keypress event occurs, record that state, and then listen for a key release event.

    Wally : Which is what I am (sort of) currently doing. The problem is, glutKeyboardFunc() doesn't pass the current state. It only passes the ASCII character of the key.
    Scottie T : So keep track of the button you're interested in. You'll have to roll your own button state machine.
  • I have never used Glut, but I know that many people will say SDL is better. I have used SDL and I like it a lot. It does everything Glut does and a lot more. In SDL, you can use SDL_PollEvent() to get key state without the keyboard buffer delay.

    Edit: I know almost nothing about Glut, but it looks like you can use glutKeyboardFunc to detect normal keys, and glutSpecialFunc for keys that do not generate ASCII characters (such as shift). I'm not sure if there is a better way, as this doesn't seem very nice.

    Wally : Looks like this is what I'm going to have to do. SDL will fix other numerous problems as well. Thanks!

UILabel: Using the userInteractionEnabled method on a label

Hello again. I am wondering if anyone has used the userInteractionEnabled method on a UILabel to allow the label to act like a button (or just to fire off a method). Any help would be greatly appreciated. Cheers!

Update (4/30/09 @1:07pm) Clarification: I have a standard InfoButton and next to it I want to place a label with the text "settings" and I would like the label to function like the button (which flips over to a settings screen. So, basically I need to tie the already defined showSettinsView to the "infoLabel" label; a user clicks on the infoButton or infoLabel and the method fires off.

The infoButton is already working and is using an IBAction to trigger the method. I would like to know how to wire up the label to implement the same method. That is all. Cheers!

From stackoverflow
  • userInteractionEnabled is not a method but a property. But I think you will want to set this to YES to allow events to get through to the UIView superview.

    What you might want to do is override the touchesBegan:withEvent: method of the UIView that contains your UIButton and UILabel subviews.

    Within this method, test if any of the UITouch touches fall inside the bounds of the UILabel.

    That is, does the CGPoint element [touch locationInView] intersect with with the CGRect element [infoLabel bounds]? Look into the function CGRectContainsPoint to run this test.

    If so, then fire off an NSNotification that calls the same IBAction selector as the UIButton.

    Kevin Bomberry : Thanks Alex, I'll go ahead and try it and see what I can do. Cheers!
  • Another solution could be to use a UIButton with its type set to custom, instead of a UILabel. This way your second button will look like a UILabel, and you can configure it to trigger the showSettingsView method.

    fyasar : That's is really good trick.
  • yes godart is right this way u can make a button look like label and also can glow it