0. Public repository

This project is now hosted on Github, the link is here. The project name is Jot (as in Jot down). This will be the main repository for the project and will contain the most up to date version of the code. Please feel free to leave comments and issue reports, fork the repository and all that good stuff.

1. Introduction

A common requirement for both web and desktop applications is persisting some elements of the application state between work sessions. The user starts up an application, inputs some data, changes some settings, moves and re-sizes windows and then closes the application. The next time they start the application it would be very nice if the settings they entered were remembered, and UI elements showed up as they were before the application was closed.

This requires the application to persist this data (most likely in a file) before it shuts down, and applies it when it starts up again. For a desktop application, this data could include locations and sizes of movable and re-sizable UI elements, user input (for example last entered username), as well as application settings and user preferences.

After coming across this requirement more times than I care to remember, I decided to spend some time and make a reusable library that automates most of the work of persisting and applying settings. The entire library is a few hundred lines of code and is not very hard to understand.

In this article I present the solution I came up with and describe what it can do, what value it provides, how to use it and the basic ideas behind it.

2. Platforms

This library can be used for WPF, Windows Forms and ASP.NET (WebForms/MVC) applications. The required version of .NET is 4.0 or higher.

3. Reasoning and motivation behind this

The usual approach to persisting settings in a .NET application would be to use .config and .settings files via the built in configuration API. It allows for type safe access to configuration data, defining complex configuration settings, separation of user-level and application-level settings, run-time reading and writing, as well as manual modification of the settings via an XML editor.

It does however involve a little too much ceremony in my opinion, with stuff like sub-classing ConfigurationSection for complex settings and hacking when handling plug-ins with their own settings. Also, (to my knowledge) the Visual Studio tool that generates settings classes does not allow you to intervene in what it generates (suppose you want to implement INotifyPropertyChanged in your settings class).

But the biggest problem is that maintaining and using a large set of settings this way is tedious. The settings objects are usually not the ones that use the data, they just store data from all over the application. This means that to use this data you must write code that copies the data from settings to the appropriate objects and later writes updated data back again to the settings some time before the application closes.

Suppose your application has several re-sizable and movable UI elements, and you want to remember and apply these sizes and locations the next time the application starts. Suppose you have 10 such UI elements, and for each of those you want to persist 4 properties (“Height”, “Width”, “Left”, “Top”) - a total of 40 properties just for this. You could add all those properties to your settings file, and write code that applies them to the corresponding UI element, then write additional code that updates the settings before the application closes. But manually adding settings and writing that code would be rather tedious and error prone. It would be much nicer if we could just declare that we want certain properties of certain objects tracked and have it taken care of more-or-less automatically.

The main purpose of this library is just that - to enable you to persist and apply data directly on the object that uses it, and to do so in a declarative manner with minimal coding (decorate a property with an attribute).

In the following chapters I demonstrate the use of the library, and discuss it's implementation.

4. Terminology

In this article I use two terms which I think might need explaining:

tracking a property - saving the value of an object's property before the application shuts down, and identifying the object and re-applying the saved value to it's property once the application starts up again.

persistent property - a property that is being tracked

5. Usage

The SettingsTracker is the class that coordinates tracking. It takes care of applying any previously stored data to your objects, and it stores new data from the desired objects to a persistent store when appropriate.

When creating it, you need to tell it how to serialize data and where to store it. This is done by providing it with implementations of the ISerilizer and IDataStore interfaces. For example:

Now we have a SettingsTracker instance which can track properties. It will use binary serialization to serialize data, and store the serialized data in a file. We should make this instance available to the rest of the application preferably by storing it in an IOC container, or for the sake of simplicity perhaps via a public static property.

All we need to do now is to tell it which properties of which object to track. There are several ways of doing this.

5.1. Example scenario 1: Persisting a WPF window location and size

The idea is best illustrated by an example. Consider the scenario where you want to track the location, size and WindowState of a WPF window. The work you would need to do if you were using a .settings file is shown on the left, while the code you would need to write with this library to achieve the same effect is shown on the right:

In this example the static property Services.Tracker holds a SettingsTracker instance. This is for simplicity sake, a better way would be to keep the instance in an IOC container and resolve it from there.

The amount of work required for option A is quite substantial, even for a single window. Most likely it would be done using copy-paste and would be quite error prone and tedious work. If we had to track many controls throughout the application, the .settings file and intellisense would quickly become cluttered with a jungle of similarly named properties.

In option B we just declare which properties of the main window we want to track, and give the main window a tracking identifier so we don't mix it's properties up with properties of some other object. Calling ApplyState applies previously persisted data (if any) to the window, while new data is automatically persisted to the store before the application closes. No writing code that copies data back and forth.

We can also specify the list of properties to track by using a [Trackable] attribute on the class and/or it's properties provided we control the source code of the class. I demonstrate this in the next example.

There is also a way to specify the list of properties to track using the [Trackable] attribute. I applied it to the class to specify that all public properties of this class should be tracked. To exclude a property, we would decorate it with [Trackable(false)]. If the class is appropriately decorated with this attribute, we can skip explicitly registering properties with the AddProperties method, like so:

Services.Tracker.Configure(settingsObj).Apply();

Note that the settings class does not need to inherit any specific class, it can subclass whatever we like, and implement interfaces as we see fit (e.g., INotifyPropertyChanged).

For extra coolness, if we use an IOC container to build up our objects, we can use it to set up tracking for all objects it builds up. Most IOC containers allow you to add custom steps when injecting an object with dependencies. We can use this to add tracking automatically to any object that implements ITrackable (just an empty „marker“ interface to mark which objects to automatically track). In that case, all a class needs to do to have its properties persisted is apply tracking attributes to itself and/or it's properties. The rest of the work will be done automatically by the extension we added to the IOC container.

6. Benefits

So what are the benefits of all this? To sum it up:

less code - you just specify what properties of what object you want to track, you don't need to write code that copies values property-by-property back and forth from settings to other objects

you don't have to explicitly add new properties in the .config or .settings file (and you don't have to come up with a name for each property of each object you want to persist)

you specify the list of properties just once (when configuring tracking), instead of three times (1- when defining the settings in a .config or .settings file. 2- when copying data from settings to other objects, and 3- when copying data back to settings)

it's declarative - you can use attributes (Trackable and TrackingKey) to configure what needs to be tracked and to identify the object

if using an IOC container you can apply tracking with virtually no code aside from attributes on appropriate properties - more on this in the "IOC integration" chapter

for web applications it can make your controller/page properties stateful

For details on how all this is implemented, and how it can be used and customized, please read on...

7. The implementation

As with any complex problem, a sensible way to approach it would be to break it down into simple components. My approach here uses two basic components: serialization, and data storing mechanisms. These are the basis of my persistence library. Here is the class diagram of the library:

7.1. Building block 1 - Serialization

OK, so first things first - in order to store any data, we need to be able to convert the data into a persistable format. The obvious candidates for this format would be a string and a byte array. Byte array seems to be the lowest common denominator for data so I would suggest we use that. Let's declare the interface for serializers:

There we go. Now we have a class which can take on object graph and turn it into a series of bytes. Serialization is tricky business though, and regarding this implementation I should note that the use of BinaryFormatter does impose certain limitations: serialized classes must be decorated with the [Serializable] attribute, events must be explicitly ignored (via [field:NonSerialized] attribute), complex object graphs with circular references may break the serialization. That being said I have used this implementation in my own projects in several different scenarios and have yet to run into serious issues. Other implementations of the ISerializer interface might for example use:

Like the ISerilizer interface, this interface is also rather minimal. Classes implementing it enable us to store and retrieve (named) binary data to/from a persistent location. Candidate locations to persist data might include:

Depending on the location of the file we choose to use, the data will be persisted in a user specific location or a global location. For instance if the file is located somewhere under %appsettings% it will be user specific, while if it is located under %allusersprofile% it will be global for all users.

So now we can take an object, get its binary representation, and store that in a persistent store. These are all the building blocks we need. Let's move on and see how we can use them.

* %appsettings% and %allusersprofile% refer to environment variables.

7.3. ObjectStore class

Using these two building blocks, we can easily create a class which can store and retrieve entire objects - an object store. To distinguish between objects in the store we need to provide an identifier for the object when storing/retrieving it. The code for the object store class looks like this:

The implementation of the ObjectStore is pretty straightforward. It will use any implementation of ISerializer and IDataStore you give it (those familiar with DI/IOC will recognize constructor injection). One more thing you have perhaps noticed is the dictionary which is there to handle object identity (1 key = 1 object) and caching.

So, instances of this class can save entire objects in a persistent location. This can be rather handy on its own, but we can do more...

