Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.IO;
- using System.Xml.Linq;
- using System.Reflection;
- using System.Runtime.Serialization;
- namespace XmlSerializeTest
- {
- public class DataClass
- {
- public DataClass Clone()
- {
- return (DataClass) this.MemberwiseClone();
- }
- }
- [DataContract]
- public class Foo : DataClass
- {
- private string test1 = "";
- private string test2 = "";
- [DataMember]
- public string Test1 { get { return test1; } set { test1 = value; } }
- [DataMember]
- public string Test2 { get { return test2; } set { test2 = value; } }
- }
- public class MeSerializer
- {
- Type targetType;
- public MeSerializer(Type targetType)
- {
- this.targetType = targetType;
- if (!targetType.IsDefined(typeof(DataContractAttribute), false))
- throw new Exception("No soup for you.");
- }
- public void WriteObjectDiff(Stream stream, object changed, object orig)
- {
- IEnumerable<PropertyInfo> properties =
- targetType.GetProperties().Where(p => p.IsDefined(typeof(DataMemberAttribute), false));
- var writer = new StreamWriter(stream);
- writer.Write("<" + targetType.Name + ">");
- foreach (PropertyInfo propInfo in properties)
- {
- string s_orig = propInfo.GetValue(orig, null).ToString();
- if (orig != null)
- {
- string s_changed = propInfo.GetValue(changed, null).ToString();
- if (s_orig.Equals(s_changed)) continue;
- }
- writer.Write("<" + propInfo.Name + ">" + propInfo.GetValue(orig, null) + "</" + propInfo.Name + ">");
- }
- writer.Write("</" + targetType.Name + ">");
- writer.Flush();
- }
- }
- public class Program
- {
- static void Main(string[] args)
- {
- Foo foo = new Foo();
- foo.Test1 = "bar";
- foo.Test2 = "ASDF";
- Foo foo2 = (Foo) foo.Clone();
- foo.Test2 = "ASDG";
- MeSerializer ser = new MeSerializer(foo.GetType());
- var output = new MemoryStream();
- ser.WriteObjectDiff(output, foo2, foo);
- output.Seek(0, SeekOrigin.Begin);
- string s = Convert.ToString(XElement.Parse(Encoding.ASCII.GetString(output.GetBuffer()).Replace("\0", "")));
- Console.WriteLine(s);
- Console.ReadKey();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement