Set the specified public field value of an object

image_pdfimage_print

#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.

image_pdfimage_print
   
 

#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

image_pdfimage_print
   
 

#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

image_pdfimage_print
   
 

#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

image_pdfimage_print
   
 

/*
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; }
        }
    }
}

   
     


Convert type from initial Value

image_pdfimage_print
   
 

#region License
// Copyright 2006 James Newton-King
// http://www.newtonsoft.com
//
// This work is licensed under the Creative Commons Attribution 2.5 License
// http://creativecommons.org/licenses/by/2.5/
//
// You are free:
//    * to copy, distribute, display, and perform the work
//    * to make derivative works
//    * to make commercial use of the work
//
// Under the following conditions:
//    * You must attribute the work in the manner specified by the author or licensor:
//          - If you find this component useful a link to http://www.newtonsoft.com would be appreciated.
//    * For any reuse or distribution, you must make clear to others the license terms of this work.
//    * Any of these conditions can be waived if you get permission from the copyright holder.
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Collections;
using System.ComponentModel;

namespace MySpace.Common.IO.JSON.Utilities
{
    internal static class ReflectionUtils
    {
        public static T Convert<T>(object initialValue)
        {
            Type targetType = typeof(T);
            Type initialType = (initialValue != null) ? initialValue.GetType() : null;

            TypeConverter converter = TypeDescriptor.GetConverter(targetType);

            if (converter == null || !converter.CanConvertFrom(initialType))
                throw new ApplicationException(string.Format("Could not convert from {0} to {1}", initialType, targetType));

            return (T)converter.ConvertFrom(initialValue);
        }
    }
}

   
     


Is it a SubClass for another class

image_pdfimage_print
   
 
#region License
// Copyright 2006 James Newton-King
// http://www.newtonsoft.com
//
// This work is licensed under the Creative Commons Attribution 2.5 License
// http://creativecommons.org/licenses/by/2.5/
//
// You are free:
//    * to copy, distribute, display, and perform the work
//    * to make derivative works
//    * to make commercial use of the work
//
// Under the following conditions:
//    * You must attribute the work in the manner specified by the author or licensor:
//          - If you find this component useful a link to http://www.newtonsoft.com would be appreciated.
//    * For any reuse or distribution, you must make clear to others the license terms of this work.
//    * Any of these conditions can be waived if you get permission from the copyright holder.
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Collections;
using System.ComponentModel;

namespace MySpace.Common.IO.JSON.Utilities
{
    internal static class ReflectionUtils
    {

        public static bool IsSubClass(Type type, Type check)
        {
            if (type == null || check == null)
                return false;

            if (type == check &amp;&amp; type.IsGenericType)
                return true;

            if (check.IsInterface)
            {
                foreach (Type t in type.GetInterfaces())
                {
                    if (IsSubClass(t, check)) return true;
                }
            }
            if (type.IsGenericType &amp;&amp; !type.IsGenericTypeDefinition)
            {
                if (IsSubClass(type.GetGenericTypeDefinition(), check))
                    return true;
            }
            return IsSubClass(type.BaseType, check);
        }

    }
}