Fluent nHibernate dictionary customType - c#

I have problem with CustomType in Fluent NHibernate.
I have to save as Json a dictionary to my database.
I created a customType for this that implements IUserType interface.
There is no problem to save dictionary to database for first time, but when i try to update collection, nHibernate dont set a property as dirty and dont update it.
My Equals and GetHashCode methods
public new bool Equals(object x, object y)
{
if (x == null && y == null)
return true;
if (x == null || y == null)
return false;
if (!(x is IDictionary<K, Z>) || !(y is IDictionary<K, Z>))
return false;
var dic1 = (x as IDictionary<K, Z>).OrderBy(z=> z.Key);
var dic2 = (y as IDictionary<K, Z>).OrderBy(z => z.Key);
return dic1.SequenceEqual(dic2);
}
public int GetHashCode(object x)
{
if (x == null)
return 0;
return x.GetHashCode();
}
The objects passed to equals method are always the same (recently modified) two object.
Anyone have a idea what i'm doing wrong ?
Rest of IUserType implementation code:
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
if (names.Length != 1)
throw new InvalidOperationException("Only expecting one column...");
var val = rs[names[0]] as string;
if (val != null && !string.IsNullOrWhiteSpace(val))
{
return JsonConvert.DeserializeObject<T>(val, JSonSerializableTypeSerializer.Settings);
}
return null;
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
var parameter = (DbParameter)cmd.Parameters[index];
if (value == null)
{
parameter.Value = DBNull.Value;
}
else
{
parameter.Value = JsonConvert.SerializeObject(value, JSonSerializableTypeSerializer.Settings);
}
}
public object DeepCopy(object value)
{
return value;
}
public object Replace(object original, object target, object owner)
{
return original;
}
public object Assemble(object cached, object owner)
{
return cached;
}
public object Disassemble(object value)
{
return value;
}
public SqlType[] SqlTypes
{
get
{
return new SqlType[] { new StringClobSqlType() };
}
}
public Type ReturnedType
{
get { return typeof(T); }
}
public bool IsMutable
{
get { return true; }
}

Maybe I am wrong, but I guess you have returned false while implementing IUserType.IsMutable.
Since your user type returns a Dictionary, which is a mutable type, and which you do indeed mutate, your user type must return true for its IsMutable property.

Related

Implement Generic Get<T> for MemoryCache (or any Cache)

I'm trying to write a "simple" Generic Get<T>; extension for
System.Runtime.MemoryCache.
Why "simple" ? Because generally I know object's real type before caching it, so when I retrieve it from cache, I'm not going to convert it in unpredictable ways.
For example: if boolean "true" value is stored in cache with cacheKey "id", so
Get<string>("id") == "true";
Get<int>("id") == 1; // any result > 0 is okay
Get<SomeUnpredictableType> == null; // just ignore these trouble conversions
Here's my incomplete implemention:
public static T DoGet<T>(this MemoryCache cache, string key) {
object value = cache.Get(key);
if (value == null) {
return default(T);
}
if (value is T) {
return (T)value;
}
// TODO: (I'm not sure if following logic is okay or not)
// 1. if T and value are both numeric type (e.g. long => double), how to code it?
// 2. if T is string, call something like Convert.ToString()
Type t = typeof(T);
t = (Nullable.GetUnderlyingType(t) ?? t);
if (typeof(IConvertible).IsAssignableFrom(value.GetType())) {
return (T)Convert.ChangeType(value, t);
}
return default(T);
}
Any suggestions are highly appreciated.
===================================
Update (04/11/2016):
For those nice suggestions given, I implement my first version of Get<T>
public class MemCache {
private class LazyObject<T> : Lazy<T> {
public LazyObject(Func<T> valueFactory) : base(valueFactory) { }
public LazyObject(Func<T> valueFactory, LazyThreadSafetyMode mode) : base(valueFactory, mode) { }
}
private static T CastValue<T>(object value) {
if (value == null || value is DBNull) {
return default(T);
}
Type valType = value.GetType();
if (valType.IsGenericType && valType.GetGenericTypeDefinition() == typeof(LazyObject<>)) {
return CastValue<T>(valType.GetProperty("Value").GetValue(value));
}
if (value is T) {
return (T)value;
}
Type t = typeof(T);
t = (Nullable.GetUnderlyingType(t) ?? t);
if (typeof(IConvertible).IsAssignableFrom(t) && typeof(IConvertible).IsAssignableFrom(value.GetType())) {
return (T)Convert.ChangeType(value, t);
}
return default(T);
}
private MemoryCache m_cache;
public T Get<T>(string key) {
return CastValue<T>(m_cache.Get(key));
}
public void Set<T>(string key, T value, CacheDependency dependency) {
m_cache.Set(key, value, dependency.AsCacheItemPolicy());
}
public T GetOrAdd<T>(string key, Func<T> fnValueFactory, CacheDependency dependency) {
LazyObject<T> noo = new LazyObject<T>(fnValueFactory, LazyThreadSafetyMode.ExecutionAndPublication);
LazyObject<T> old = m_cache.AddOrGetExisting(key, noo, dependency.AsCacheItemPolicy()) as LazyObject<T>;
try {
return CastValue<T>((old ?? noo).Value);
} catch {
m_cache.Remove(key);
throw;
}
}
/* Remove/Trim ... */
}
The essential work is to write a CastValue<T> to convert any object to desired type. And it doesn't have to handle very complicate condition because object types in cache is predictable for the programmer. And here's my version.
public static T CastValue<T>(object value) {
if (value == null || value is DBNull) {
return default(T);
}
if (value is T) {
return (T)value;
}
Type t = typeof(T);
t = (Nullable.GetUnderlyingType(t) ?? t);
if (typeof(IConvertible).IsAssignableFrom(t) && typeof(IConvertible).IsAssignableFrom(value.GetType())) {
return (T)Convert.ChangeType(value, t);
}
return default(T);
}
Proposal:
public static T DoGet<T>(this MemoryCache cache, string key)
{
object value = cache.Get(key);
if (value == null) {
return default(T);
}
// support for nullables. Do not waste performance with
// type conversions if it is not a nullable.
var underlyingType = Nullable.GetUnderlyingType(t);
if (underlyingType != null)
{
value = Convert.ChangeType(value, underlyingType);
}
return (T)value;
}
Usage (supposed you have an id of type int in the cache):
int id = Get<int>("id");
int? mayBeId = Get<int?>("id");
string idAsString = Get<int?>("id")?.ToString();
double idAsDouble = (double)Get<int>("id");
I haven't test it.

