Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.Linq;
- using System.Reflection;
- using System.ComponentModel;
- using System.Collections;
- namespace Core {
- using Linq;
- public static class TypeHelper {
- public static T CopyObject<T>(T source) {
- var dcs = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
- using(var ms = new System.IO.MemoryStream()) {
- dcs.WriteObject(ms,source);
- ms.Seek(0,System.IO.SeekOrigin.Begin);
- return (T)dcs.ReadObject(ms);
- }
- }
- public static T CreateInstance<T>() {
- return (T)CreateInstance(typeof(T),null);
- }
- public static T CreateInstance<T>(params object[] args) {
- return (T)typeof(T).InvokeMember(string.Empty,System.Reflection.BindingFlags.CreateInstance,null,null,args);
- }
- public static object CreateInstance(Type t) {
- return CreateInstance(t,null);
- }
- public static object CreateInstance(Type t,params object[] args) {
- return Activator.CreateInstance(t,args);
- }
- public static object CreateInstance(string fullName) {
- return CreateInstance(Type.GetType(fullName));
- }
- public static object CreateInstance(string fullName,params object[] args) {
- return CreateInstance(Type.GetType(fullName),args);
- }
- public static T CreateInstance<T>(string fullName) {
- return (T)CreateInstance(Type.GetType(fullName));
- }
- public static T CreateInstance<T>(string fullName,params object[] args) {
- return (T)CreateInstance(Type.GetType(fullName),args);
- }
- public static T GetValue<T>(object obj,string propertyName) {
- return (T)GetValue(obj,propertyName);
- }
- public static object GetValue(object obj,string propertyName) {
- PropertyDescriptor prop = GetProperty(obj.GetType(),propertyName);
- if(prop == null)
- return null;
- return prop.GetValue(obj);
- }
- public static void SetValue(object obj,string propertyName,object value) {
- PropertyDescriptor prop = GetProperty(obj.GetType(),propertyName);
- if(prop == null)
- return;
- prop.SetValue(obj,value);
- }
- public static void CopyProperties(object src,object desc,params string[] ignoreProperyNames) {
- var srcProperties = GetProperties(src);
- var descProperties = GetProperties(desc);
- List<string> errors = new List<string>();
- foreach(var pinfo in srcProperties) {
- if(ignoreProperyNames != null) {
- if(ignoreProperyNames.Contains(pinfo.Name))
- continue;
- }
- if(descProperties.FirstOrDefault(x => x.Name.EqualsIgnoreCase(pinfo.Name)) == null)
- continue;
- try {
- object val = GetValue(src,pinfo.Name);
- SetValue(desc,pinfo.Name,val);
- }
- catch(Exception err) {
- errors.Add(pinfo.Name + " mapping error => " + err.Message);
- }
- }
- if(errors.Count > 0)
- throw new FormatException(errors.JoinStrings(Environment.NewLine));
- }
- public static T[] CopyProperties<T>(object[] src,params string[] ignoreProperyNames) {
- List<T> list = new List<T>(src.Length);
- for(int i = 0;i < src.Length;i++) {
- if(src[i] == null)
- continue;
- T to = TypeHelper.CreateInstance<T>();
- list.Add(to);
- CopyProperties(src[i],to,ignoreProperyNames);
- }
- return list.ToArray();
- }
- //NameValueCollection
- public static void CopyProperties(NameValueCollection src,object dest,params string[] ignoreProperyNames) {
- var toProperties = GetProperties(dest,ignoreProperyNames);
- var matches = toProperties
- .Where(p => src.AllKeys.Contains(p.Name,StringComparer.CurrentCulture));
- matches.Each(pinfo => {
- object value = src[pinfo.Name];
- if(value == null)
- pinfo.SetValue(dest,null);
- else {
- if(pinfo.Converter.CanConvertFrom(value.GetType())) {
- object converted = pinfo.Converter.ConvertFrom(value);
- pinfo.SetValue(dest,converted);
- }
- else {
- throw new InvalidCastException("Property: {0} can not convert from Value: {1} with Type of {2}"
- .FormatString(pinfo.Name,value,value.GetType().Name));
- }
- }
- });
- }
- //IDictionary<string,object>
- public static void CopyProperties(IDictionary<string,object> src,object desc,params string[] ignoreProperyNames) {
- var descProperties = GetProperties(desc,ignoreProperyNames);
- descProperties.Each(pinfo => {
- foreach(var item in src.Keys) {
- if(item.ToString() == pinfo.Name) {
- var value = src[pinfo.Name];
- pinfo.SetValue(desc,value);
- break;
- }
- }
- });
- }
- public static PropertyDescriptor GetProperty<T>(string propertyName) {
- return GetProperty(typeof(T),propertyName);
- }
- public static PropertyDescriptor GetProperty(object obj,string propertyName) {
- return GetProperty(obj.GetType(),propertyName);
- }
- public static PropertyDescriptor GetProperty(Type obj,string propertyName) {
- PropertyDescriptor prop = TypeDescriptor.GetProperties(obj)
- .OfType<PropertyDescriptor>()
- .Where(p => p.Name.Equals(propertyName))
- .FirstOrDefault();
- return prop;
- }
- public static Dictionary<string,object> GetPropertyValues(object obj) {
- var dictionary = TypeDescriptor.GetProperties(obj)
- .OfType<PropertyDescriptor>()
- .ToDictionary(p => p.Name,p => p.GetValue(obj));
- return dictionary;
- }
- public static string[] GetStringConstents(Type type) {
- return null;
- }
- public static Dictionary<string,object> GetFieldValues(object obj) {
- Type t = obj.GetType();
- var fields = t.GetFields();
- var dict = new Dictionary<string,object>(fields.Length);
- foreach(var item in fields) {
- dict.Add(item.Name,item.GetValue(obj));
- }
- return dict;
- }
- public static IEnumerable<MethodInfo> GetMethods(Type type,Type returnType) {
- var methods = type.GetMethods()
- .Where(meth => meth.ReturnType.Equals(returnType));
- return methods;
- }
- public static IEnumerable<PropertyDescriptor> GetProperties(object obj,params string[] ignoreProperyNames) {
- var properties = GetProperties(obj.GetType())
- .Where(pinfo => !ignoreProperyNames.Contains(pinfo.Name,StringComparer.CurrentCulture));
- return properties;
- }
- public static IEnumerable<PropertyDescriptor> GetProperties(Type type) {
- return TypeDescriptor.GetProperties(type)
- .OfType<PropertyDescriptor>().AsEnumerable();
- }
- public static string[] GetPropertyNames(object obj) {
- return GetPropertyNames(obj.GetType());
- }
- public static string[] GetPropertyNames(Type t) {
- return TypeDescriptor.GetProperties(t)
- .OfType<PropertyDescriptor>()
- .Select(p => p.Name)
- .ToArray();
- }
- public static IEnumerable<T> AnonymousToTypedList<T>(IEnumerable<object> component) {
- List<T> list = new List<T>();
- foreach(var item in component) {
- list.Add(AnonymousToTyped<T>(item));
- }
- return list;
- }
- public static T AnonymousToTyped<T>(object component) {
- T typedObject = CreateInstance<T>();
- foreach(PropertyDescriptor descriptor in TypeDescriptor.GetProperties(component)) {
- object propValue = descriptor.GetValue(component);
- SetValue(typedObject,descriptor.Name,propValue);
- }
- return typedObject;
- }
- public static Dictionary<string,object> AnonymousToDictionary(object component) {
- return AnonymousToDictionary<object>(component);
- }
- public static Dictionary<string,TValue> AnonymousToDictionary<TValue>(object component) {
- Dictionary<string,TValue> dictionary = new Dictionary<string,TValue>();
- foreach(PropertyDescriptor descriptor in TypeDescriptor.GetProperties(component)) {
- object propValue = descriptor.GetValue(component);
- if(propValue == null)
- dictionary.Add(descriptor.Name,default(TValue));
- else {
- TValue typedValue = (TValue)Convert.ChangeType(propValue,typeof(TValue));
- dictionary.Add(descriptor.Name,typedValue);
- }
- }
- return dictionary;
- }
- public static Dictionary<string,TAttributeType> GetAttributes<TAttributeType>(object component) where TAttributeType:Attribute {
- if(component == null)
- throw new ArgumentNullException("component");
- Type componentType = component.GetType();
- return GetAttributes<TAttributeType>(componentType);
- }
- public static Dictionary<string,TAttributeType> GetAttributes<TAttributeType>(Type componentType) where TAttributeType:Attribute {
- if(componentType == null)
- throw new ArgumentNullException("componentType");
- Type attribteType = typeof(TAttributeType);
- var dict = componentType.GetMembers()
- .Where(p => Attribute.IsDefined(p,attribteType))
- .ToDictionary(
- key => key.Name,
- value => (TAttributeType)Attribute.GetCustomAttribute(value,attribteType)
- );
- return dict;
- }
- /// <summary>
- /// Returns an array of PropertyAttributeDescriptor that contains the specified attributes along with property info
- /// </summary>
- /// <typeparam name="TAttributeType">The desired attribute to retrieve</typeparam>
- /// <param name="componentType">The component type to get the properties and attributes</param>
- /// <param name="includeAllProperties">True to include all properties including properties without the specified attribute</param>
- /// <returns>Array of PropertyAttributeDescriptor</returns>
- public static PropertyAttributeDescriptor<TAttributeType>[] GetPropertiesWithAttribute<TAttributeType>(Type componentType,bool includeAllProperties) where TAttributeType:Attribute {
- var attributes = GetAttributes<TAttributeType>(componentType);
- var props = TypeHelper.GetProperties(componentType);
- var dictionary = new Dictionary<string,PropertyAttributeDescriptor<TAttributeType>>(props.Count());
- foreach(var item in props) {
- if(item.Attributes.Count == 0)
- continue;
- if(dictionary.ContainsKey(item.Name))
- continue;
- foreach(var att in item.Attributes) {
- if(!(att is TAttributeType))
- continue;
- dictionary.Add(item.Name,new PropertyAttributeDescriptor<TAttributeType>() {
- Name = item.Name,
- Attribute = (TAttributeType)att,
- PropertyInfo = item
- });
- }
- }
- return dictionary.Values.ToArray();
- }
- public class PropertyAttributeDescriptor<TAttributeType> where TAttributeType:Attribute {
- public string Name { get; set; }
- public PropertyDescriptor PropertyInfo { get; set; }
- public TAttributeType Attribute { get; set; }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment