Provides a simple reflection based mapper to perform a Data Mapping between two types of objects

   
 
//---------------------------------------------------------------------
//  This file is part of the Background Motion solution.
// 
//  Copyright (C) Mindscape (TM).  All rights reserved.
//  http://www.mindscape.co.nz
// 
//  THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//---------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Reflection;

namespace Mindscape.BackgroundMotion.Core.Utilities
{
  /// <summary>
  /// Provides a simple reflection based mapper to perform a Data Mapping between two types of objects
  /// </summary>
  /// <remarks>
  /// We are working on the convention that the source object will be property based and the target will be field based
  /// This is used between our domain entities and DTO&#039;s
  /// </remarks>
  /// <typeparam name="T"></typeparam>
  public class DataMapper<T> where T : new()
  {
    // TODO: Not thread-safe - using ThreadStatic should be ok here

    private static Dictionary<Type, Dictionary<string, PropertyInfo>> _propertyReflectionCache =
      new Dictionary<Type, Dictionary<string, PropertyInfo>>();

    private static Dictionary<Type, FieldInfo&#91;&#93;> _fieldReflectionCache = new Dictionary<Type, FieldInfo&#91;&#93;>();

    /// <summary>
    /// Use a reflection based mapping to map between properties and fields
    /// </summary>
    public static T Map(object source)
    {
      T target = new T();
      FieldInfo[] fields = GetFieldSetInfo(typeof(T));

      if (source == null)
      {
        return target;
      }

      foreach (FieldInfo field in fields)
      {
        try
        {
          PropertyInfo sourceProperty = GetPropertyInfo(source.GetType(), field.Name);
          if (sourceProperty == null)
          {
            continue;
          }

          field.SetValue(target, sourceProperty.GetValue(source, null));
        }
        catch (InvalidCastException)
        {
        }
      }

      return target;
    }

    /// <summary>
    /// Finds a property in the reflection cache
    /// </summary>
    private static PropertyInfo GetPropertyInfo(Type t, string name)
    {
      if (_propertyReflectionCache.ContainsKey(t))
      {
        if (_propertyReflectionCache[t].ContainsKey(name))
        {
          return _propertyReflectionCache[t][name];
        }

        _propertyReflectionCache[t].Add(name, t.GetProperty(name, BindingFlags.Public | BindingFlags.Instance));
        return _propertyReflectionCache[t][name];
      }

      Dictionary<string, PropertyInfo> dictionary = new Dictionary<string, PropertyInfo>();
      _propertyReflectionCache.Add(t, dictionary);
      dictionary.Add(name, t.GetProperty(name, BindingFlags.Public | BindingFlags.Instance));

      return _propertyReflectionCache[t][name];
    }

    /// <summary>
    /// Finds a collection of field information from the reflection cache
    /// </summary>
    private static FieldInfo[] GetFieldSetInfo(Type t)
    {
      if (_fieldReflectionCache.ContainsKey(t))
      {
        return _fieldReflectionCache[t];
      }

      _fieldReflectionCache.Add(t, t.GetFields(BindingFlags.Public | BindingFlags.Instance));

      return _fieldReflectionCache[t];
    }
  }
}

   
     


Determine if a type is cloneable: either a value type or implementing ICloneable.

   
 
        
//******************************
// Written by Peter Golde
// Copyright (c) 2004-2007, Wintellect
//
// Use and restribution of this code is subject to the license agreement 
// contained in the file "License.txt" accompanying this file.
//******************************

using System;
using System.Collections;
using System.Collections.Generic;


namespace Wintellect.PowerCollections
{
  /// <summary>
  /// A holder class for various internal utility functions that need to be shared.
  /// </summary>
    internal static class Util
    {
        /// <summary>
        /// Determine if a type is cloneable: either a value type or implementing
        /// ICloneable.
        /// </summary>
        /// <param name="type">Type to check.</param>
        /// <param name="isValue">Returns if the type is a value type, and does not implement ICloneable.</param>
        /// <returns>True if the type is cloneable.</returns>
        public static bool IsCloneableType(Type type, out bool isValue)
        {
            isValue = false;

            if (typeof(ICloneable).IsAssignableFrom(type)) {
                return true;
            }
            else if (type.IsValueType) {
                isValue = true;
                return true;
            }
            else
                return false;
        }




    }
}

   
     


Set the specified public field value of an object

#region License and Copyright
/*
* Dotnet Commons Reflection
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the
* Free Software Foundation, Inc.,
* 59 Temple Place,
* Suite 330,
* Boston,
* MA 02111-1307
* USA
*
*/

#endregion

