Ovi Diaconescu

Blog more, tweet less

ObservableCollectionEx

ObservableCollectionExNuget

Published my first project on GitHub and wrapped it up in a Nuget package. Extends the observable collection to track events when a value of a particular element within the collection is changed. The Event Arguments also include the actual object that triggered the event. NuGet: https://nuget.org/packages/ObservableCollectionExtended/ GitHub: https://github.com/ovidiaconescu/ObservableCollectionEx Supported frameworks via Portable Class Library: [...]

Set Properties using Reflection

Clone a class property by property using reflection. public class ModelBase {     public T GetEF<T>()     {         T myClass = (T)FormatterServices.GetUninitializedObject(typeof(T));         return GetEF<T>(myClass);     }     public T GetEF<T>(T myClass)     {         PropertyInfo[] pi = myClass.GetType().GetProperties();         foreach (PropertyInfo prop in pi)         {             PropertyInfo localProp = this.GetType().GetProperty(prop.Name);             if (localProp != null)             {                 object value = localProp.GetValue(this, null);                 if (localProp.PropertyType == typeof(string) && value == null)                      value = string.Empty;                 prop.SetValue(myClass, value, null);             }         }         return myClass;     }     public void SetEF<T>(T myClass)     {         if (myClass == null)             return;         PropertyInfo[] pi = myClass.GetType().GetProperties();         foreach (PropertyInfo prop in pi)         {             PropertyInfo localProp = this.GetType().GetProperty(prop.Name);             if (localProp != null)             {                 if (localProp.PropertyType == prop.PropertyType)                     localProp.SetValue(this, prop.GetValue(myClass, null), null);             }         }     } }

List to DataTable Extension Method

A simple extension method that converts a generic list to a DataTable public static DataTable ToDataTable<T>(this List<T> items) {     var tb = new DataTable(typeof(T).Name);     PropertyInfo[] props = typeof(T).GetProperties(         BindingFlags.Public | BindingFlags.Instance);     foreach (var prop in props)     {         Type propType = prop.PropertyType;         if (propType.IsGenericType &&             propType.GetGenericTypeDefinition() == typeof(Nullable<>))         {             propType = Nullable.GetUnderlyingType(propType);         }         tb.Columns.Add(prop.Name, propType);     }     foreach (var item in items)     {         var values = new object[props.Length];         for (var i = 0; i < props.Length; i++)         {             values[i] = props[i].GetValue(item, null);         }         tb.Rows.Add(values);     }     return tb; }