Monday, March 7, 2011

Serialize ASP.NET Control collection

I've been tasked with converting an existing ASP.NET site from using InProc session management to using the ASP.NET State Server.

Of course what this means is that anything stored in the Session must be serializable.

One of the most complicated pages in the app is currently storing an ASP.NET control collection to the Session. This is failing miserably because the controls cannot be serialized automatically.

Short of totally rewriting how the page works to prevent the need for storing the control collection in the Session, does anyone have a trick/solution for making the collection serializable?

From stackoverflow
  • The first answer that comes to mind is to do a partial rewrite (I don't think there's going to be an easy answer to this). If it's a small number of control types, write your own controls that inherit from those controls and also implement ISerializable. Then, using search and replace, replace the page's controls with your versions. If you are using a large number of control types, you might spend more time extending the standard types than you would refactoring the page.

    The work is going to be in the serialization and deserialization of the controls when you initialize them, to make sure you're capturing what you need (the TextBox values, the IsSelected, etc.).

    This is obviously a hack, but if your priority really is not rewriting the functionality of that particuar page, this might work for you. Then, of course, you need to add this solution to the "technical debt" that your application is accruing, to make sure it's always on someone's radar to refactor at some point.

  • Don't store control collections in session state. Tess has a lot of articles about this, for example this one.

  • Rewrite the page. You'll thank yourself later. There are sure to be other problems if the original "programmer" (and I use that term loosely here) thought it was a good idea to store a control hierarchy in session.

    Tim Cavanaugh : Thanks for the suggestion, I came to this realization as well and spent a large part of last week redo-ing the page so it doesn't need to store the controls in the session at all. The re-write seems to be working well.
    Robert C. Barth : Glad to hear it. Sometimes you just have to bite the bullet and hack through the overgrown underbrush with a giant machete until things look right. :-)

0 comments:

Post a Comment