using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Dotnet.Commons.Reflection
{
/// ———————————————————————–
///

/// This utility class contains a rich sets of utility methods that perform operations
/// on objects during runtime such as copying of property and field values
/// between 2 objects, deep cloning of objects, etc.
///

/// ———————————————————————–
public abstract class ObjectUtils
{

/// ————————————————————————
///

/// Set the specified public field value of an object
///

/// the Value Object on which setting is to be performed /// Field name /// Value to be set /// ————————————————————————
public static object SetField(object vo, string fieldName, Object fieldValue)
{
if (vo == null)
throw new System.ArgumentNullException(“No object specified to set.”);

if (fieldName == null)
throw new System.ArgumentNullException(“No field name specified.”);

if ((fieldName == String.Empty) || (fieldName.Length < 1)) throw new System.ArgumentException("Field name cannot be empty."); FieldInfo fieldInfo = vo.GetType().GetField(fieldName); if (fieldInfo == null) throw new System.ArgumentException("The class '" + vo.GetType().Name + "' does not have the field '"+ fieldName + "'"); // Set the value vo.GetType().InvokeMember(fieldInfo.Name, BindingFlags.SetField, null, vo, new object[]{fieldValue}); return vo; } } } [/csharp]

Deep Comparison two objects if they are alike.

   
 

#region License and Copyright
/*
 * Dotnet Commons Reflection
 *
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License as published by 
 * the Free Software Foundation; either version 2.1 of the License, or 
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License 
 * for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this library; if not, write to the 
 * Free Software Foundation, Inc., 
 * 59 Temple Place, 
 * Suite 330, 
 * Boston, 
 * MA 02111-1307 
 * USA 
 * 
 */

#endregion

using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Dotnet.Commons.Reflection
{
  /// -----------------------------------------------------------------------
  /// <summary>  
  /// This utility class contains a rich sets of utility methods that perform operations 
  /// on objects during runtime such as copying of property and field values
  /// between 2 objects, deep cloning of objects, etc.  
  /// </summary>
  /// -----------------------------------------------------------------------
  public abstract class ObjectUtils
  {


    /// ------------------------------------------------------------------------
    /// <summary>
    /// Deep Comparison two objects if they are alike. The objects are consider alike if 
    /// they are:
    /// <list type="ordered">
    ///    <item>of the same <see cref="System.Type"/>,</item>
    ///    <item>have the same number of methods, properties and fields</item>
    ///    <item>the public and private properties and fields values reflect each other&#039;s. </item>
    /// </list>
    /// </summary>
    /// <param name="original"></param>
    /// <param name="comparedToObject"></param>
    /// <returns></returns>
    /// ------------------------------------------------------------------------
    public static bool IsALike(object original, object comparedToObject) 
    { 
      
      if (original.GetType() != comparedToObject.GetType())
        return false;

      // ...............................................
      // Compare Number of Private and public Methods
      // ...............................................
      MethodInfo[] originalMethods = original
        .GetType()
        .GetMethods(BindingFlags.Instance | 
        BindingFlags.NonPublic | 
        BindingFlags.Public); 
      
      MethodInfo[] comparedMethods = comparedToObject
        .GetType()
        .GetMethods(BindingFlags.Instance | 
        BindingFlags.NonPublic | 
        BindingFlags.Public); 

      if (comparedMethods.Length != originalMethods.Length)       
        return false;
      
      // ...............................................
      // Compare Number of Private and public Properties
      // ................................................
      PropertyInfo[] originalProperties = original
        .GetType()
        .GetProperties(BindingFlags.Instance | 
        BindingFlags.NonPublic | 
        BindingFlags.Public); 

      PropertyInfo[] comparedProperties = comparedToObject
        .GetType()
        .GetProperties(BindingFlags.Instance | 
        BindingFlags.NonPublic | 
        BindingFlags.Public); 
      
      
      if (comparedProperties.Length != originalProperties.Length)
        return false;


      // ...........................................
      // Compare number of public and private fields
      // ...........................................
      FieldInfo[] originalFields = original
        .GetType()
        .GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); 

      FieldInfo[] comparedToFields = comparedToObject
        .GetType()
        .GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); 

      
      if (comparedToFields.Length != originalFields.Length) 
        return false;

      // ........................................
      // compare field values
      // ........................................
      foreach (FieldInfo fi in originalFields)
      {    
    
        // check to see if the object to contains the field          
        FieldInfo fiComparedObj = comparedToObject.GetType().GetField(fi.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

        if (fiComparedObj == null)
          return false;

        // Get the value of the field from the original object        
        Object srcValue =  original.GetType().InvokeMember(fi.Name,
          BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
          null,
          original,
          null);


          
        // Get the value of the field
        object  comparedObjFieldValue = comparedToObject
          .GetType()
          .InvokeMember(fiComparedObj.Name,
          BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
          null,
          comparedToObject,
          null);

          
        // -------------------------------
        // now compare the field values
        // -------------------------------

        if (srcValue == null)
        {
          if (comparedObjFieldValue != null)
            return false;
          else
            return true;
        }

        if (srcValue.GetType() != comparedObjFieldValue.GetType())
          return false;

        if (!srcValue.ToString().Equals(comparedObjFieldValue.ToString()))
          return false;      
      } 

      // ........................................
      // compare each Property values
      // ........................................
      foreach (PropertyInfo pi in originalProperties)
      {    
    
        // check to see if the object to contains the field          
        PropertyInfo piComparedObj = comparedToObject
          .GetType()
          .GetProperty(pi.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

        if (piComparedObj == null)
          return false;

        // Get the value of the property from the original object        
        Object srcValue = original
          .GetType()
          .InvokeMember(pi.Name,
          BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
          null,
          original,
          null);
          
        // Get the value of the property
        object  comparedObjValue = comparedToObject
          .GetType()
          .InvokeMember(piComparedObj.Name,
          BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
          null,
          comparedToObject,
          null);

          
        // -------------------------------
        // now compare the property values
        // -------------------------------
        if (srcValue.GetType() != comparedObjValue.GetType())
          return false;

        if (!srcValue.ToString().Equals(comparedObjValue.ToString()))
          return false;      
      }
      return true; 
    } 
   }
}

   
     


Get a public field value given its name

   
 

#region License and Copyright
/*
 * Dotnet Commons Reflection
 *
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License as published by 
 * the Free Software Foundation; either version 2.1 of the License, or 
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License 
 * for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this library; if not, write to the 
 * Free Software Foundation, Inc., 
 * 59 Temple Place, 
 * Suite 330, 
 * Boston, 
 * MA 02111-1307 
 * USA 
 * 
 */

#endregion

using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Dotnet.Commons.Reflection
{
  /// -----------------------------------------------------------------------
  /// <summary>  
  /// This utility class contains a rich sets of utility methods that perform operations 
  /// on objects during runtime such as copying of property and field values
  /// between 2 objects, deep cloning of objects, etc.  
  /// </summary>
  /// -----------------------------------------------------------------------
  public abstract class ObjectUtils
  {

    /// ------------------------------------------------------------------------
    /// <summary>
    /// Get a <b>public</b> field value given its name
    /// </summary>
    /// <param name="srcObj">object to inspect</param>
    /// <param name="fieldName">Name of the field to retrieve the value from</param>
    /// <returns>property value</returns>
    /// ------------------------------------------------------------------------
    public static Object GetFieldValue(object srcObj, string fieldName)
    {

      FieldInfo fieldInfoObj = srcObj.GetType().GetField(fieldName);

      if (fieldInfoObj == null)
        return null;

      // Get the value from property.
      object srcValue = srcObj.GetType()
                  .InvokeMember(fieldInfoObj.Name,
                  BindingFlags.GetField,
                  null,
                  srcObj,
                  null);

      return srcValue;
    }
   }
}

   
     


Helper to display the “contents” of the Value Object

   
 

#region License and Copyright
/*
 * Dotnet Commons Reflection
 *
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License as published by 
 * the Free Software Foundation; either version 2.1 of the License, or 
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License 
 * for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this library; if not, write to the 
 * Free Software Foundation, Inc., 
 * 59 Temple Place, 
 * Suite 330, 
 * Boston, 
 * MA 02111-1307 
 * USA 
 * 
 */

#endregion

using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Dotnet.Commons.Reflection
{
  /// -----------------------------------------------------------------------
  /// <summary>  
  /// This utility class contains a rich sets of utility methods that perform operations 
  /// on objects during runtime such as copying of property and field values
  /// between 2 objects, deep cloning of objects, etc.  
  /// </summary>
  /// -----------------------------------------------------------------------
  public abstract class ObjectUtils
  {

    /// ------------------------------------------------------------------------
    /// <summary>
    /// Helper to display the "contents" of the Value Object
    /// </summary>
    /// <param name="valueObject"></param>
    /// <returns></returns>
    /// ------------------------------------------------------------------------
    public static string ConvertToString(object valueObject) 
    {
      StringBuilder buffy = new StringBuilder(valueObject.GetType().FullName);


      // null objects cannot be reflected
      if(valueObject == null) 
      {
        buffy.Append(" is null.");
        return buffy.ToString();
      }

      buffy.Append("[
");
      foreach(PropertyInfo objProperty in valueObject.GetType().GetProperties())
      {
        string nvp;

        nvp = "  <<Property>> " + "<" + objProperty.PropertyType + "> " + objProperty.Name+"=";

        if (objProperty != null) 
        {
          object   value = valueObject
                   .GetType()
                   .InvokeMember(objProperty.Name,
                          BindingFlags.GetProperty,
                          null,
                          valueObject,
                          null);

          buffy.Append(nvp+value.ToString()+"
");
        }
        else          
        {
          buffy.Append(nvp+"<null>
");
        }
      }

      foreach(FieldInfo objField in valueObject.GetType().GetFields())
      {
        string nvp;

        nvp = "  <<Field>> " + "<" + objField.FieldType + "> " + objField.Name +"=";

        if (objField != null) 
        {
          object   value = valueObject.GetType().InvokeMember(objField.Name,
                                    BindingFlags.GetField,                                    
                                    null,
                                    valueObject,
                                    null);

          buffy.Append(nvp+value.ToString()+"
");
        }
        else          
        {
          buffy.Append(nvp+"<null>
");
        }
      }
      // ----------- End ---------
      buffy.Append("]");
      return buffy.ToString();
    }

    }
}

   
     


Returns all assemblies and their properties

   
 

/*
Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Linq.Expressions;
using System.Collections;
#endregion

namespace Utilities
{
    /// <summary>
    /// Utility class that handles various
    /// functions dealing with reflection.
    /// </summary>
    public static class Reflection
    {
        /// <summary>
        /// Dumps the properties names and current values
        /// from an object
        /// </summary>
        /// <param name="Object">Object to dunp</param>
        /// <returns>An HTML formatted table containing the information about the object</returns>
        public static string DumpProperties(object Object)
        {
            try
            {
                StringBuilder TempValue = new StringBuilder();
                TempValue.Append("<table><thead><tr><th>Property Name</th><th>Property Value</th></tr></thead><tbody>");
                Type ObjectType = Object.GetType();
                PropertyInfo[] Properties = ObjectType.GetProperties();
                foreach (PropertyInfo Property in Properties)
                {
                    TempValue.Append("<tr><td>" + Property.Name + "</td><td>");
                    ParameterInfo[] Parameters = Property.GetIndexParameters();
                    if (Property.CanRead &amp;&amp; Parameters.Length == 0)
                    {
                        try
                        {
                            object Value = Property.GetValue(Object, null);
                            TempValue.Append(Value == null ? "null" : Value.ToString());
                        }
                        catch { }
                    }
                    TempValue.Append("</td></tr>");
                }
                TempValue.Append("</tbody></table>");
                return TempValue.ToString();
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }
        /// <summary>
        /// Dumps the properties names and current values
        /// from an object type (used for static classes)
        /// </summary>
        /// <param name="ObjectType">Object type to dunp</param>
        /// <returns>An HTML formatted table containing the information about the object type</returns>
        public static string DumpProperties(Type ObjectType)
        {
            try
            {
                StringBuilder TempValue = new StringBuilder();
                TempValue.Append("<table><thead><tr><th>Property Name</th><th>Property Value</th></tr></thead><tbody>");
                PropertyInfo[] Properties = ObjectType.GetProperties();
                foreach (PropertyInfo Property in Properties)
                {
                    TempValue.Append("<tr><td>" + Property.Name + "</td><td>");
                    if (Property.GetIndexParameters().Length == 0)
                    {
                        try
                        {
                            TempValue.Append(Property.GetValue(null, null) == null ? "null" : Property.GetValue(null, null).ToString());
                        }
                        catch { }
                    }
                    TempValue.Append("</td></tr>");
                }
                TempValue.Append("</tbody></table>");
                return TempValue.ToString();
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }
        /// <summary>
        /// Returns all assemblies and their properties
        /// </summary>
        /// <returns>An HTML formatted string that contains the assemblies and their information</returns>
        public static string DumpAllAssembliesAndProperties()
        {
            try
            {
                StringBuilder Builder = new StringBuilder();
                Assembly[] Assemblies = AppDomain.CurrentDomain.GetAssemblies();
                foreach (Assembly Assembly in Assemblies)
                {
                    Builder.Append("<strong>" + Assembly.GetName().Name + "</strong><br />");
                    Builder.Append(DumpProperties(Assembly) + "<br /><br />");
                }
                return Builder.ToString();
            }
            catch { throw; }
        }
    }
}