Wednesday, April 13, 2011

How do I Turn negative numbers red?

I am working with a dataset, and will be returning both positive and negative currency figures. I already have a parenthesis around it. How do I get only the negative numbers in the gridview to show up in red? Can I do this on the HTML side?

From stackoverflow
  • There are many ways to do this, two spring to mind:

    1. Apply a CSS class that will set the element's color to red.
    2. Set the Color property on the WebControl you are using to render the number.

    Without some code it will be difficult to give you specific examples.

  • Without going to a third party control that has formatting rules, I would use the Row's data binding event and color the text of the cell in question when it is negative. This adds a slight bit of weight to the UI layer, but not enough it will be noticeable until you are delivering thousands and thousands of rows. If you are delivering thousands and thousands of rows, you probably have an architecture problem.

  • I would set the CssClass of the control to something that styles the text the way you want if the number is negative. The reason for using CssClass instead of FontColor is that you may change this in the future and it will be easier to just change the CSS style rather than any code that uses it.

    <asp:BoundField runat="server"
        ItemStyleCssClass='<% (double)Eval("Value") < 0 ? "negative-number" : "" %>' />
  • protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)    {
       myCell = new TableCell();       
       myCell.Text =   e.Row.DataItemIndex.ToString();
       myCell.Style["color"] = decimal.Parse(myCell.Text)<0?"Red":"OtherColor";

    or something like that

  • You could try styling with jQuery:


    $("span:contains('-')").css("color", "#f00");

    Of course, change span for whatever tag your number is in (and consider going into something more specific than just span like span.number-container for example.

WCF and Object

I am trying to pass an object into a WCF web service, the object I am passing in is a Server object, I then want to be able to call TestConnection();

The issue I am having is that Server is the base class and there are several derived classes of Server, i.e. SqlServer2005Server, OracleServer and ODBCServer that I want to use

I want to be able to pass in a Server Object and then determine its type, cast it and then use the method

public string TestServerConnection(Server server)
    if (server.ConnectionType == "SqlServer")
        SqlServer2005Server x = (SqlServer2005Server)server;
        // Tests connection to server and returns result
        return x.TestConnection();

    return "";

'Server' the base class implements IServer

I am unable to cast it, can you advise?

Much Appreciated


From stackoverflow
  • You need to add the KnownType declaration to your service contract for each derived class. There are ways to automate this (since it obviously convolutes code and breaks inheritance), but they require a lot of work.

  • Does the object you're passing represent a "live" connection to a DBMS? If the answer is yes, there is no hope of this ever working. Keep in mind that despite the pretty wrapper, the only thing your web service is getting from the caller is a chunk of xml.

  • As Daniel Pratt said, in the end, you are only shuttling XML (not always the case, but most of the time you are) across the wire.

    If you used a proxy generator to generate the definition of the Server type, then you aren't going to be able to make calls on the methods of Server, because only properties (semantically at least) are used in the proxy definition. Also, you can't cast to the derived types because your instance is really a separate type definition, not the actual base.

    If the Server type is indeed the same type (and by same, I mean a reference to the same assembly, not just in name and schema only), then you can do what Steve said and use the KnownType attribute on the Server definition, adding one attribute for each derived class.

    However, like he said, that convolutes your code, so be careful when doing this.

    I thought that using inversion of control would work here, but you run into the same situation with generic references to specific providers.

Using Cups Reverse Orientation on a Postscript file

When using the lp -o orientation-requested=6 in CUPS to print a postscript file, the first page is reversed 180 degrees and then the next page is back to 0 orientation. Third page has the 180 degree rotation and fourth page back to 0 and so on. I need each page in the file to be reversed 180 degrees. Any suggestions on what to try would be most appreciated.

From stackoverflow
  • If your PostScript file does not conform strictly to the PostScript DSC (document structuring convention), and the file is being sent to a PostScript printer, then whatever extras that CUPS may add to the pages may be getting overridden by ill-behaved per-page stuff in your document. Unfortunately there's no particularly good fix for overcoming arbitrary ill-behaved PostScript code. (The rotate-every-other-page or rotate-every-page-an-extra-180 behavior supports this via.

    If it's your own application that's generating the PostScript file, you might benefit from comparing what you pipe into the spooler against what CUPS actually sends to the printer (you could capture it with netcat).

A regular expression to retrieve the previous line in a log file

My log files contain the following:

2009-03-12T12:44:27+0000 something was logged
2009-03-12T12:45:36+0000 <> last message repeated 2 times

I can write a regular expression that retrieves the line with the "last message repeated..." statement, however, that line is meaningless without also retrieving the line that precedes it.

With that being said, does anyone know of a regular expression that would allow me to retrieve both lines whenever the "last message repeated..." statement is detected?

From stackoverflow
  • I would do it this way. Try to search for pattern that includes two groups. First group is a line followed by another group containing another line with "last message repeated" text. Then the content of the first group is the text you are looking for.

    Something like this (this is overly simplified regex):

    \n(.*)\n(.*)last message repeated

    Now first group value contain the line you are interested in.

    Huuuze : What would that regex look like?
    goldenmean : @David: Can u give the regex with two groups as u said?
    David Pokluda : Regexes added to the answer. Those are simple but you get the idea. They work - I verified them in Regex Buddy.
  • Edited to be 2 group matching regex. You can give it a shot at: RegexLib

    Less then optimized but this:

    ([\r\n].*?)(?:=?\r|\n)(.*?(?:last message repeated).*)

    Should work to get results out of something like this:

    2009-03-12T12:44:27+0000 something1 was logged
    2009-03-12T12:44:27+0000 something2 was logged
    2009-03-12T12:45:36+0000 <> last message repeated 2 times
    2009-03-12T12:44:27+0000 something3 was logged
    2009-03-12T12:44:27+0000 something4 was logged
    2009-03-12T12:44:27+0000 something5 was logged
    2009-03-12T12:45:36+0000 <> last message repeated 2 times

    Resulting in:

    First Match, First Group: 2009-03-12T12:44:27+0000 something2 was logged
    First Match, Second Group: 2009-03-12T12:45:36+0000 <> last message repeated 2 times
    Second Match, First Group: 2009-03-12T12:44:27+0000 something5 was logged 
    Second Match, Second Group: 2009-03-12T12:45:36+0000 <> last message repeated 2 times
  • Does it have to be regex? grep allows you to get a context before and after match (-B NUM and -A NUM options)

    Huuuze : Good answer, but, yes, it has to be a regex.
  • The pattern ^.*$ matches a whole line. Translation: Start Of Line, followed by any number of characters, followed by End Of Line. So perhaps you can search for "any line, followed by" (the pattern you have there).

how do I install apache portable runtime

Hi,..I am trying to install subversion on a linux machine and get I get and error saying that I don't have APR installed

My question is: how do I install APR and link with with my Apache HTTP server (i have 2.2 running)?

I have looked for documentation for about 2 hours now,...can't find anything...i would also like to mention that i am pretty big unix newb.

Pointing me in the right direction would be greatly appreciated.


From stackoverflow
  • Apache Portable Runtime is installed alongside apache server. all you have to do is make sure your LD_LIBRARY_PATH contains path for <APACHEINSTALLDIR>/lib and it will be detected by your svn.

    Andrew : what about apr-util?
    Andrew : nevermind. thanks.

What does the csrss.exe process do?

What is the purpose of the csrss.exe (Client/Server Runtime Server Subsystem) on Windows?

Maybe someone could give a good explanation or pointers to documentation? Unfortunately Google results are pretty noisy when searching a core process of Windows.

The reason I'm asking is that I got a BSOD from my service application which seems to be related to the csrss.exe process, at least this is what the analysis of the memory dump shows:


IMAGE_NAME:  csrss.exe

PROCESS_NAME:  PreviewService.
BUGCHECK_STR:  0xF4_PreviewService.
LAST_CONTROL_TRANSFER:  from 80998221 to 80876b40

f5175d00 80998221 000000f4 00000003 85eeeb70 nt!KeBugCheckEx+0x1b
f5175d24 8095b1be 8095b1fa 85eeeb70 85eeecd4 nt!PspCatchCriticalBreak+0x75
f5175d54 8082350b 00000494 ffffffff 051bf114 nt!NtTerminateProcess+0x7a
f5175d54 7c8285ec 00000494 ffffffff 051bf114 nt!KiFastCallEntry+0xf8
051bf114 00000000 00000000 00000000 00000000 ntdll!KiFastSystemCallRet

FOLLOWUP_NAME:  MachineOwner
FAILURE_BUCKET_ID:  0xF4_PreviewService._IMAGE_csrss.exe
BUCKET_ID:  0xF4_PreviewService._IMAGE_csrss.exe

Followup: MachineOwner

EDIT: Thanks already for the good answers, but I actually don't need help concerning my service, I just would like to get some basic understanding of what the purpose of this service is.

From stackoverflow
  • csrss is the user-mode portion of the Win32 subsystem -- the user-mode analog to the kernel-mode win32.sys. As for what's going on with your particular service, it's hard to say without some better hints about what your service is doing.

  • CSRSS hosts the server side of the Win32 subsystem. It is considered a system critical process, and if it is ever terminated you'll get a blue screen. More data is necessary, but you need to find out if some process is terminating csrss, or if it is crashing due to a bug.

    Windows Internals is a great book for stuff like this. Wikipedia also has an article on CSRSS.

  • One thing it does is provide the default console window for console apps like cmd.exe. At least according to jdeBP:

    It would appear that when a console app process is created without being passed handles to stdin, stdout and stderr, then some interprocess comms asks csrss to create a console window in a new thread and give its IO handles to the console process.

what is the right way to validate if an object exists in a django view without returning 404?

basically just verify if an object exists and return the object. then based on that perform actions. I'm wondering whats the right way to do it without returning a 404?

    listing = RealEstateListing.objects.get(slug_url = slug)
    listing = None

if listing:
From stackoverflow
  • If you want a page to return 404 Not Found if an object doesn't exist, you can use django.shortcuts.get_object_or_404:

    listing = get_object_or_404(RealEstateListing, slug_url=slug)

    This will return the object with the given ID, or raise Http404 if it's not found.

    If you want to do something other than raise an Http404 exception, you could do something like this:

        listing = get_object_or_404(RealEstateListing, slug_url=slug)
    except Http404:
        # Do something else
    mipadi : I provided the second code snippet for that case. ;)
    Rasiel : oops.. sorry did not notice that somehow
  • I would not use the 404 wrapper if you aren't given a 404. That is misuse of intent. Just catch the DoesNotExist, instead.

        listing = RealEstateListing.objects.get(slug_url=slug)
    except RealEstateListing.DoesNotExist:
        listing = None
    Tiago : +1: I'd use this instead of 404 wrapper too.
    Carl Meyer : +1: Yes, this is a better solution than the accepted one, if you don't want the 404.
    Rasiel : yap, this seems to be the better solution

How to add extra newline with 'puts' without sticking newline character into string?

If I say

puts "Hello"

and decide to add an extra newline I need to do this:

puts "Hello\n"

Having this character in the string is ugly. Is there any way to do this without polluting my string?

From stackoverflow
  • Just make another call to puts:

    puts "Hello"
  • Well, I don't think an explicit newline is ugly. mipadi's answer is just fine as well. Just to throw another answer in, make an array of the lines then join the aray with a newline. :)

  • Do you think this looks nicer?

    puts "Hello"+$/


  • The reason why Ruby use \n for a newline is because its base on C where Ruby MRI is written in C and even JRuby is written in Java which is base on C++ which is base on C... you get the idea! So all these C-style languages use the \n for the new line.

    You can always write your own method that act like puts but add new lines base upon a parameter to the method.

  • puts "Hello",""

