///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// * Neither the name of Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Security.Cryptography;
using System.Text;
using System.Globalization;
using System.IO;
namespace WOSI.Utilities
{
/// <summary>
/// Summary description for CryptoUtils.
/// </summary>
public class CryptoUtils
{
public static byte[] GetFileBytes(string filename)
{
if (File.Exists(filename))
{
FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read);
byte[] fileBytes = new byte[fs.Length];
fs.Read(fileBytes, 0, (int)fs.Length);
fs.Close();
return fileBytes;
}
return null;
}
public static string GetByteChecksum(byte[] bytes)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] hashValue = md5.ComputeHash(bytes);
return Convert.ToBase64String(hashValue);
}
public static string GetFileChecksum(string filename)
{
if (File.Exists(filename))
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] fileBytes = GetFileBytes(filename);
return GetByteChecksum(fileBytes);
}
return "";
}
}
}
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'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[]> _fieldReflectionCache = new Dictionary<Type, FieldInfo[]>();
/// <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
{
/// ———————————————————————–
///
/// on objects during runtime such as copying of property and field values
/// between 2 objects, deep cloning of objects, etc.
///
/// ———————————————————————–
public abstract class ObjectUtils
{
/// ————————————————————————
///
///
/// 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'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();
}
}
}