C# WPF ComboBox.ObjectCollection.IndexOf Method (Object) can't find Object in ComboBox with an other object with the same value

I have a Combobox which contain IdDataClass object and im tying to find the index of an IdDataClass in my ComboBox with an IdDataClass with the same parameter as the one in the ComboBox.
IdDataClass Instance1 = new IdDataClass(0, "Text");
IdDataClass Instance2 = new IdDataClass(0, "Text");
MyComboBox.Items.Add(Instance1);
int Index = MyComboBox.Items.IndexOf(Instance1);
This example will work and will return the index of ContactClientIdDataClass1
But this one
IdDataClass Instance1 = new IdDataClass(0, "Text");
IdDataClass Instance2 = new IdDataClass(0, "Text");
MyComboBox.Items.Add(Instance1);
int Index = MyComboBox.Items.IndexOf(Instance2);
will not work the value of index is -1. My question is why can't i find the index of instance1 with instance2. They have exactly the same value ?
Ps. I have try to overload the Equals function of my IdDataClass:
public class IdDataClass
{
int _ID;
string _MyData;
public IdDataClass(int ID, string Data)
{
_ID = ID;
_MyData = Data;
}
public bool Equals(IdDataClass p)
{
if ((object)p == null)
{
return false;
}
return (_ID == p._ID)&&(_MyData == p._MyData);
}
}
When you use IndexOf() the method uses Object.Equals() to determine whether two objects are alike. So your own Equals method never gets called because it is not the same method. You have to override the Equals method to obtain the behaviour you want. Add the following lines:
public override bool Equals(object obj)
{
IdDataClass otherObject = obj as IdDataClass;
if (otherObject == null)
return false;
else
return Equals(otherObject );
}
public override int GetHashCode()
{
return _ID.GetHashCode() + _MyData.GetHashCode();
}
Overriding the GetHashCode() should be done as well as you never know how the items are stored within a collection. It maybe uses some kind of HashTable for performance manner. You should make clear that instances that are equal (according to your implementation) return the same hash code.
Try this:
public class IdDataClass : IEquatable<IdDataClass>
{
int _ID;
string _MyData;
public IdDataClass(int ID, string Data)
{
_ID = ID;
_MyData = Data;
}
public bool Equals(IdDataClass p)
{
return (_ID == p._ID) && (_MyData == p._MyData);
}
public override bool Equals(object obj)
{
if (obj == null || !(obj is IdDataClass))
return false;
else
return Equals(obj as IdDataClass);
}
public override int GetHashCode()
{
return _ID.GetHashCode() ^ _MyData.GetHashCode();
}
}
When p is null, this line if ((object)p == null) will throw exception, simple p==null is enough.
_ID, and _MyData are private, so you can't access them like in
return (_ID == p._ID)&&(_MyData == p._MyData);