Find MySQL row identified by number in a warning message

The MySQL "show warnings" output identifies problematic rows by number. What's the best way to quickly see all the data for such a row?

For example, after running an update statement the result indicates "1 warning" and running show warnings gives a message like this: "Data truncated for column 'person' at row 65278". How can I select exactly that row?

Here is a concrete example exploring the limit solution:

create table test1 (
  id     mediumint,
  value  varchar(2)
insert into test1 (id, value) values
  (11, "a"),
  (12, "b"),
  (13, "c"),
  (14, "d"),
  (15, "ee"),
  (16, "ff");
update test1 set value = concat(value, "X") where id % 2 = 1;
show warnings;

That results in this warning output:

| Level   | Code | Message                                    |
| Warning | 1265 | Data truncated for column 'value' at row 5 | 

To get just that row 5 I can do this:

select * from test1 limit 4,1;

resulting in this:

| id   | value |
|   15 | ee    | 

So it seems that the limit offset (4) must be one less than the row number, and the row number given in the warning is for the source table of the update without regard to the where clause.

From stackoverflow
  • As far as I'm aware, the only way to select those rows is to just SELECT them using the criteria from your original UPDATE query:

    mysql> UPDATE foo SET bar = "bar" WHERE baz = "baz";
    mysql> SHOW WARNINGS;
    Message: Data truncated for column 'X' at row 420
    mysql> SELECT * FROM foo WHERE baz = "baz" LIMIT 420,1;

    Obviously, this doesn't work if you've modified one or more of the columns that were part of your original query.

  • LIMIT x,y returns y number of rows after row x, based on the order of the resultset from your select query. However, if you look closely at what I just said, you'll notice that without an ORDER BY clause, you've got no way to guarantee the position of the row(s) you're trying to get.

    You might want to add an autoincrement field to your insert or perhaps a trigger that fires before each insert, then use that index to ensure the order of the results to limit by.

What is causing this ActiveRecord::ReadOnlyRecord error?

This follows this prior question, which was answered. I actually discovered I could remove a join from that query, so now the working query is

start_cards = DeckCard.find :all, :joins => [:card], :conditions => ["deck_cards.deck_id = ? and cards.start_card = ?",, true]

This appears to work. However, when I try to move these DeckCards into another association, I get the ActiveRecord::ReadOnlyRecord error.

Here's the code

for player in @game.players 
  player.tableau =
  start_card = start_cards.pop 
  start_card.draw_pile = false
  player.tableau.deck_cards << start_card  # the error occurs on this line

and the relevant Models (tableau are the players cards on the table)

class Player < ActiveRecord::Base
  belongs_to :game
  belongs_to :user
  has_one :hand
  has_one :tableau

class Tableau < ActiveRecord::Base
  belongs_to :player
  has_many :deck_cards

class DeckCard < ActiveRecord::Base
  belongs_to :card
  belongs_to :deck  

I am doing a similar action just after this code, adding DeckCards to the players hand, and that code is working fine. I wondered if I needed belongs_to :tableau in the DeckCard Model, but it works fine for the adding to player's hand. I do have a tableau_id and hand_id columns in the DeckCard table.

I looked up ReadOnlyRecord in the rails api, and it doesn't say much beyond the description.

From stackoverflow
  • From the ActiveRecord CHANGELOG:

    Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around.

    Using find_by_sql is not really an alternative as it returns raw row/column data, not ActiveRecords. You have two options:

    1. Force the instance variable @readonly to false in the record (hack)
    2. Use :include => :card instead of :join => :card

    Cheers, V.

    Sep 2010 UPDATE

    Most of the above no longer holds true. Thus, in Rails 2.3.4 and 3.0.0:

    • using Record.find_by_sql is a viable option
    • :readonly => true is automatically inferred only if :joins was specified without an explicit :select nor an explicit (or finder-scope-inherited) :readonly option (see the implementation of set_readonly_option! in active_record/base.rb for Rails 2.3.4, or the implementation of to_a in active_record/relation.rb and of custom_join_sql in active_record/relation/query_methods.rb for Rails 3.0.0)
    • however, :readonly => true is always automatically inferred in has_and_belongs_to_many if the join table has more than the two foreign keys columns and :joins was specified without an explicit :select (i.e. user-supplied :readonly values are ignored -- see finding_with_ambiguous_select? in active_record/associations/has_and_belongs_to_many_association.rb.)
    • in conclusion, unless dealing with a special join table and has_and_belongs_to_many, then @BigCanOfTuna's answer applies just fine in Rails 2.3.4 and 3.0.0.
    • do not use :includes if you want to achieve an INNER JOIN (:includes implies a LEFT OUTER JOIN, which is less selective and less efficient than INNER JOIN.)
    : the :include is helpful in reducing the # of queries done, I didn't know about that; but I tried to fix it by changing the Tableau/Deckcards association to a has_many: through, and now I'm getting a 'could not find association' msg; I may have to post another question for that
    vladr : @codeman, yes, the :include will reduce the number of queries *and* will bring the included table into your condition scope (a sort of implicit join without Rails marking your records as read-only, which it does as soon as it sniffs anything SQL-ish in your find, including :join/:select clauses IIRC
    vladr : For 'has_many :a, through => :b' to work, the B association must be declared as well, e.g. 'has_many :b; has_many :a, :through => :b', I hope this is your case?
    : yes, I didn't have the 'has_many :b' association; once I got that it all worked great - Thanks!
    BigCanOfTuna : This might have changed in recent releases, but you can simply add :readonly => false as part of the find method attributes.
    Lee : This answer is also applicable if you have a has_and_belongs_to_many association with a custom :join_table specified.
  • Instead of find_by_sql, you can specify a :select on the finder and everything's happy again...

    start_cards = DeckCard.find :all, :select => 'deck_cards.*', :joins => [:card], :conditions => ["deck_cards.deck_id = ? and cards.start_card = ?",, true]

  • This might have changed in recent release of Rails, but the appropriate way to solve this problem is to add :readonly => false to the find options.

    Olly : I don't believe this is the case, with 2.3.4 at least
  • Or in Rails 3 you can use the readonly method (replace "..." with your conditions):

    ( Deck.joins(:card) & Card.where('...') ).readonly(false)

    See for more info.

    There are also some good Railscasts on this. See "Active Record Queries in Rails 3" and "Advanced Queries in Rails 3". I can't post the links here due to the spam filter.

How can i store attributes of an xml node in an array of strings?(Reframed)

Duplicate of how can i store the attributes of an xml node in an array of strings, you should edit the original question.

I am a newbie so I am reframing earlier asked question. I have a project where my xmldoc is created with help of XmlDocument class and then loaded with the help of xmldoc.Load() method.With the help of addnodes() method,i add nodes to tree,thus its displayed in a winform.Now when i click on an xmlnode in the treeview its attributes get displayed in the listbox.Now i have divided the whole logic in UI and back end part. Now what i want that my back end class contains the method to display atrributes(name and value) of the xml node clicked and these are stored in an array and it is returned as a string to my front end class in the treev_AfterSelect event. How can i do it?I need to store attributes of the node i click on winform in a string array and display in listbox.How to do it?

From stackoverflow
  • This could use more detail, but I'll hazard a guess:

    You save an XmlElement in the Tag property of the TreeNode, right? Then you want to take that XmlElement from the Tag on the AfterSelect event, and pass it to a method that will return an IEnumerable of the attributes (and values?). IEnumerable instead of string[] to be flexible.

    That's pretty simple, and I'll leave the details "as an exercise", but just loop through element.Attributes, and add to a list each attribute name and value. Format them as "name=value" if you like. Then, just return the list.

    : i did exactly what you said. now i am trying to implement another method by using string array. i am not much aware of string array manipulation. please help. can you give me the syntax of how to add attributes to an array of string?
    John Saunders : Don't use an array. Use a List (List(Of String) in VB). If necessary, you can then return list.ToArray().
  • I've found through bitter experience that using the Tag property builds fragile solutions. A type-safe way of mapping TreeNodes to XmlElements is to create a Dictionary<TreeNode, XmlElement>. It's a mite harder at first than using the Tag property, but it makes the association extremely explicit. (I just yesterday fixed a bug that came from one piece of code saving keys to objects in a Tag property while another one was expecting the Tag to contain the objects themselves.)

    So the code in the AfterSelect event would look something like:

    TreeNode n = sender as TreeNode;
    if (n != null)
       string[] result = TreeNodeMap[n].Attributes
          .Select(x => x.Name + "=" + x.Value)
  • But TreeNode class cannote be put in backend. It can only come in front end. The above solution would give an error if i put it in backend class, I have made something like this

    "public List selectedNode(XmlNode eventNode) { if (eventNode == null) return; XmlAttributeCollection attCol = eventNode.Attributes; List ab = new List(); MessageBox.Show(attCol.Count.ToString()); if (attCol != null) for (int i = 0; i <= attCol.Count; i++) { ab[i] = "Attribute name:" + attCol[i].Name + "," + "Attribute value:" + attCol[i].Value; } return ab; } " I am calling this method in front end, But i am getting an error Index out of range. Please help me rectify it. Its in relation to my main question.

ExpectedException not catching exception, but I can catch it with try catch

Any ideas on this one? I'm trying to write a unit test that will delete an item and confirm that item is no longer in a repository by trying to retrieve the item by its ID which should throw a DataAccessException. However, the test keeps failing. I added a try catch block and sure enough I caught the exception I was expecting. I'm using VS Test Tools for unit testing.

    private static void NHibernateRepositoryBaseDeleteHelper<T, TKey>(T myItem, TKey myItemId)
        MyTestRepository<T, TKey> myRepository = new MyTestRepository<T, TKey>();
            myRepository.GetById(myItemId, false);
        catch (DataAccessException dae)
From stackoverflow
  • You need to add the ExpectedException attribute onto the same method which has the TestMethod attribute. The VS Unit Test Framework will only look for an ExpectedException attribute at the entry point of a particular test.

    public void ATestMethod() {
      NHibernateRepositoryBaseDeleteHelper(itemValue, keyValue);
  • You are munging up your delete method first of all. I would have a separate delete method and test method. Yes, you are testing the delete, but really you are testing the behavior that is associated with delete. There are probably additional tests here.

    As this is part of what appears to be an autogenerated test, I would not add to the same repository object in that test, but would perform my test(s) in their own test methods and use the delete as part of the set up for the class. That will certainly separate the test from the delete.

    Hope this helps.

  • I'll add to what Jared said by pointing out that the "ExpectedException" attribute sucks. There's no way to assert that the exception's message is correct (the "message" parameter doesn't do what you might think it does) and you can't check for multiple exceptions in one test.

    A better solution is to do something like this:

    That class lets you do neat stuff like this:

    public void TestAFewObviousExceptions()
    // some setup here
       ExceptionAssert.Throws("Category 47 does not exist", () => 
       ExceptionAssert.Throws("Id Flim is not valid", () => 
    Scott Dorman : Have to give you a +1 for the link. :) Just curious, did you need to edit or add to the ExceptionAssert class in the blog post?
    mhenry1384 : I originally wrote in my answer "I wrote my own exception class based off that code", but now that I compare the function that I use with what's on that website, it looks like all I did was take it verbatim and stick it in my own namespace. :-)

Whats the most important part of html page in terms of SEO keyword targeting- the title?

whats the most important part of html page in terms of SEO keyword targeting- the title?

From stackoverflow
  • In my experience:

    1. The domain name (
    2. The name and path of the page itself (/key/word/lots-of-keywords.html)
    3. The Title (keywords first, the shorter the better)
    4. Header tags (from h1 -> h3)
    5. Stuff closest to the top of the page.

How do I group items in a WPF ListView

I have a ListView that I want to group results into, however the examples I am finding are not working. How can I group my results?

I want to group on the Status property in my custom object.

This is what I have:

<ListView IsSynchronizedWithCurrentItem="True"
                 Background="Transparent" SelectionChanged="ListView_SelectionChanged"

                        <TextBlock FontWeight="Bold" FontSize="15"
                         Text="{Binding Path=Status}"/>

            <Style TargetType="{x:Type ListViewItem}">
                <Setter Property="BorderThickness" Value="1" />
                <Setter Property="Width" Value="Auto" />
                <Setter Property="FontSize" Value="10.4"  />               

                <GridViewColumn DisplayMemberBinding="{Binding Path=Number}" Header="Shelve ID"  />
                <GridViewColumn DisplayMemberBinding="{Binding Path=Customer}" Header="Customer" />
                <GridViewColumn DisplayMemberBinding="{Binding Path=PurchaseOrderNo}" Header="PO Number" />
                <GridViewColumn DisplayMemberBinding="{Binding Path=SubmittedBy}" Header="Shelved By"  />
                <GridViewColumn DisplayMemberBinding="{Binding Path=OrderDate, StringFormat=MMM dd\, yyyy}" Header="Date"  />
                <GridViewColumn DisplayMemberBinding="{Binding Path=CustomerTerms.Description}" Header="Order Terms"  />
                <GridViewColumn DisplayMemberBinding="{Binding Path=ShippingMethod.Description}" Header="Shipping"  />
                <GridViewColumn DisplayMemberBinding="{Binding Path=TotalPrice, StringFormat=c}" Header="Order Total"  />

 void ShelvedOrderList_DataContextChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)

 private void AddGrouping()
            if ( lstShelvedOrders.ItemsSource == null)

            CollectionView myView = (CollectionView)CollectionViewSource.GetDefaultView(lstShelvedOrders.ItemsSource);
            PropertyGroupDescription groupDescription = new PropertyGroupDescription("Status");
From stackoverflow
  • I notice one thing right away - the GroupStyle.HeaderTemplate will be applied to a CollectionViewGroup, so your DataTemplate should probably look like this:

                <TextBlock FontSize="15" FontWeight="Bold" Text="{Binding Name}"/>

    CollectionViewGroup.Name will be assigned the value of Status for that group.

    Russ : Well, I'm getting three instances of the group now now, but its grouping so thats a win. Your getting to be my personal hero here.

Crystal Reports: Subreport on more than one page

Hi I have a Crystal reports, report set up and I want to insert a sub report as the first page. I thought I can do this buy placing a subreport in the PageHeader of my other report. It works well but it does not display the rest of my sub report pages; it only displays the first page. Can someone help me configure this? Thank you.

From stackoverflow
  • Sorry, for wasting time; It appears to work now.

  • If you put a subreport in the pageheader and the subreport is longer than a page, crystal might blow up!

Asp.Net, DropDownList, AutoPostBack and Google Chrome

I've a simple page (framework 3.5) and an UpdatePanel with a series of dropdownlist I want to populate asyncronously. All works fine in all major browsers (Opera, Safari, IE6, IE7, FF3), but not in Chrome.

Chrome seems to ignore the SelectedIndexChanged event who had to make the asynch request.

Anyone knows a simple workaround to this? Thanks!

EDIT: More Informations

As I say to Adam Lassek, the updatepanel refresh after the click to an asp:Button inside of it, but it doesn't work with the dropdown's SelectedIndexChanged event.

The updatepanel is set like:

<asp:UpdatePanel ID="updPanel" runat="server" UpdateMode="Always" ChildrenAsTriggers="true">

without Triggers specified, and the dropdows have sets AutoPostBack="true"

UPDATE: (and retagging)

After a few attempts I discover that it isn't a problem of the UpdatePanel, but it seems that the AutoPostback of dropdowns doesn't work properly, even in pages without ScriptManager and UpdatePanel... I'm sure that it is a problem concerning only this project, because if I start a new WebSite from scratch and replicate the structure of this, works fine in Chrome... I'm trying to remove step by step all the other things in the original project to find exactly what's the problem.

If anyone has some ideas in meantime....

From stackoverflow
  • This happens because MicrosoftAjax.js does browser detection, and it's incorrectly detecting Chrome as Safari. In order to fix this, you need to make the following changes:

    Add a new browser type

    Sys.Browser = {};
    Sys.Browser.InternetExplorer = {};
    Sys.Browser.Firefox = {};
    Sys.Browser.Safari = {};
    Sys.Browser.Opera = {};
    Sys.Browser.Chrome = {};

    Update the if-then logic to search for Chrome

    else if (navigator.userAgent.indexOf(' Firefox/') > -1) {
        Sys.Browser.agent = Sys.Browser.Firefox;
        Sys.Browser.version = parseFloat(navigator.userAgent.match(/ Firefox\/(\d+\.\d+)/)[1]); = 'Firefox';
        Sys.Browser.hasDebuggerStatement = true;
    else if (navigator.userAgent.indexOf(' Chrome/') > -1) {
        Sys.Browser.agent = Sys.Browser.Chrome;
        Sys.Browser.version = parseFloat(navigator.userAgent.match(/ Chrome\/(\d+\.\d+)/)[1]); = 'Chrome';
        Sys.Browser.hasDebuggerStatement = true;
    else if (navigator.userAgent.indexOf(' AppleWebKit/') > -1) {
        Sys.Browser.agent = Sys.Browser.Safari;
        Sys.Browser.version = parseFloat(navigator.userAgent.match(/ AppleWebKit\/(\d+(\.\d+)?)/)[1]); = 'Safari';

    Be sure to put the Chrome check before Safari. If you need help replacing the Framework script with your custom version, read this.


    I created a test page and put the following controls on it:

    <asp:ScriptManager ID="scriptManager1" runat="server" />
    <asp:UpdatePanel ID="panel1" runat="server" ChildrenAsTriggers="true">
        <asp:DropDownList ID="ddlTest" runat="server" AutoPostBack="true">
          <asp:ListItem Value="0" Text="Item 1" />
          <asp:ListItem Value="1" Text="Item 2" />
        <asp:Literal ID="litTest" runat="server" />

    And wrote the following codebehind:

    protected override void OnInit(EventArgs e)
        ddlTest.SelectedIndexChanged += new EventHandler(ddlTest_SelectedIndexChanged);
    void ddlTest_SelectedIndexChanged(object sender, EventArgs e)
        litTest.Text = "Selected: " + ddlTest.SelectedItem.Text;

    The Updatepanel works fine in Chrome, with no modification of the Ajax library. So, I think something else is causing this problem. You're going to need to isolate the cause of the problem through a process of elimination. Start with something simple like this example, and work up to what you have a piece at a time.

    tanathos : I've tried your suggestion (and thank you for your answer), but it seems to not change nothing..I see that if I insert an asp:Button inside the updatepanel (that has ChildrenAsTrigger set to true),it works fine..but it doesn't work with SelectedIndexChanged of the DropDowns (only Chrome of course)..
    tanathos : I'll try as you say, thanks : )
  • There is a known incompatibility with Ajax.NET and Chrome & Safari 3.

    Small, quick tests can be deceptive because it will appear to work fine with the existing Ajax.NET library as is. This is because it manages to perform the first Ajax request and fails when that ends, so only when you try to perform the second Ajax action will you notice it has failed. If you put an UpdateProgress control on your page, you'll notice that after the first request your UpdateProgress control won't disapppear.

    Luckily, there is an answer!

    Recently there was a great post put up detailing what to do which you can find here:

    The general gist of it is that both Chrome and Safari 3 report themselves as WebKit in their userAgent strings.

    You need to add a little bit of javascript in to aid the Ajax.NET framework in recognising WebKit based browsers that looks like the following:

    if (typeof(Sys.Browser.WebKit) == "undefined") {
        Sys.Browser.WebKit = {};
    if (navigator.userAgent.indexOf("WebKit/") > -1 ) {
        Sys.Browser.agent = Sys.Browser.WebKit;
        Sys.Browser.version = 
            parseFloat(navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]); = "WebKit";

    You need to add that to a javascript file and reference it in your ScriptManager:

    <asp:ScriptManager ID="ScriptManager1" runat="server">
            <asp:ScriptReference Path="~/assets/javascript/WebKit.js" />

    Note that you can keep the WebKit.js in an assembly and reference that by using a ScriptReference tag similar to this:

    <asp:ScriptReference Assembly="Scripts" Name="Scripts.webkit.js" />

    Once you've done all that, if at all possible stop using WebForms and Ajax.NET and use MVC and jQuery :)

    Ole Lynge : Thanks! This solved my problem with paging a GridView inside an UpdatePanel in Chrome.
    Bayard Randel : "If at all possible stop using WebForms and Ajax.NET and use MVC and jQuery." Sage advice, but in the meantime, this fix works beautifully. Thank you kind sir.
  • It is not an appropriate suggestion to use MVC and jQuery instead of WebForms and ASP.NET AJAX. One should understand all the pros and cons of the technologies and approaches to choose from.

    First, MVC is a design pattern and has nothing to do with the particular frameworks mentioned. You can easily implement an MVC pattern with WebFroms. There are many different implementations of MVC for ASP.NET and WebForms.

    Second, jQuery, being a great JavaScript library, does not allow any integration with and does not leverage server side ASP.NET functionality, as opposed to ASP.NET AJAX framework that comes standard with the ASP.NET 3.5+ and fully utilizes ASP.NET features, such as server side mark-up, ScriptManager control, server-side script combining, localization and globalization, etc.

    Third, jQuery can be easily used in conjunction with ASP.NET and ASP.NET AJAX frameworks thus enhancing client-side programming. Microsoft has announced that jQuery will be shipped with the next ASP.NET 4.0 and for now you can just add it to your project manually.

  • I just ran into a similar problem today (although I wasn't using Ajax), and found a fix. See the third comment down on this blog post.

  • I have the same problem. I've got a dropdown inside a ajax postback and need to do an update when the selected index changes. It works with a basic page in a new project too.

    After adding the Webkit script mentioned in the other answers I still get the same problem and when running the javascript debugger in Chrome I get this error:

    uncaught exception ReferenceError: evt is not defined


    I found that in my case it was a CustomValidator that was interfering with the event handler. Setting EnableClientScript to false fixed the issue.

  • You can check out solution