Monday, December 1, 2008

Persistor of a Serializer

We had this situation in my last project where we wanted to have some of our objects to get easily serialized into a specific table. Therefor we had to add up to the Serializer an new generic class that uses the Serializer to get the sream to put into a table.
In this example we have several classes like Article, Order, etc. and we wanted to give them a specific addition that would implement the Save and Load for all these classes. So we wanted to have something like this :

[Serializable]
public class Article : Persistor


and then later use it as follows:

// Read the last saved Article filter
private Article filter = Article.Load();

...
// and do something with it and finally save it back to Database

this.filter.Remove(e.Item.Key);
...
this.filter.Save();

Well, to achive that we implemented the Persistor class as follows:



using System;
using System.Collections.Generic;

/// <summary>
/// Provides the persistance methods for the filter classes.
/// It reads and writes the content in an xml format into the Filter table
/// </summary>
/// <typeparam name="T">The type of the filter. This type should derive from Persistor&lt;T&gt; and have an empty constructor</typeparam>
[Serializable]
public class Persistor<T>
where T : Persistor
<T>, new()
{
/// <summary>
/// Saves this filter as the default filter for the current user.
/// </summary>
public void Save()
{
// Serialize the current filter instance
Serializer<T> serializer = new Serializer<T>();
string xml = serializer.Serialize(this as T);

// The filter class is a data class that handles the saveing of a record
Data.Tables.Filter filter = Persistor<T>.LoadFilter(true);

// Actual save to database
filter.Value = xml;
filter.Save();
}

/// <summary>
/// Loads the default filter for the current table and user.
/// </summary>
public static T Load()
{
Tables.Filter filter
= Persistor<T>.LoadFilter(false);

// Deserialize
T currentFilter = null;
if (filter != null && !string.IsNullOrEmpty(filter.Value))
{
Serializer
<T> serializer = new Serializer<T>();
currentFilter
= serializer.Deserialize(filter.Value);
}
else
{
currentFilter
= new T();
}

return currentFilter;
}

/// <summary>
/// Loads the Filter for the current user and table from the database.
/// </summary>
protected static Tables.Filter LoadFilter(bool createNew)
{
string tableId = typeof(T).Name;
int userId = UserContext.Current.User.ID;

// Load current filter, if available, otherwise create a new filter instance.
Tables.Filter filter = Tables.Filter.GetForUserTable(userId, tableId);
if (filter == null && createNew)
{
filter
= new Data.Tables.Filter();
filter.UserID
= userId;
filter.TableID
= tableId;
}

return filter;
}
}

No comments: