andrew4582

TypeHelper

Aug 4th, 2010
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.58 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.ComponentModel;
  7. using System.Collections;
  8. namespace Core {
  9.     using Linq;
  10.     public static class TypeHelper {
  11.         public static T CopyObject<T>(T source) {
  12.             var dcs = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
  13.             using(var ms = new System.IO.MemoryStream()) {
  14.                 dcs.WriteObject(ms,source);
  15.                 ms.Seek(0,System.IO.SeekOrigin.Begin);
  16.                 return (T)dcs.ReadObject(ms);
  17.             }
  18.         }
  19.         public static T CreateInstance<T>() {
  20.             return (T)CreateInstance(typeof(T),null);
  21.         }
  22.         public static T CreateInstance<T>(params  object[] args) {
  23.             return (T)typeof(T).InvokeMember(string.Empty,System.Reflection.BindingFlags.CreateInstance,null,null,args);
  24.         }
  25.         public static object CreateInstance(Type t) {
  26.             return CreateInstance(t,null);
  27.         }
  28.         public static object CreateInstance(Type t,params  object[] args) {
  29.             return Activator.CreateInstance(t,args);
  30.         }
  31.         public static object CreateInstance(string fullName) {
  32.             return CreateInstance(Type.GetType(fullName));
  33.         }
  34.         public static object CreateInstance(string fullName,params  object[] args) {
  35.             return CreateInstance(Type.GetType(fullName),args);
  36.         }
  37.         public static T CreateInstance<T>(string fullName) {
  38.             return (T)CreateInstance(Type.GetType(fullName));
  39.         }
  40.         public static T CreateInstance<T>(string fullName,params  object[] args) {
  41.             return (T)CreateInstance(Type.GetType(fullName),args);
  42.         }
  43.         public static T GetValue<T>(object obj,string propertyName) {
  44.             return (T)GetValue(obj,propertyName);
  45.         }
  46.         public static object GetValue(object obj,string propertyName) {
  47.             PropertyDescriptor prop = GetProperty(obj.GetType(),propertyName);
  48.             if(prop == null)
  49.                 return null;
  50.             return prop.GetValue(obj);
  51.         }
  52.         public static void SetValue(object obj,string propertyName,object value) {
  53.             PropertyDescriptor prop = GetProperty(obj.GetType(),propertyName);
  54.             if(prop == null)
  55.                 return;
  56.             prop.SetValue(obj,value);
  57.         }
  58.         public static void CopyProperties(object src,object desc,params  string[] ignoreProperyNames) {
  59.             var srcProperties = GetProperties(src);
  60.             var descProperties = GetProperties(desc);
  61.  
  62.             List<string> errors = new List<string>();
  63.             foreach(var pinfo in srcProperties) {
  64.                 if(ignoreProperyNames != null) {
  65.                     if(ignoreProperyNames.Contains(pinfo.Name))
  66.                         continue;
  67.                 }
  68.                 if(descProperties.FirstOrDefault(x => x.Name.EqualsIgnoreCase(pinfo.Name)) == null)
  69.                     continue;
  70.  
  71.                 try {
  72.                     object val = GetValue(src,pinfo.Name);
  73.                     SetValue(desc,pinfo.Name,val);
  74.                 }
  75.                 catch(Exception err) {
  76.                     errors.Add(pinfo.Name + " mapping error => " + err.Message);
  77.                 }
  78.             }
  79.             if(errors.Count > 0)
  80.                 throw new FormatException(errors.JoinStrings(Environment.NewLine));
  81.         }
  82.         public static T[] CopyProperties<T>(object[] src,params  string[] ignoreProperyNames) {
  83.             List<T> list = new List<T>(src.Length);
  84.             for(int i = 0;i < src.Length;i++) {
  85.                 if(src[i] == null)
  86.                     continue;
  87.                 T to = TypeHelper.CreateInstance<T>();
  88.                 list.Add(to);
  89.                 CopyProperties(src[i],to,ignoreProperyNames);
  90.             }
  91.             return list.ToArray();
  92.         }
  93.         //NameValueCollection
  94.         public static void CopyProperties(NameValueCollection src,object dest,params  string[] ignoreProperyNames) {
  95.             var toProperties = GetProperties(dest,ignoreProperyNames);
  96.  
  97.             var matches = toProperties
  98.                 .Where(p => src.AllKeys.Contains(p.Name,StringComparer.CurrentCulture));
  99.  
  100.             matches.Each(pinfo => {
  101.                 object value = src[pinfo.Name];
  102.                 if(value == null)
  103.                     pinfo.SetValue(dest,null);
  104.                 else {
  105.                     if(pinfo.Converter.CanConvertFrom(value.GetType())) {
  106.                         object converted = pinfo.Converter.ConvertFrom(value);
  107.                         pinfo.SetValue(dest,converted);
  108.                     }
  109.                     else {
  110.                         throw new InvalidCastException("Property: {0} can not convert from Value: {1} with Type of {2}"
  111.                             .FormatString(pinfo.Name,value,value.GetType().Name));
  112.                     }
  113.                 }
  114.             });
  115.         }
  116.         //IDictionary<string,object>
  117.         public static void CopyProperties(IDictionary<string,object> src,object desc,params  string[] ignoreProperyNames) {
  118.             var descProperties = GetProperties(desc,ignoreProperyNames);
  119.             descProperties.Each(pinfo => {
  120.                 foreach(var item in src.Keys) {
  121.                     if(item.ToString() == pinfo.Name) {
  122.                         var value = src[pinfo.Name];
  123.                         pinfo.SetValue(desc,value);
  124.                         break;
  125.                     }
  126.                 }
  127.             });
  128.         }
  129.         public static PropertyDescriptor GetProperty<T>(string propertyName) {
  130.             return GetProperty(typeof(T),propertyName);
  131.         }
  132.         public static PropertyDescriptor GetProperty(object obj,string propertyName) {
  133.             return GetProperty(obj.GetType(),propertyName);
  134.         }
  135.         public static PropertyDescriptor GetProperty(Type obj,string propertyName) {
  136.             PropertyDescriptor prop = TypeDescriptor.GetProperties(obj)
  137.                .OfType<PropertyDescriptor>()
  138.                .Where(p => p.Name.Equals(propertyName))
  139.                .FirstOrDefault();
  140.             return prop;
  141.         }
  142.         public static Dictionary<string,object> GetPropertyValues(object obj) {
  143.             var dictionary = TypeDescriptor.GetProperties(obj)
  144.               .OfType<PropertyDescriptor>()
  145.               .ToDictionary(p => p.Name,p => p.GetValue(obj));
  146.             return dictionary;
  147.         }
  148.         public static string[] GetStringConstents(Type type) {
  149.  
  150.             return null;
  151.         }
  152.         public static Dictionary<string,object> GetFieldValues(object obj) {
  153.             Type t = obj.GetType();
  154.             var fields = t.GetFields();
  155.             var dict = new Dictionary<string,object>(fields.Length);
  156.             foreach(var item in fields) {
  157.                 dict.Add(item.Name,item.GetValue(obj));
  158.             }
  159.             return dict;
  160.         }
  161.         public static IEnumerable<MethodInfo> GetMethods(Type type,Type returnType) {
  162.             var methods = type.GetMethods()
  163.                 .Where(meth => meth.ReturnType.Equals(returnType));
  164.             return methods;
  165.         }
  166.         public static IEnumerable<PropertyDescriptor> GetProperties(object obj,params  string[] ignoreProperyNames) {
  167.             var properties = GetProperties(obj.GetType())
  168.                 .Where(pinfo => !ignoreProperyNames.Contains(pinfo.Name,StringComparer.CurrentCulture));
  169.             return properties;
  170.         }
  171.         public static IEnumerable<PropertyDescriptor> GetProperties(Type type) {
  172.             return TypeDescriptor.GetProperties(type)
  173.                 .OfType<PropertyDescriptor>().AsEnumerable();
  174.         }
  175.         public static string[] GetPropertyNames(object obj) {
  176.             return GetPropertyNames(obj.GetType());
  177.         }
  178.         public static string[] GetPropertyNames(Type t) {
  179.             return TypeDescriptor.GetProperties(t)
  180.                 .OfType<PropertyDescriptor>()
  181.                 .Select(p => p.Name)
  182.                 .ToArray();
  183.         }
  184.  
  185.         public static IEnumerable<T> AnonymousToTypedList<T>(IEnumerable<object> component) {
  186.             List<T> list = new List<T>();
  187.             foreach(var item in component) {
  188.                 list.Add(AnonymousToTyped<T>(item));
  189.             }
  190.             return list;
  191.         }
  192.         public static T AnonymousToTyped<T>(object component) {
  193.             T typedObject = CreateInstance<T>();
  194.             foreach(PropertyDescriptor descriptor in TypeDescriptor.GetProperties(component)) {
  195.                 object propValue = descriptor.GetValue(component);
  196.                 SetValue(typedObject,descriptor.Name,propValue);
  197.             }
  198.             return typedObject;
  199.         }
  200.         public static Dictionary<string,object> AnonymousToDictionary(object component) {
  201.             return AnonymousToDictionary<object>(component);
  202.         }
  203.         public static Dictionary<string,TValue> AnonymousToDictionary<TValue>(object component) {
  204.             Dictionary<string,TValue> dictionary = new Dictionary<string,TValue>();
  205.             foreach(PropertyDescriptor descriptor in TypeDescriptor.GetProperties(component)) {
  206.                 object propValue = descriptor.GetValue(component);
  207.                 if(propValue == null)
  208.                     dictionary.Add(descriptor.Name,default(TValue));
  209.                 else {
  210.                     TValue typedValue = (TValue)Convert.ChangeType(propValue,typeof(TValue));
  211.                     dictionary.Add(descriptor.Name,typedValue);
  212.                 }
  213.             }
  214.             return dictionary;
  215.         }
  216.         public static Dictionary<string,TAttributeType> GetAttributes<TAttributeType>(object component) where TAttributeType:Attribute {
  217.             if(component == null)
  218.                 throw new ArgumentNullException("component");
  219.             Type componentType = component.GetType();
  220.             return GetAttributes<TAttributeType>(componentType);
  221.         }
  222.         public static Dictionary<string,TAttributeType> GetAttributes<TAttributeType>(Type componentType) where TAttributeType:Attribute {
  223.             if(componentType == null)
  224.                 throw new ArgumentNullException("componentType");
  225.  
  226.             Type attribteType = typeof(TAttributeType);
  227.  
  228.             var dict = componentType.GetMembers()
  229.                 .Where(p => Attribute.IsDefined(p,attribteType))
  230.                 .ToDictionary(
  231.                     key => key.Name,
  232.                     value => (TAttributeType)Attribute.GetCustomAttribute(value,attribteType)
  233.                 );
  234.             return dict;
  235.         }
  236.         /// <summary>
  237.         /// Returns an array of PropertyAttributeDescriptor that contains the specified attributes along with property info
  238.         /// </summary>
  239.         /// <typeparam name="TAttributeType">The desired attribute to retrieve</typeparam>
  240.         /// <param name="componentType">The component type to get the properties and attributes</param>
  241.         /// <param name="includeAllProperties">True to include all properties including properties without the specified attribute</param>
  242.         /// <returns>Array of PropertyAttributeDescriptor</returns>
  243.         public static PropertyAttributeDescriptor<TAttributeType>[] GetPropertiesWithAttribute<TAttributeType>(Type componentType,bool includeAllProperties) where TAttributeType:Attribute {
  244.             var attributes = GetAttributes<TAttributeType>(componentType);
  245.             var props = TypeHelper.GetProperties(componentType);
  246.             var dictionary = new Dictionary<string,PropertyAttributeDescriptor<TAttributeType>>(props.Count());
  247.  
  248.             foreach(var item in props) {
  249.                 if(item.Attributes.Count == 0)
  250.                     continue;
  251.                 if(dictionary.ContainsKey(item.Name))
  252.                     continue;
  253.                 foreach(var att in item.Attributes) {
  254.                     if(!(att is TAttributeType))
  255.                         continue;
  256.  
  257.                     dictionary.Add(item.Name,new PropertyAttributeDescriptor<TAttributeType>() {
  258.                         Name = item.Name,
  259.                         Attribute = (TAttributeType)att,
  260.                         PropertyInfo = item
  261.                     });
  262.                 }
  263.             }
  264.             return dictionary.Values.ToArray();
  265.         }
  266.         public class PropertyAttributeDescriptor<TAttributeType> where TAttributeType:Attribute {
  267.             public string Name { get; set; }
  268.             public PropertyDescriptor PropertyInfo { get; set; }
  269.             public TAttributeType Attribute { get; set; }
  270.         }
  271.     }
  272. }
Advertisement
Add Comment
Please, Sign In to add comment