using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace Roadie.Library.Extensions { public static class GenericExt { public static TEntity CopyTo(this TEntity OriginalEntity, TEntity NewEntity) { PropertyInfo[] oProperties = OriginalEntity.GetType().GetProperties(); foreach (PropertyInfo CurrentProperty in oProperties.Where(p => p.CanWrite)) { if (CurrentProperty.GetValue(NewEntity, null) != null) { CurrentProperty.SetValue(OriginalEntity, CurrentProperty.GetValue(NewEntity, null), null); } } return OriginalEntity; } /// /// Perform a deep Copy of the object using a BinaryFormatter. /// IMPORTANT: the object class must be marked as [Serializable] and have an parameterless constructor. /// /// The type of object being copied. /// The object instance to copy. /// The copied object. public static T Clone(this T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } IFormatter formatter = new BinaryFormatter(); using (Stream stream = new MemoryStream()) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } public static string DescriptionAttr(this T source) { FieldInfo fi = source.GetType().GetField(source.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes != null && attributes.Length > 0) return attributes[0].Description; else return source.ToString(); } } }