How to Serialize a Collection

In a fragment of a code I’m working on, I must serialize a collection of links into an XML file. Fortunately, .NET Framework provides a quick XmlSerializer class to do the dirty job for you.

Well, almost…

The problem

If you try to serialize a class derived from CollectionBase, the Serialize method will throw a nasty exception.

The workaround

Use a container class, put the CollectionBase-derived class as a property, decorate this property with XmlArray and XmlArrayItem tags.

[Serializable]

public class CollectionContainer

{

private LinkCollection _links= new ColeccionEnlaces();

[XmlArray(“Links”)]

[XmlArrayItem(“Link”,typeof(Link))]

public LinkCollection Links

{

get

{

return _links;

}

set

{

_links = value;

}

}

}

Data Caching in SharePoint 2003

If you are used to the ASP.NET Cache object, you can use it in SharePoint (after all, it’s just an ASP.NET extended application). However, the Web part framework encapsulates this Cache and enables you to have per-webpart and per-user cache. How? After a little bit of investigation I’ve found it out. The reason was to find out how to remove a cached item outside the webpart.

After inserting a key/value pair using SharePoint’s PartCacheWrite method, SharePoint creates an entry in the Application Cache object (remember that the cache is shared among all the users), with a custom prefix attached to your own key. This prefix includes:

  • SharePoint webpart key:
    • Request URL
    • Creation date and time of the containing WebPartPage
    • Webpart UniqueID
  • User Security Identifier (SID) in hexadecimal format
  • “?” character which marks the end of SharePoint prefix
  • Your own key

 

So, let’s say you’ve cached an object within a webpart named “_ctl6” (default names for no-name webparts) with a key of “abc” and that the webpart is placed under the URL “/C7/Informatica/default.aspx”. The real cache key is:

/C7/Informatica/default.aspx09/27/2006 11:49:49_ctl60x01050000000000051500000069CE0AC3F42CDE9F7071B56E87080000?abc

It can be broken into the key components:

/C7/Informatica/default.aspx09/27/2006 11:49:49_ctl60x01050000000000051500000069CE0AC3F42CDE9F7071B56E87080000?abc

is composed of:

  • /C7/Informatica/default.aspx
    (Request URL)
  • 09/27/2006 11:49:49 (Creation date of the URL page in SharePoint server time)
  • _ctl6
    (UniqueID of the webpart)
  • 0x01050000000000051500000069CE0AC3F42CDE9F7071B56E87080000
    (User SID in hex format)
  • ? (separating character)
  • abc
    (your custom key)

     

It also inserts two dependency strings, used to invalidate per-webpart or per-user cached data. The names of those keys are Depend_String and Depend_String_Per_User, followed by a SharePoint webpart key:

Depend_String_Per_User/C7/Informatica/default.aspx09/27/2006 11:49:49_ctl7