Converting and Casting an object based on a [Type] object

Hopefully a simple enough question, but I am struggling to find an answer.
How can I cast an 'object' to a type defined in a 'Type' object.
For example, basically I am trying to do the following with reflection, making it as generic as possible:
public class MyClass
{
public string Prop1 { get; set; }
public int Prop2 { get; set; }
}
public T FillMyClass<T>() where T : new()
{
//The definitions here are suppled in code - each class we want to work with needs to be "mapped".
string name1 = "Prop1";
Type type1 = typeof(string);
string name2 = "Prop2";
Type type2 = typeof(int);
//The values always start out as a string because of the way I'm receiving it.
string val1 = "test";
string val2 = "1";
T t= new T();
//Works fine, because val1 is already a string
t.GetType().GetProperty(name1).SetValue(t, val1, null);
//Having trouble with the below.
object o = Convert.ChangeType(val2, type2);
//Fails because o is not an int
t.GetType().GetProperty(name2).SetValue(t, o, null);
}
So the type is defined by the user (or possibly even just by looking up the type of the property).
But I just can't see how to cast the object to a [Type].
I've come across this issue as well a couple of times. While I'm sure there is a more elegant solution to this problem, I've made the following extension method to get you 99% of the way there.
public static object TryConvertToType(this object source, Type destinationType, object defaultValue = null)
{
try
{
if (source == null)
return defaultValue;
if (destinationType == typeof(bool))
{
bool returnValue = false;
if (!bool.TryParse(source.ToString(), out returnValue))
{
return Convert.ChangeType(source.ToString() == "1", destinationType);
}
else
{
return Convert.ChangeType(returnValue, destinationType);
}
}
else if (destinationType.IsSubclassOf(typeof(Enum)))
{
try
{
return Enum.Parse(destinationType, source.ToString());
}
catch
{
return Enum.ToObject(destinationType, source);
}
}
else if (destinationType == typeof(Guid))
{
return Convert.ChangeType(new Guid(source.ToString().ToUpper()), destinationType);
}
else if (destinationType.IsGenericType && destinationType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type genericType = destinationType.GetGenericArguments().First();
return Convert.ChangeType(source, genericType);
}
else if (source.GetType().IsSubclassOf(destinationType))
{
return Convert.ChangeType(source, destinationType);
}
else if (!source.GetType().IsValueType
&& source.GetType() != typeof(string)
&& destinationType == typeof(string))
{
return Convert.ChangeType(source.GetType().Name, destinationType);
}
else
{
return Convert.ChangeType(source, destinationType);
}
}
catch
{
return defaultValue;
}
}
Basically, in usage, it works like so:
t.GetType().GetProperty(name).GetValue(t, null).TryConvertToType(type2, 0);

NHibernate IUserType not being applied on Insert

