using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using System.Windows.Forms;
namespace ClassLibrary.Security
{
///
/// provides simple, strongly typed xml serialization methods.
///
static class Serializer
{
///
/// returns the serializer for a specific type.
///
///
///
private static XmlSerializer getSerializer()
{
return new XmlSerializer(typeof(T));
}
///
/// serializes data of type T to the specified filename.
///
///
///
///
public static void Save(T o, String fileName)
{
using (FileStream fs = File.Open(fileName, FileMode.Create))
{
Save(o, fs);
}
}
///
/// serialize data of type T to the specified stream.
///
///
/// the type of data to serialize.
///
///
/// the object to serialize (must be of type t)
///
///
/// the stream to write the serialized data to.
///
public static void Save(T o, Stream stream)
{
getSerializer().Serialize(stream, o);
}
///
/// get the xml bytes the object of type T is serialized to.
///
///
///
///
public static byte[] Save(T o)
{
using (MemoryStream ms = new MemoryStream())
{
// write the data to the memory stream:
Save(o, ms);
// return the back-buffer:
return ms.GetBuffer();
}
}
///
/// get the xml string the object is seriaized to, using the specified encoding.
///
///
/// the type of object to serialize.
///
///
/// the object to serialize.
///
///
public static String Save(T o, Encoding encoding)
{
return encoding.GetString(Save(o));
}
///
/// loads data of type T from the stream.
///
///
///
///
///
public static T Load(Stream stream)
{
return (T)getSerializer().Deserialize(stream);
}
///
/// loads the data from the file.
///
///
///
///
///
public static T Load(FileInfo file)
{
try
{
using (FileStream fs = file.Open(FileMode.Open))
{
return Load(fs);
}
} catch(Exception ex)
{
MessageBox.Show("Error: 512"); // No license file found
return default(T);
}
}
///
/// deserialize an object of type T from the byte-array of XML data.
///
///
///
///
public static T Load(byte[] data)
{
using (MemoryStream ms = new MemoryStream(data))
{
return Load(ms);
}
}
///
/// deserialize an object of type T from the supplied XML data string.
///
///
///
///
public static T Load(String data)
{
return Load(Encoding.ASCII.GetBytes(data));
}
}
}