While developing a multi-threaded Web Application, I had the need to store my collections generated in multiple thread somewhere.
I tried the CACHE in .NET, however, threads do block the whole CACHE and notonly an item in the CACHE, so as usual, the solution is with XML.
Now, the key is how to come up with a simple and easy way to store any collection into XML without the need to have a seperate method for each collection I have in the application, the answer is typically Reflection.
I will show you a method that is capable of storing any collection implementing IList into XML:
public class Helper
{
public static void StoreCollectionInXML(IList list)
{
// Validate list
if (list == null)
throw new Exception("Collection cannot be null");
if (list.Count == 0)
throw new Exception("Collection cannot be empty");
// Create XmlTextWriter
string filePath = HttpRuntime.AppDomainAppPath + "\\XML\\" + list.GetType().Name + ".xml";
XmlTextWriter writer = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
// Set the Writer formatting
writer.Formatting = Formatting.Indented;
// Convert collection
Helper.CollectionToXML(list, writer);
// Close the writer
writer.Flush();
writer.Close();
}
private static void CollectionToXML(IList list, XmlTextWriter writer)
{
// Validate list
if (list == null)
throw new Exception("Collection cannot be null");
if (list.Count == 0)
throw new Exception("Collection cannot be empty");
// Validate writer
if (writer == null)
throw new RAException("XmlTextWriter cannot be null");
//Write the root element
writer.WriteStartElement(list.GetType().Name);
foreach(object obj in list)
{
// Start an element
writer.WriteStartElement(list[0].GetType().Name);
// Get all properties
PropertyDescriptorCollection pInfo = Helper.GetProperties(obj);
if (pInfo != null)
{
foreach(PropertyDescriptor p in pInfo)
{
// Add Property
writer.WriteElementString(p.DisplayName, p.GetValue(obj).ToString());
}
}
// Close the element
writer.WriteEndElement();
}
// Close root element
writer.WriteEndElement();
}
private static PropertyDescriptorCollection GetProperties(object obj)
{
// Get the type of the object
Type t = obj.GetType();
// Get the properties
PropertyDescriptorCollection props;
props = TypeDescriptor.GetProperties(t);
if (props != null)
return props;
return null;
}
}
The main method is: StoreCollectionInXML
This method, simply validates the List we want to store in XML, and then creates an instance of the XmlTextWriter.
Then it calls the CollectionToXML method, this method, writes the Root and the sub elements into the XML file. This method, gets the Type of the objects stored in the collection, then for each Type it calls the method GetProperties. That method will return all the properties of that Type.
Once I have all the properties, I can use the property name and value to generated a new XML element and its value.
I hope you liked this post!
Regards
Tags: ASP.NET 1.x