7.4. SettingsTracker class

Suppose we want to persist the size and location of the main window of our application. It would not make sense to persist an entire window object just to maintain its size and location (even if it could be done). Instead we have to track just the values of specific properties.

As it's name suggests, the SettingsTracker class is the one that orchestrates the tracking of the properties of objects. This class uses the previously described ObjectStore to store and retrieve the values of tracked properties.

To track your object you must first tell the SettingsTracker instance what properties of the target you want to track, and when to persist those properties to the store. To accomplish this you must call the Configure(object target) method. This method returns a TrackingConfiguration object which you use to specify how to track your object.

Here is an example showing how to configure persisting the size and location of a window:

Here we fetch the configuration for tracking our window, we tell it which properties to persist, we specify the identifier (key) for the target object, and lastly we specify automatic mode which means persist the properties just before the application closes. If you don't like using hard coded strings when specifying properties, you can instead use the other overload of the AddProperties method like so:

This overload analyzes the expression trees to determine the correct properties, thus eliminating the need for hard coded strings.

The SettingsTracker stores a list of all TrackingConfiguration objects it creates. It makes sure that there is exactly one configuration object per target, so each time you call Configure() for the same target, you always get the same TrackingConfiguration object.

Applying state: After you have configured what properties you want to track, you can apply any previously persisted state to those properties by calling the tracker.ApplyState(object target) method.

Storing state: In the configuration, you can set the tracking mode to be manual or automatic. If you have chosen the automatic tracking mode (this is the default), the values of the target's properties will be stored just before the application closes (or before the session ends for web apps). If, instead, you want to store them at some earlier time, use manual mode, and explicitly call the tracker.PersistState(target) method when appropriate.

When persisting a target object's properties, the settings tracker will:

locate the TrackingConfiguration for the target

for each property that is specified in the target's configuration:

construct a key by concatenating the target object type, the target's tracking key, and the property name ([TargetObjetType]_[TargetObjectKey].[PropertyName]).

get the value of the property using reflection, and save it to the store using the constructed key as the identifier.

So for the window in the previous example the PersistState method would store 5 objects to the ObjectStore and the keys would be:

DemoTracking.MainWindow_TheMainWindowKey.Height

DemoTracking.MainWindow_TheMainWindowKey.Width

DemoTracking.MainWindow_TheMainWindowKey.Left

DemoTracking.MainWindow_TheMainWindowKey.Top

DemoTracking.MainWindow_TheMainWindowKey.WindowState

Note: Since there will only ever be one instance of the MainWindow class in the application, we didn't really have to specify the key for the window object (using the SetKey method) since it is already uniquely identified by it's class name.

The ApplyState method does almost the same thing as PersistState but moves the data in the opposite direction, from the store to the object's properties.

Ok, let's get back to the code, the following is the code for the TrackingConfiguration class:

This class uses method chaining - each method returns the same TrackingConfiguration object thus facilitating further method calls. The implementation is mostly straightforward. One thing to mention is the AddMetaData method - it is used when tracking is configured via attributes.

Note that the configuration object stores a WeakReference to the target so it does not make it live longer than it needs to.

Depending on the type of application (WinForms, WPF, ASP.NET), the WireUpAutomaticPersist method subscribes to the appropriate event that indicates when targets with PersistMode.Automatic should be persisted.

All the other important methods (Configure, ApplyState, and PersistState) have already been described...

7.5. Configuring tracking by attributes

An alternative way to configure tracking is to use the Trackable and TrackingKey attributes.

Instead of calling configuration.AddProperties([list of properties]) for a target, we can mark the relevant properties of the target's class (or the entire class) with the TrackableAttribute. Also, instead of calling configuration.SetKey(“[some key]”), we can mark a property with the TrackingKey attribute, which will cause that property to behave like an ID property – the value of this property will be the identifier (key) of the target object.

These two attributes allow us to specify which properties to track and the tracking key at the class level, instead of having to specify this data for every instance we want to track. Another benefit to this is that it enables automatic tracking if we are using an IOC container- we simply hook into the container so that after it has injected dependencies on an object we call AddMetadata and AppySettings if the object implements the marker interface ITrackable.

7.6. The ITrackingAware interface

When defining a class, it’s not always possible to decorate the properties with attributes. For instance, when we subclass System.Windows.Window we don't have control over the properties that are defined in it (unless they are virtual) because we don’t control the source code of the Window class, so we can't decorate them with attributes. In this case, we can, instead, implement the ITrackingAware interface which looks like this:

///<summary>/// Allows the object that is being tracked to customize
/// its persitence
///</summary>publicinterface ITrackingAware : ITrackable
{
///<summary>/// Called before applying persisted state to the object.
///</summary>///<paramname="configuration"></param>///<returns>Return false to cancel applying state</returns>bool OnApplyingState(TrackingConfiguration configuration);
///<summary>/// Called after state aplied.
///</summary>///<returns></returns>void OnAppliedState();
///<summary>/// Called before persisting object state.
///</summary>///<paramname="configuration"></param>///<returns>Return false to cancel persisting state</returns>bool OnPersistingState(TrackingConfiguration configuration);
///<summary>/// Called after state persisted.
///</summary>///<paramname="configuration"></param>///<returns></returns>void OnPersistedState();
}

This interface allows us to modify the tracking configuration before applying and persisting state, and even to cancel either of those. This can also come in handy for WindowsForms, where Forms have bogus sizes and locations when minimized – in this case we can cancel persisting a minimized window.

7.7. IOC integration

Now for the cool part... When using an IOC container (Unity/Castle Windsor/Ninject/Lin Fu etc...) in an application, a lot of objects are either created or built up (have their dependencies injected) by the IOC container. So why not have the container automatically configure tracking and apply state to all trackable objects it builds up!

This way, if your object is going to be built up by the container, all you need to do to make a property persistent is:

make sure the class that defines the property implements the empty marker interface ITrackable and decorate the property with [Trackable], - or -

implement the ITrackingAware interface in the appropriate way

The ITrackable interface has no members, and serves only as a marker to let the IOC extension know you want to automatically track objects that have it. I opted to use an interface instead of an attribute for this because checking for the existence of an attribute is a little bit slower than checking for an interface.

Note: ITrackingAware already inherits from ITrackable.

So far, I have used this approach with Unity and Ninject but I suspect it should not be hard to do with other IOC containers. Here is the code for the UnityContainerExtension which automatically adds tracking to objects:

The library also contains derived TrackingExtension classes specifically for WPF (WPFTrackingExtension) and WinForms (WinFormsTrackingExtension) which, when added, automatically configure tracking for Windows (WPF) and Forms (WinForms) respectively. That way, all Windows/Forms that the UnityContainer resolves will have their sizes and locations tracked with no effort (except for registering the approprieate TrackingExtension with the UnityContainer).

8. What about web apps?

In web apps, objects have a very short lifespan indeed. They are created when the server starts processing a request and discarded as soon as the response is sent. With the exception of manually storing data on the server (for example by using the Session store or user profiles), the server does not keep any application state. Instead, (any) state is passed arround from client to server and back again with each request-response (inside the querry string, form data, cookies etc...).

The "Session" object can, for example, be used to maintain state but it's clunky, and the compiler can't ensure type and name safety of the data inside it.

Using this library in web applications however allows for having ASP.NET pages and MVC controllers whose properties seem to "survive" between postbacks. Depending on the IDataStore implementation used, the data can be stored in the Session state, an ASP.NET user profile or somewhere else. We don't need to do anything else but decorate the desired properties with the [Trackable] attribute, and ensure that the page or controller is built up using an IOC container with an extension for managing tracking. Using IOC for resolving Pages and Controllers can be done with a custom ControllerFactory (for MVC) or with a custom IHttpModule (for regular ASP.NET) – I've included demo apps for both flavours of ASP.NET with comments on the important parts. So let's see how we could use this library to handle counting the number of visits to a page (MVC example).

name safety (no need to worry about naming the data in the session store when saving/retrieving)

type safety (no need to cast when retrieving data from the session store)

8.1. Configuring tracking in ASP.NET WebForms

In order to enable this behavior in ASP.NET (WebForms), I have created a custom IHttpModule so I can do stuff before and after a page is processed. The module takes an IUnityContainer reference in it's constructor and does the following:

Adds the tracking extension to the IOC container (so every object the container creates or injects into gets tracked if it implements the ITrackable marker interface)

Before the HttpHandler (the ASP.NET page) starts executing, it uses the IOC container to inject it with dependencies (and applies tracking to it and any other objects that are created in the process)

After the handler (the ASP.NET Page) is done processing, it calls PersistAutomaticTargets on all SettingsTrackers that are registered in the container.

Since the module needs a reference to the IUnityContainer in it's constructor, it needs to be created in code (instead of in app.config). This must be done in the Init() method in the global.asax file, like so:

8.2. Configuring tracking in ASP.NET MVC

In MVC, the controllers are not handlers, so the HttpModule approach is not applicable. Instead, the dependency injection and tracking can be set up using a custom controller factory. I've included one in the library and here is what it looks like:

The controller factory also needs to be set up in the Init() method in global.asax, because it is subscribing to the PostRequestHandlerExecute event which can only work during Init. The global.asax file might look like this:

Now all we need to do is decorate properties we want to be persisted with [Trackable] and implement the ITrackable interface in the controllers. You may have noticed I have registered more than one settings tracker here. The brings me to the last point of interest...

9. Multiple trackers (named trackers)

There are times when you need to store some data e.g. at the user level, and other data at the machine level, or perhaps at the session level. In this case, we can create multiple trackers, give each one a name, register them in the IOC container by name, and specify the tracker name in the Trackable attribute. An example is shown in the MVC demo, but here is what specifying the tracker name looks like:

I've included an example of using multiple trackers in the ASP.NET WebForms demo application where some properties are tracked on a per-user level, and some are tracked on a per-session level.

10. The demo apps

In the desktop demo apps I have used the tracking library for persisting UI state, as well as persisting application settings (without using the standard .NET configuration API). Note that I had no problem implementing INotifyPropertyChanged in one of my settings classes. If my application was plugin-enabled I would also not have any problems allowing the plugins to have settings of their own. In the demo, there is one app that uses Unity IOC Container, and one that doesn't.

I have also included a ASP.NET WebForms application, and a MVC application with an example of using multiple trackers. The apps use ASP.NET user profiles with a aspnetdb.mdf file for storing user data. Depending on the SQL server you have installed, you may need to adjust the connection string in the web.config for the demos to work.

11. Conclusion

The work of saving settings and applying them to concerned objects involves a lot of copying data back and forth, and can be quite monotonous and error prone. In this article I aimed to present a more declarative approach in which you only specify what needs to be persisted and when, and have the copying (the "how") taken care of automatically. This approach results in a lot less effort, code, and repetition.

Share

About the Author

I have been an a(tra)ctive software developer since 2005 mostly working on .NET. Currently living and working in Zagreb Croatia. I have earned my masters degree in Computer Science at the Faculty of Electrical Engineering and Computer Science in Zagreb in 2006.

I have two questions: - Can you provide a small example of a Windows Forms App? (VB.NET or C#) - How to track one or more user control's properties dragged on main form an external project (dll) with your library in the same xml file (an example should be appreciated)?

1. Yes, I will add a WinForms example and a new chapter about using this in ASP.NET when I have the time.

2. You distinguish between instances of the same class by the Key, much like objects that are persisted to the databse are distinguished by some ID property. You specify the key at the instance level by calling SetKey for each instance's tracking configuration, or you can do it at the class level by using the [TrackingKey] attribute or by implementing ITrackingAware. Ill probably upload an example some time next week so drop by later on...

I would recomment though if you track UI controls that you only track their UI-related properties, not the user data - for instance it would be better to track a Customer object's Name property, that to track the text property of the Textbox that displays it.

One more note: in the source I uploaded there is a bug so you can't use the AddProperties(()=>textbox1.Text) overload, it will throw an exception, but I will upload a fixed version when I have the time, and ofcourse you can fix it on your own if you feel like it

Thanks I did wince a little bit when I suggested cookies as a datastore given the network traffic implications. It's been a while since I last dabbled in web development so I hadn't even heard of profiles until I visited your links. You are in fact right, it would be quite easy to implement an IDataStore that uses profiles and it seems like a better approach than cookies.

On a related matter - it would also be easy to implement an IDataStore that uses session state (or TempData). In ASP.NET MVC a custom ControllerFactory could be used to add DI and tracking to all controllers. This would in effect allow the controllers to have stateful properties (they would just need the [Trackable] attribute). I think this might be a nice feature. Seems preferable to copying data back and forth from TempData manually. I'd like to hear what do you think about this, could it be a good idea?

You could still use profiles for storage, as the provider architecture is not limited to ASP.Net forms applications.

Since there are many provider implementations for various databases, and other backends, it kind of makes sense to build on this architecture, and for what it's worth: It also works well with Sharepoint.