ln.types/sync/Syncable.cs

126 lines
3.6 KiB
C#

// /**
// * File: Syncable.cs
// * Author: haraldwolff
// *
// * This file and it's content is copyrighted by the Author and / or copyright holder.
// * Any use wihtout proper permission is illegal and may lead to legal actions.
// *
// *
// **/
using System;
using System.IO;
using System.Collections.Generic;
using ln.logging;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.Reflection;
using System.Text;
using ln.types.serialize;
namespace ln.types.sync
{
public class Synced : Attribute
{
}
public class Unsynced : Attribute
{
}
public abstract class Syncable
{
public String FileName { get; set; }
public Syncable()
{
}
public Syncable(string fileName)
{
FileName = fileName;
Load();
}
public void Load()
{
using (ObjectReader objectReader = new ObjectReader(FileName))
{
objectReader.ReadThis(this);
}
}
public void Sync()
{
using (FileStream fileStream = new FileStream(FileName, FileMode.OpenOrCreate))
{
ObjectWriter objectWriter = new ObjectWriter(fileStream);
objectWriter.Write(this);
fileStream.Close();
}
}
public virtual void Restore(Dictionary<string,object> keyValues)
{
if (keyValues.ContainsKey("sync.timestamp"))
Logging.Log(LogLevel.DEBUG, "Syncable restoring from state of {0}",keyValues["sync.timestamp"]);
foreach (FieldInfo fieldInfo in GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance))
{
if (fieldInfo.GetCustomAttribute<Synced>() != null)
{
string key = String.Format("field.{0}", fieldInfo.Name);
if (keyValues.ContainsKey(key))
{
fieldInfo.SetValue(this,keyValues[key]);
}
}
}
}
public virtual void Collect(Dictionary<string, object> keyValues)
{
keyValues["sync.timestamp"] = DateTime.Now;
Logging.Log(LogLevel.DEBUG, "Syncable: collectiong state at {0}", keyValues["sync.timestamp"]);
foreach (FieldInfo fieldInfo in GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance))
{
if (fieldInfo.GetCustomAttribute<Synced>() != null)
{
string key = String.Format("field.{0}", fieldInfo.Name);
object value = fieldInfo.GetValue(this);
keyValues.Add(key, value);
}
}
}
private byte[] Serialize(object o)
{
if (o == null)
return new byte[0];
XmlSerializer xmlSerializer = new XmlSerializer(o.GetType());
MemoryStream memoryStream = new MemoryStream();
xmlSerializer.Serialize(memoryStream, o);
byte[] result = memoryStream.ToArray();
Logging.Log(LogLevel.DEBUG, "Serialized: {0}",Encoding.UTF8.GetString(result));
return result;
}
private object Unserialize(byte[] buffer,Type type)
{
if ((type == null) || (buffer.Length == 0))
return null;
MemoryStream memoryStream = new MemoryStream(buffer);
XmlSerializer xmlSerializer = new XmlSerializer(type);
return xmlSerializer.Deserialize(memoryStream);
}
}
}