PostSharp4ViewState is a plugin for PostSharp AOP framework by Gael Fraiteur. Its goal is to simplify state management in ASP.NET pages and controls using declarative programming concept.

How do I use it?

Whenever you want to store some value between postbacks you decorate it with an anttribute - namely PersistAttribute. You can store both property and field values this way. The attribute lets you decide whether value should be stored in ViewState or in ControlState. The difference is that storing ViewState can be disabled to decrease page size. Storing control state can not be disabled externally, but it should be explicitly enabled by the control itself.

How does it work?

PostSharp4ViewState main component is an advice provider which searches for types with fields/properties decorated with Persist attribute. For each such type, a weaving process is initiated as follows:
  • If there is one or more fields/properties to be stored in ViewState, LoadViewState and SaveViewState are created or modified
  • If there is one or more fields/properties to be stored in ControlState, LoadControlState and SaveControlState are created or modified. Also OnInit method is created if it does not exists and a call to Page.RegisterRequiresControlState(this) is added
Methods for handling storing in ViewState and ControlState are in fact identical, differing only by name. Their generation is conducted using following rules:
  • If Save*State method exists new code is added after existing. It stores values of decorated fields/properties in object[] array and puts it together with resut of existing code in another object[] array.
  • If Save*State method doesn't exist it is generated as if it existed and contained only a call to base.Save*State.
  • If Load*State method exists new code is added before existing. It casts passed value to object[] array and uses second element (casted as another object[]) to initiate decorated fields/properties. First value is passed to existing code.
  • If Load*State method does't exist it is generated as if it existed and contained only a call to base.Load*State.

How about performance?

PostSharp4ViewState is as fast as your hand-written code! It does not use Laos but pure low-level PostSharp so no additional objects are being instantiated because of using aspects. The only effect is pure code to save and load persistent values. You can use Reflector to disassemble the dll and make sure there are no excess code in your classes.

Last edited Sep 20, 2008 at 3:37 PM by SzymonPobiega, version 2


No comments yet.