Tuesday, 29 April 2008

Firefox refresh viewstate updatepanel bug hell!!!

Have you ever noticed that when you click the Refresh button in Firefox, any form values you have filled in on the screen are retained after the refresh? Firefox is automatically altering these values at the end of the request, presumably as a convenience to you, the user. Hence the DOM and the page source are out of sync immediately after the refresh. There is nothing you can do to disable this behaviour within Firefox.

For the average web app, this is a desirable feature. But when combined with the ASP.Net viewstate model, it is anything but desirable, as ASP.Net uses a hidden form field to store serialized viewstate information.

The specific bug I have encountered is when using ASP.Net in conjunction with the built-in validation controls and AJAX. When using validation controls, if viewstate does not match that which last left the server, an error is produced :
The state information is invalid for this page and might be corrupted.

Because Firefox attempts to fill in the current form with current values after a refresh, a new viewstate, representing a fresh page, can be overwritten by an old viewstate (the result of 1 or many AJAX postbacks changing control states since the last "fresh" page load.)

The easiest solution I have found to this problem thus far is to change the form ID with each (non postback) page load. This will fool Firefox into thinking the form is different, and as such all values (including viewstate) will get their values from the incoming HTML rather than the browser's previous state.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not Me.IsPostBack Then

        Me.form1.ID = "form" & Date.Now.Ticks().ToString()            

End If

End Sub

The only potential problem you could encounter with this solution is where the form ID has been hardwired in your application, either in client side script or server side code. This can be mitigated by always using myForm.clientID when referencing the form's ID. This is good practice in any case.

Hopefully this will help others having the same problems I was.

This solution will not work when using a Master Page. Use the solution suggested here instead (change form ID in pageLoaded AJAX event).

For those interested, the offending code is here in System.Web.UI.HtmlControls.HtmlForm.UniqueID: (from Reflector)

Public Overrides ReadOnly Property UniqueID As String
      If (Me.NamingContainer Is Me.Page) Then
         Return MyBase.UniqueID
      End If
      Return "aspnetForm"
   End Get
End Property

Wednesday, 23 April 2008

LINQDataSource Many-to-many filtering Hell!!

OK new LINQ is all wizzy do and great at Teched and Microsoft demo's etc, but what about when you want to do something real world? Like using drag-and-drop to build an asp.net form with a gridview for editing a many-to-many child table?

As it says somewhere in the bowels of the stupendous MSDN help, LINQDataSource is only for use with a single table: the where clause can only refer to fields within that table or an error will be generated.

I looked all over the net and could find no simple way to implement Northwind's Order - OrderDetails - Products example using LINQDataSource to show an editable gridview containing all the products for a given order - i.e. productList.aspx?orderID=123.

The only (relatively) easy method I could figure out was this:

  • Create your LINQ DBML file in the usual way by dragging on all tables from the Server Explorer.
  • Do a compile here or you will be frustrated in the next step...
  • Add a LINQDataSource(LDS) and Gridview to the form and wire up the LDS to your Products table and the GridView in the usual Dev for Dummies way on the designer.
  • Leave the WHERE clause of the LDS empty for now...
  • Make sure you tick the * in the SELECT fields, otherwise the cast (below) won't work!!
  • Make sure you tick enable update, delete, insert or it won't work (don't ask me why).
  • Add an event handler for your LINQDataSource's Selected event. The e.Result parameter gives you access to the returned records as a generic list that you can remove items from, yay!
  • Add the code below to the event handler...
  • Voila! Almost drag and drop - only a little bit of code required.

    Protected Sub LinqDataSource1_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.LinqDataSourceStatusEventArgs) Handles LinqDataSource1.Selected

' Cast result to generic list of (LINQ) Products

        Dim prodList As List(Of Product) = CType(e.Result, List(Of Product))

' iterate through each Product and remove any that aren't associated with the passed OrderID

        For Each aProduct In New List(Of Product)(prodList)

Dim keepProduct As Boolean = False

            ' Asking for the Order_Details will cause a new request to SQL for these rows

            For Each anOrderDetail As Order_Detail In aProduct.Order_Details

If Request("orderID") IsNot Nothing AndAlso anOrderDetail.OrderID = CInt(Request("orderID")) Then

                    ' We have a match, this product is in the request order, keep it!!

                    keepProduct = True

                    Exit For

                End If


            If Not keepProduct Then

                ' Remove it from e.result list.


End If


    End Sub

Transparent GIFs in .Net hell!!

There is a very useful article here about creating transparent gifs in .net, but there are (I think) a couple of points missing, which I'll detail here in case it saves anyone wasting a day scratching their head like I have...

GDI+ Version
It would appear that there are differences between versions 1.0 (file version 5.x) and 1.1 (6.x) of Microsoft's GDI+, in the way that they encode a non-indexed bitmap (eg 32bppARGB) into an indexed format such as Format8bppIndexed.

The problem comes with the converted palette; on my development machine (gdiplus.dll version 6.x), I appeared to be getting a custom palette based on (maybe?) the colours in the converted image (image quantization).

On a Windows 2003 server, running gdiplus.dll 5.x, I would get the standard palette as per Bob Powell's article.

This could potentially cause headaches for you if (as I did) you released a web project to production and it didn't behave as it did on your dev machine...

There appears to be very little documentation on this change between gdi+ 1.0 and 1.1, but what links I found I've added below.

Altering GIF palette
When I tried to adapt Bob's algorithm to make my gif's background transparent, I ran into a problem. Sometimes the algorithm would work, sometimes it wouldn't. At this stage, the only conclusion I can draw is that you must remove any transparent colours from the palette before attempting to set a new transparent colour... i.e, don't do this (variation of Bob's code):

'copy all the entries from the old palette removing any transparency
Dim n As Integer = 0
Dim c As Color
For Each c In cp.Entries
If n = idxToMakeTransparent Then
ncp.Entries(n) = Color.FromArgb(0, c)
ncp.Entries(n) = Color.FromArgb(255, c)
End If

n += 1
Next c

're-insert the palette
bm.Palette = ncp

I think that this doesn't work if one of the colours is already defined as transparent (as seems to be the default in old gdi+ (1.0). This is all pure speculation at this point!

Good luck with your hacking.


Wednesday, 9 April 2008

AvalonCab Arcade Frontend Released!

I have now released the beta version of my MAME (and generic emulator) frontend for arcade cabinets. It is built on top of Microsoft's new Windows Presentation Framework, so can take advantage of declarative GUI design with XAML, making the interface very flexible.

The idea was to allow rapid navigation to any game within the database, whilst showing videos and/or screenshots of the selected game.

I have released the project as open source, so as anyone else can make modifications or improvements. It is my hope that someone will tidy up all the loose ends and maybe add all the missing functionality that will make it a "complete" system.

You can download the windows executable or source code here www.avaloncab.info