I'm using NHibernate with Postgresql as the backend and had to create custom types for converting System.DateTime to Postgresql "time" types as well as System.TimeSpans to "interval" db types. The IUserType I created are working and are being applied for reads and updates but they are never being applied when I try to insert an object into the database. I've set breakpoints in the IUserTypes but they never are hit when an insert is happening.
I think the issue may be around the fact that the object is just a POCO object and isn't a proxy yet so the mapping that applies the transformation to the usertype doesn't happen when I set the value of my property.
If I do an update and set one of these properties I can see the breakpoints in the IUserType are fired.
Any thoughts?
UPDATE
The Equals Method of the IUserType is being called but the NullSafeSet where I do the necessary conversion is not.
EDIT
Added code samples
public class TimeType : BaseImmutableUserType<TimeSpan>
{
public override object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var val = NHibernateUtil.Time.NullSafeGet(rs, names[0]);
if (val == null)
return null;
var dt = DateTime.Parse(val.ToString());
return new TimeSpan(0, dt.Hour, dt.Minute, dt.Second);
}
public override void NullSafeSet(IDbCommand cmd, object value, int index)
{
var obj = (TimeSpan)value;
((IDbDataParameter) cmd.Parameters[index]).Value = obj;
}
public override SqlType[] SqlTypes
{
get
{
return new[] { SqlTypeFactory.Time };
}
}
}
public abstract class BaseImmutableUserType<T> : IUserType
{
public abstract object NullSafeGet(IDataReader rs, string[] names, object owner);
public abstract void NullSafeSet(IDbCommand cmd, object value, int index);
public abstract SqlType[] SqlTypes { get; }
public BaseImmutableUserType()
{
int i = 0;
}
public new bool Equals(object x, object y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x == null || y == null)
{
return false;
}
return x.Equals(y);
}
public int GetHashCode(object x)
{
return x.GetHashCode();
}
public object DeepCopy(object value)
{
return value;
}
public object Replace(object original, object target, object owner)
{
return original;
}
public object Assemble(object cached, object owner)
{
return DeepCopy(cached);
}
public object Disassemble(object value)
{
return DeepCopy(value);
}
public Type ReturnedType
{
get { return typeof(T); }
}
public bool IsMutable
{
get { return false; }
}
}
I found the following two options:
Option 1: do not use your own UserType. Instead use NHibernate's own TimeAsTimeSpan like this:
Map(x => x.TimeFrom)
.CustomType("TimeAsTimeSpan");
(Example taken from here)
Option 2: Modify your class a little:
public class TimeType : BaseImmutableUserType<TimeSpan>
{
// this is taken from the source of NHibernate.Type.TimeAsTimeSpanType
private static readonly DateTime BaseDateValue = new DateTime(1753, 01, 01);
public override object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var val = NHibernateUtil.TimeAsTimeSpan.NullSafeGet(rs, names[0]);
if (val == null)
return null;
var dt = DateTime.Parse(val.ToString());
return new TimeSpan(0, dt.Hour, dt.Minute, dt.Second);
}
public override void NullSafeSet(IDbCommand cmd, object value, int index)
{
//var obj = (TimeSpan)value; // we can't use TimeSpan here but need to use DateTime
// this is taken from the source of NHibernate.Type.TimeAsTimeSpanType
DateTime date = BaseDateValue.AddTicks(((TimeSpan)value).Ticks);
((IDbDataParameter)cmd.Parameters[index]).Value = date;
}
public override SqlType[] SqlTypes
{
get
{
return new[] { NHibernate.SqlTypes.SqlTypeFactory.Time };
}
}
}

C# implementation of deep/recursive object comparison in .net 3.5

I am looking for a C# specific , open source (or source code available) implementation of recursive, or deep, object comparison.
I currently have two graphs of live objects that I am looking to compare to each other, with the result of the comparison being a set of discrepancies in the graphs. The objects are instantiations of a set of classes that are known at run time (but not necessarily at compile time).
There is a specific requirement to be able to map from the discrepancies in the graphs, back to the objects containing the discrepancies.
I found a really nice, free implementation at www.kellermansoftware.com called Compare .NET Objects which can be found here. Highly recommended.
Appears to have relocated to github - most recent version is available here
This is a complex area; I've done some things like this at runtime, and it quickly gets messy. If possible, you might find that the simplest way to do this is to serialize the objects and compare the serialized form (perhaps xml-diff and XmlSerializer). This is complicated a little by the types not being known until runtime, but not hugely (you can always use new XmlSerializer(obj.GetType()) etc).
That would be my default approach, anyway.
Here's an NUnit 2.4.6 custom constraint we use for comparing complex graphs. It supports embedded collections, parent references, setting tolerance for numeric comparisons, identifying field names to ignore (even deep within the hierarchy), and decorating types to be always ignored.
I'm sure this code can be adapted to be used outside NUnit, the bulk of the code isn't dependent on NUnit.
We use this in thousands of unit tests.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using NUnit.Framework;
using NUnit.Framework.Constraints;
namespace Tests
{
public class ContentsEqualConstraint : Constraint
{
private readonly object expected;
private Constraint failedEquality;
private string expectedDescription;
private string actualDescription;
private readonly Stack<string> typePath = new Stack<string>();
private string typePathExpanded;
private readonly HashSet<string> _ignoredNames = new HashSet<string>();
private readonly HashSet<Type> _ignoredTypes = new HashSet<Type>();
private readonly LinkedList<Type> _ignoredInterfaces = new LinkedList<Type>();
private readonly LinkedList<string> _ignoredSuffixes = new LinkedList<string>();
private readonly IDictionary<Type, Func<object, object, bool>> _predicates = new Dictionary<Type, Func<object, object, bool>>();
private bool _withoutSort;
private int _maxRecursion = int.MaxValue;
private readonly HashSet<VisitedComparison> _visitedObjects = new HashSet<VisitedComparison>();
private static readonly HashSet<string> _globallyIgnoredNames = new HashSet<string>();
private static readonly HashSet<Type> _globallyIgnoredTypes = new HashSet<Type>();
private static readonly LinkedList<Type> _globallyIgnoredInterfaces = new LinkedList<Type>();
private static object _regionalTolerance;
public ContentsEqualConstraint(object expectedValue)
{
expected = expectedValue;
}
public ContentsEqualConstraint Comparing<T>(Func<T, T, bool> predicate)
{
Type t = typeof (T);
if (predicate == null)
{
_predicates.Remove(t);
}
else
{
_predicates[t] = (x, y) => predicate((T) x, (T) y);
}
return this;
}
public ContentsEqualConstraint Ignoring(string fieldName)
{
_ignoredNames.Add(fieldName);
return this;
}
public ContentsEqualConstraint Ignoring(Type fieldType)
{
if (fieldType.IsInterface)
{
_ignoredInterfaces.AddFirst(fieldType);
}
else
{
_ignoredTypes.Add(fieldType);
}
return this;
}
public ContentsEqualConstraint IgnoringSuffix(string suffix)
{
if (string.IsNullOrEmpty(suffix))
{
throw new ArgumentNullException("suffix");
}
_ignoredSuffixes.AddLast(suffix);
return this;
}
public ContentsEqualConstraint WithoutSort()
{
_withoutSort = true;
return this;
}
public ContentsEqualConstraint RecursingOnly(int levels)
{
_maxRecursion = levels;
return this;
}
public static void GlobalIgnore(string fieldName)
{
_globallyIgnoredNames.Add(fieldName);
}
public static void GlobalIgnore(Type fieldType)
{
if (fieldType.IsInterface)
{
_globallyIgnoredInterfaces.AddFirst(fieldType);
}
else
{
_globallyIgnoredTypes.Add(fieldType);
}
}
public static IDisposable RegionalIgnore(string fieldName)
{
return new RegionalIgnoreTracker(fieldName);
}
public static IDisposable RegionalIgnore(Type fieldType)
{
return new RegionalIgnoreTracker(fieldType);
}
public static IDisposable RegionalWithin(object tolerance)
{
return new RegionalWithinTracker(tolerance);
}
public override bool Matches(object actualValue)
{
typePathExpanded = null;
actual = actualValue;
return Matches(expected, actualValue);
}
private bool Matches(object expectedValue, object actualValue)
{
bool matches = true;
if (!MatchesNull(expectedValue, actualValue, ref matches))
{
return matches;
}
// DatesEqualConstraint supports tolerance in dates but works as equal constraint for everything else
Constraint eq = new DatesEqualConstraint(expectedValue).Within(tolerance ?? _regionalTolerance);
if (eq.Matches(actualValue))
{
return true;
}
if (MatchesVisited(expectedValue, actualValue, ref matches))
{
if (MatchesDictionary(expectedValue, actualValue, ref matches) &&
MatchesList(expectedValue, actualValue, ref matches) &&
MatchesType(expectedValue, actualValue, ref matches) &&
MatchesPredicate(expectedValue, actualValue, ref matches))
{
MatchesFields(expectedValue, actualValue, eq, ref matches);
}
}
return matches;
}
private bool MatchesNull(object expectedValue, object actualValue, ref bool matches)
{
if (IsNullEquivalent(expectedValue))
{
expectedValue = null;
}
if (IsNullEquivalent(actualValue))
{
actualValue = null;
}
if (expectedValue == null && actualValue == null)
{
matches = true;
return false;
}
if (expectedValue == null)
{
expectedDescription = "null";
actualDescription = "NOT null";
matches = Failure;
return false;
}
if (actualValue == null)
{
expectedDescription = "not null";
actualDescription = "null";
matches = Failure;
return false;
}
return true;
}
private bool MatchesType(object expectedValue, object actualValue, ref bool matches)
{
Type expectedType = expectedValue.GetType();
Type actualType = actualValue.GetType();
if (expectedType != actualType)
{
try
{
Convert.ChangeType(actualValue, expectedType);
}
catch(InvalidCastException)
{
expectedDescription = expectedType.FullName;
actualDescription = actualType.FullName;
matches = Failure;
return false;
}
}
return true;
}
private bool MatchesPredicate(object expectedValue, object actualValue, ref bool matches)
{
Type t = expectedValue.GetType();
Func<object, object, bool> predicate;
if (_predicates.TryGetValue(t, out predicate))
{
matches = predicate(expectedValue, actualValue);
return false;
}
return true;
}
private bool MatchesVisited(object expectedValue, object actualValue, ref bool matches)
{
var c = new VisitedComparison(expectedValue, actualValue);
if (_visitedObjects.Contains(c))
{
matches = true;
return false;
}
_visitedObjects.Add(c);
return true;
}
private bool MatchesDictionary(object expectedValue, object actualValue, ref bool matches)
{
if (expectedValue is IDictionary && actualValue is IDictionary)
{
var expectedDictionary = (IDictionary)expectedValue;
var actualDictionary = (IDictionary)actualValue;
if (expectedDictionary.Count != actualDictionary.Count)
{
expectedDescription = expectedDictionary.Count + " item dictionary";
actualDescription = actualDictionary.Count + " item dictionary";
matches = Failure;
return false;
}
foreach (DictionaryEntry expectedEntry in expectedDictionary)
{
if (!actualDictionary.Contains(expectedEntry.Key))
{
expectedDescription = expectedEntry.Key + " exists";
actualDescription = expectedEntry.Key + " does not exist";
matches = Failure;
return false;
}
if (CanRecurseFurther)
{
typePath.Push(expectedEntry.Key.ToString());
if (!Matches(expectedEntry.Value, actualDictionary[expectedEntry.Key]))
{
matches = Failure;
return false;
}
typePath.Pop();
}
}
matches = true;
return false;
}
return true;
}
private bool MatchesList(object expectedValue, object actualValue, ref bool matches)
{
if (!(expectedValue is IList && actualValue is IList))
{
return true;
}
var expectedList = (IList) expectedValue;
var actualList = (IList) actualValue;
if (!Matches(expectedList.Count, actualList.Count))
{
matches = false;
}
else
{
if (CanRecurseFurther)
{
int max = expectedList.Count;
if (max != 0 && !_withoutSort)
{
SafeSort(expectedList);
SafeSort(actualList);
}
for (int i = 0; i < max; i++)
{
typePath.Push(i.ToString());
if (!Matches(expectedList[i], actualList[i]))
{
matches = false;
return false;
}
typePath.Pop();
}
}
matches = true;
}
return false;
}
private void MatchesFields(object expectedValue, object actualValue, Constraint equalConstraint, ref bool matches)
{
Type expectedType = expectedValue.GetType();
FieldInfo[] fields = expectedType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
// should have passed the EqualConstraint check
if (expectedType.IsPrimitive ||
expectedType == typeof(string) ||
expectedType == typeof(Guid) ||
fields.Length == 0)
{
failedEquality = equalConstraint;
matches = Failure;
return;
}
if (expectedType == typeof(DateTime))
{
var expectedDate = (DateTime)expectedValue;
var actualDate = (DateTime)actualValue;
if (Math.Abs((expectedDate - actualDate).TotalSeconds) > 3.0)
{
failedEquality = equalConstraint;
matches = Failure;
return;
}
matches = true;
return;
}
if (CanRecurseFurther)
{
while(true)
{
foreach (FieldInfo field in fields)
{
if (!Ignore(field))
{
typePath.Push(field.Name);
if (!Matches(GetValue(field, expectedValue), GetValue(field, actualValue)))
{
matches = Failure;
return;
}
typePath.Pop();
}
}
expectedType = expectedType.BaseType;
if (expectedType == null)
{
break;
}
fields = expectedType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
}
}
matches = true;
return;
}
private bool Ignore(FieldInfo field)
{
if (_ignoredNames.Contains(field.Name) ||
_ignoredTypes.Contains(field.FieldType) ||
_globallyIgnoredNames.Contains(field.Name) ||
_globallyIgnoredTypes.Contains(field.FieldType) ||
field.GetCustomAttributes(typeof (IgnoreContentsAttribute), false).Length != 0)
{
return true;
}
foreach(string ignoreSuffix in _ignoredSuffixes)
{
if (field.Name.EndsWith(ignoreSuffix))
{
return true;
}
}
foreach (Type ignoredInterface in _ignoredInterfaces)
{
if (ignoredInterface.IsAssignableFrom(field.FieldType))
{
return true;
}
}
return false;
}
private static bool Failure
{
get
{
return false;
}
}
private static bool IsNullEquivalent(object value)
{
return value == null ||
value == DBNull.Value ||
(value is int && (int) value == int.MinValue) ||
(value is double && (double) value == double.MinValue) ||
(value is DateTime && (DateTime) value == DateTime.MinValue) ||
(value is Guid && (Guid) value == Guid.Empty) ||
(value is IList && ((IList)value).Count == 0);
}
private static object GetValue(FieldInfo field, object source)
{
try
{
return field.GetValue(source);
}
catch(Exception ex)
{
return ex;
}
}
public override void WriteMessageTo(MessageWriter writer)
{
if (TypePath.Length != 0)
{
writer.WriteLine("Failure on " + TypePath);
}
if (failedEquality != null)
{
failedEquality.WriteMessageTo(writer);
}
else
{
base.WriteMessageTo(writer);
}
}
public override void WriteDescriptionTo(MessageWriter writer)
{
writer.Write(expectedDescription);
}
public override void WriteActualValueTo(MessageWriter writer)
{
writer.Write(actualDescription);
}
private string TypePath
{
get
{
if (typePathExpanded == null)
{
string[] p = typePath.ToArray();
Array.Reverse(p);
var text = new StringBuilder(128);
bool isFirst = true;
foreach(string part in p)
{
if (isFirst)
{
text.Append(part);
isFirst = false;
}
else
{
int i;
if (int.TryParse(part, out i))
{
text.Append("[" + part + "]");
}
else
{
text.Append("." + part);
}
}
}
typePathExpanded = text.ToString();
}
return typePathExpanded;
}
}
private bool CanRecurseFurther
{
get
{
return typePath.Count < _maxRecursion;
}
}
private static bool SafeSort(IList list)
{
if (list == null)
{
return false;
}
if (list.Count < 2)
{
return true;
}
try
{
object first = FirstNonNull(list) as IComparable;
if (first == null)
{
return false;
}
if (list is Array)
{
Array.Sort((Array)list);
return true;
}
return CallIfExists(list, "Sort");
}
catch
{
return false;
}
}
private static object FirstNonNull(IEnumerable enumerable)
{
if (enumerable == null)
{
throw new ArgumentNullException("enumerable");
}
foreach (object item in enumerable)
{
if (item != null)
{
return item;
}
}
return null;
}
private static bool CallIfExists(object instance, string method)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
if (String.IsNullOrEmpty(method))
{
throw new ArgumentNullException("method");
}
Type target = instance.GetType();
MethodInfo m = target.GetMethod(method, new Type[0]);
if (m != null)
{
m.Invoke(instance, null);
return true;
}
return false;
}
#region VisitedComparison Helper
private class VisitedComparison
{
private readonly object _expected;
private readonly object _actual;
public VisitedComparison(object expected, object actual)
{
_expected = expected;
_actual = actual;
}
public override int GetHashCode()
{
return GetHashCode(_expected) ^ GetHashCode(_actual);
}
private static int GetHashCode(object o)
{
if (o == null)
{
return 0;
}
return o.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (obj.GetType() != typeof(VisitedComparison))
{
return false;
}
var other = (VisitedComparison) obj;
return _expected == other._expected &&
_actual == other._actual;
}
}
#endregion
#region RegionalIgnoreTracker Helper
private class RegionalIgnoreTracker : IDisposable
{
private readonly string _fieldName;
private readonly Type _fieldType;
public RegionalIgnoreTracker(string fieldName)
{
if (!_globallyIgnoredNames.Add(fieldName))
{
_globallyIgnoredNames.Add(fieldName);
_fieldName = fieldName;
}
}
public RegionalIgnoreTracker(Type fieldType)
{
if (!_globallyIgnoredTypes.Add(fieldType))
{
_globallyIgnoredTypes.Add(fieldType);
_fieldType = fieldType;
}
}
public void Dispose()
{
if (_fieldName != null)
{
_globallyIgnoredNames.Remove(_fieldName);
}
if (_fieldType != null)
{
_globallyIgnoredTypes.Remove(_fieldType);
}
}
}
#endregion
#region RegionalWithinTracker Helper
private class RegionalWithinTracker : IDisposable
{
public RegionalWithinTracker(object tolerance)
{
_regionalTolerance = tolerance;
}
public void Dispose()
{
_regionalTolerance = null;
}
}
#endregion
#region IgnoreContentsAttribute
[AttributeUsage(AttributeTargets.Field)]
public sealed class IgnoreContentsAttribute : Attribute
{
}
#endregion
}
public class DatesEqualConstraint : EqualConstraint
{
private readonly object _expected;
public DatesEqualConstraint(object expectedValue) : base(expectedValue)
{
_expected = expectedValue;
}
public override bool Matches(object actualValue)
{
if (tolerance != null && tolerance is TimeSpan)
{
if (_expected is DateTime && actualValue is DateTime)
{
var expectedDate = (DateTime) _expected;
var actualDate = (DateTime) actualValue;
var toleranceSpan = (TimeSpan) tolerance;
if ((actualDate - expectedDate).Duration() <= toleranceSpan)
{
return true;
}
}
tolerance = null;
}
return base.Matches(actualValue);
}
}
}
This is actually a simple process. Using reflection you can compare each field on the object.
public static Boolean ObjectMatches(Object x, Object y)
{
if (x == null && y == null)
return true;
else if ((x == null && y != null) || (x != null && y == null))
return false;
Type tx = x.GetType();
Type ty = y.GetType();
if (tx != ty)
return false;
foreach(FieldInfo field in tx.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
if (field.FieldType.IsValueType && (field.GetValue(x).ToString() != field.GetValue(y).ToString()))
return false;
else if (field.FieldType.IsClass && !ObjectMatches(field.GetValue(x), field.GetValue(y)))
return false;
}
return true;
}
Using the Nuget suggested by Jesse and this code I managed to compare two objects with great results.
using KellermanSoftware.CompareNetObjects;
using System;
namespace MyProgram.UnitTestHelper
{
public class ObjectComparer
{
public static bool ObjectsHaveSameValues(object first, object second)
{
CompareLogic cl = new CompareLogic();
ComparisonResult result = cl.Compare(first, second);
if (!result.AreEqual)
Console.WriteLine(result.DifferencesString);
return result.AreEqual;
}
}
}
Here is a simple comparer that we've used with unit testing to assert that two objects have equal properties. It's a mash-up of ideas found in various articles, and handles circular references.
public static class TestHelper
{
public static void AssertAreEqual(Object expected, Object actual, String name)
{
// Start a new check with an empty list of actual objects checked
// The list of actual objects checked is used to ensure that circular references don't result in infinite recursion
List<Object> actualObjectsChecked = new List<Object>();
AssertAreEqual(expected, actual, name, actualObjectsChecked);
}
private static void AssertAreEqual(Object expected, Object actual, String name, List<Object> actualObjectsChecked)
{
// Just return if already checked the actual object
if (actualObjectsChecked.Contains(actual))
{
return;
}
actualObjectsChecked.Add(actual);
// If both expected and actual are null, they are considered equal
if (expected == null && actual == null)
{
return;
}
if (expected == null && actual != null)
{
Assert.Fail(String.Format("The actual value of {0} was not null when null was expected.", name));
}
if (expected != null && actual == null)
{
Assert.Fail(String.Format("The actual value of {0} was null when an instance was expected.", name));
}
// Get / check type info
// Note: GetType always returns instantiated (i.e. most derived) type
Type expectedType = expected.GetType();
Type actualType = actual.GetType();
if (expectedType != actualType)
{
Assert.Fail(String.Format("The actual type of {0} was not the same as the expected type.", name));
}
// If expected is a Primitive, Value, or IEquatable type, assume Equals is sufficient to check
// Note: Every IEquatable type should have also overridden Object.Equals
if (expectedType.IsPrimitive || expectedType.IsValueType || expectedType.IsIEquatable())
{
Assert.IsTrue(expected.Equals(actual), "The actual {0} is not equal to the expected.", name);
return;
}
// If expected is an IEnumerable type, assume comparing enumerated items is sufficient to check
IEnumerable<Object> expectedEnumerable = expected as IEnumerable<Object>;
IEnumerable<Object> actualEnumerable = actual as IEnumerable<Object>;
if ((expectedEnumerable != null) && (actualEnumerable != null))
{
Int32 actualEnumerableCount = actualEnumerable.Count();
Int32 expectedEnumerableCount = expectedEnumerable.Count();
// Check size first
if (actualEnumerableCount != expectedEnumerableCount)
{
Assert.Fail(String.Format("The actual number of enumerable items in {0} did not match the expected number.", name));
}
// Check items in order, assuming order is the same
for (int i = 0; i < actualEnumerableCount; ++i)
{
AssertAreEqual(expectedEnumerable.ElementAt(i), actualEnumerable.ElementAt(i), String.Format("{0}[{1}]", name, i), actualObjectsChecked);
}
return;
}
// If expected is not a Primitive, Value, IEquatable, or Ienumerable type, assume comparing properties is sufficient to check
// Iterate through properties
foreach (PropertyInfo propertyInfo in actualType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
// Skip properties that can't be read or require parameters
if ((!propertyInfo.CanRead) || (propertyInfo.GetIndexParameters().Length != 0))
{
continue;
}
// Get properties from both
Object actualProperty = propertyInfo.GetValue(actual, null);
Object expectedProperty = propertyInfo.GetValue(expected, null);
AssertAreEqual(expectedProperty, actualProperty, String.Format("{0}.{1}", name, propertyInfo.Name), actualObjectsChecked);
}
}
public static Boolean IsIEquatable(this Type type)
{
return type.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEquatable<>));
}
}

Categories