Override ToString() implementation of anonymous objects - c#

var sample = new
{
Time = DateTime.Now,
Name = "Hello"
};
Trace.TraceInformation("{0}", sample);
outputs as
ProcessInvocation86.exe Information: 0 : { Time = 04.11.2012 22:07:52,
Name = Hello }
I'd like different formatting in my application. Is there a way to change the implementation of ToString() for anonymous objects in C#? Maybe some static field per AppDomain or something?

No, you can't do this - ToString, Equals, and GetHashCode have default implementation provided by framework. To override this functionality you should inherit from your anonymous type, which is impossible.
Use String.Format to get desired output.

As far as im aware, there is no way to override the default ToString behaviour.
Might be worthwhile looking at some of the posts from Eric Lippert about anonymous types: http://blogs.msdn.com/b/ericlippert/archive/tags/anonymous+types/
Probably best to create a simple class for this purpose:
e.g.
public class MyClass
{
public DateTime Time { get; set; }
public string Name { get; set; }
public override string ToString()
{
return string.Format("Time = {0}. Name = {1}.", Time, Name);
}
}

I know, some guys will actually punch me for such a solution and I agree, that you shouldn't use it in production. If you have specific functionality for some bunch of data - this should definitely go to separate class. But for minor issues, you can use a little of reflection like this to write some custom formatter (I repeat, I'm not suggesting to use it in production ):
private string FormatProperties<T> (T obj)
{
string result = "";
var type = typeof(T);
foreach (var prop in type.GetProperties())
{
result += string.Format("{0}:{1}\r\n", prop.Name, prop.GetValue(obj));
}
return result;
}
Then the call
var anon = new {Name = "Ilya", Surname = "Ivanov"};
Console.WriteLine (FormatProperties(anon));
Will result in printed
Name:Ilya
Surname:Ivanov
And then you can cache types for performance benefits and get into another types of troubles.

this isn't exactly ideal.. but you could create an extension method that takes a function that does the formatting.
Following example formatted for LinqPad
EXAMPLE
void Main()
{
var sample = new
{
Time = DateTime.Now,
Name = "Hello",
};
sample.ToAnonString(()=>sample.Name).Dump();
}
public static class ovs{
public static string ToAnonString(this object o,Func<string> exp){
return exp();
}
}

Related

the easest way of findind the difference of two objects of the same class [duplicate]

The project I'm working on needs some simple audit logging for when a user changes their email, billing address, etc. The objects we're working with are coming from different sources, one a WCF service, the other a web service.
I've implemented the following method using reflection to find changes to the properties on two different objects. This generates a list of the properties that have differences along with their old and new values.
public static IList GenerateAuditLogMessages(T originalObject, T changedObject)
{
IList list = new List();
string className = string.Concat("[", originalObject.GetType().Name, "] ");
foreach (PropertyInfo property in originalObject.GetType().GetProperties())
{
Type comparable =
property.PropertyType.GetInterface("System.IComparable");
if (comparable != null)
{
string originalPropertyValue =
property.GetValue(originalObject, null) as string;
string newPropertyValue =
property.GetValue(changedObject, null) as string;
if (originalPropertyValue != newPropertyValue)
{
list.Add(string.Concat(className, property.Name,
" changed from '", originalPropertyValue,
"' to '", newPropertyValue, "'"));
}
}
}
return list;
}
I'm looking for System.IComparable because "All numeric types (such as Int32 and Double) implement IComparable, as do String, Char, and DateTime." This seemed the best way to find any property that's not a custom class.
Tapping into the PropertyChanged event that's generated by the WCF or web service proxy code sounded good but doesn't give me enough info for my audit logs (old and new values).
Looking for input as to if there is a better way to do this, thanks!
#Aaronaught, here is some example code that is generating a positive match based on doing object.Equals:
Address address1 = new Address();
address1.StateProvince = new StateProvince();
Address address2 = new Address();
address2.StateProvince = new StateProvince();
IList list = Utility.GenerateAuditLogMessages(address1, address2);
"[Address] StateProvince changed from
'MyAccountService.StateProvince' to
'MyAccountService.StateProvince'"
It's two different instances of the StateProvince class, but the values of the properties are the same (all null in this case). We're not overriding the equals method.
IComparable is for ordering comparisons. Either use IEquatable instead, or just use the static System.Object.Equals method. The latter has the benefit of also working if the object is not a primitive type but still defines its own equality comparison by overriding Equals.
object originalValue = property.GetValue(originalObject, null);
object newValue = property.GetValue(changedObject, null);
if (!object.Equals(originalValue, newValue))
{
string originalText = (originalValue != null) ?
originalValue.ToString() : "[NULL]";
string newText = (newText != null) ?
newValue.ToString() : "[NULL]";
// etc.
}
This obviously isn't perfect, but if you're only doing it with classes that you control, then you can make sure it always works for your particular needs.
There are other methods to compare objects (such as checksums, serialization, etc.) but this is probably the most reliable if the classes don't consistently implement IPropertyChanged and you want to actually know the differences.
Update for new example code:
Address address1 = new Address();
address1.StateProvince = new StateProvince();
Address address2 = new Address();
address2.StateProvince = new StateProvince();
IList list = Utility.GenerateAuditLogMessages(address1, address2);
The reason that using object.Equals in your audit method results in a "hit" is because the instances are actually not equal!
Sure, the StateProvince may be empty in both cases, but address1 and address2 still have non-null values for the StateProvince property and each instance is different. Therefore, address1 and address2 have different properties.
Let's flip this around, take this code as an example:
Address address1 = new Address("35 Elm St");
address1.StateProvince = new StateProvince("TX");
Address address2 = new Address("35 Elm St");
address2.StateProvince = new StateProvince("AZ");
Should these be considered equal? Well, they will be, using your method, because StateProvince does not implement IComparable. That's the only reason why your method reported that the two objects were the same in the original case. Since the StateProvince class does not implement IComparable, the tracker just skips that property entirely. But these two addresses are clearly not equal!
This is why I originally suggested using object.Equals, because then you can override it in the StateProvince method to get better results:
public class StateProvince
{
public string Code { get; set; }
public override bool Equals(object obj)
{
if (obj == null)
return false;
StateProvince sp = obj as StateProvince;
if (object.ReferenceEquals(sp, null))
return false;
return (sp.Code == Code);
}
public bool Equals(StateProvince sp)
{
if (object.ReferenceEquals(sp, null))
return false;
return (sp.Code == Code);
}
public override int GetHashCode()
{
return Code.GetHashCode();
}
public override string ToString()
{
return string.Format("Code: [{0}]", Code);
}
}
Once you've done this, the object.Equals code will work perfectly. Instead of naïvely checking whether or not address1 and address2 literally have the same StateProvince reference, it will actually check for semantic equality.
The other way around this is to extend the tracking code to actually descend into sub-objects. In other words, for each property, check the Type.IsClass and optionally the Type.IsInterface property, and if true, then recursively invoke the change-tracking method on the property itself, prefixing any audit results returned recursively with the property name. So you'd end up with a change for StateProvinceCode.
I use the above approach sometimes too, but it's easier to just override Equals on the objects for which you want to compare semantic equality (i.e. audit) and provide an appropriate ToString override that makes it clear what changed. It doesn't scale for deep nesting but I think it's unusual to want to audit that way.
The last trick is to define your own interface, say IAuditable<T>, which takes a second instance of the same type as a parameter and actually returns a list (or enumerable) of all of the differences. It's similar to our overridden object.Equals method above but gives back more information. This is useful for when the object graph is really complicated and you know you can't rely on Reflection or Equals. You can combine this with the above approach; really all you have to do is substitute IComparable for your IAuditable and invoke the Audit method if it implements that interface.
This project on github checks nearly any type of property and can be customized as you need.
You might want to look at Microsoft's Testapi It has an object comparison api that does deep comparisons. It might be overkill for you but it could be worth a look.
var comparer = new ObjectComparer(new PublicPropertyObjectGraphFactory());
IEnumerable<ObjectComparisonMismatch> mismatches;
bool result = comparer.Compare(left, right, out mismatches);
foreach (var mismatch in mismatches)
{
Console.Out.WriteLine("\t'{0}' = '{1}' and '{2}'='{3}' do not match. '{4}'",
mismatch.LeftObjectNode.Name, mismatch.LeftObjectNode.ObjectValue,
mismatch.RightObjectNode.Name, mismatch.RightObjectNode.ObjectValue,
mismatch.MismatchType);
}
Here a short LINQ version that extends object and returns a list of properties that are not equal:
usage: object.DetailedCompare(objectToCompare);
public static class ObjectExtensions
{
public static List<Variance> DetailedCompare<T>(this T val1, T val2)
{
var propertyInfo = val1.GetType().GetProperties();
return propertyInfo.Select(f => new Variance
{
Property = f.Name,
ValueA = f.GetValue(val1),
ValueB = f.GetValue(val2)
})
.Where(v => !v.ValueA.Equals(v.ValueB))
.ToList();
}
public class Variance
{
public string Property { get; set; }
public object ValueA { get; set; }
public object ValueB { get; set; }
}
}
You never want to implement GetHashCode on mutable properties (properties that could be changed by someone) - i.e. non-private setters.
Imagine this scenario:
you put an instance of your object in a collection which uses GetHashCode() "under the covers" or directly (Hashtable).
Then someone changes the value of the field/property that you've used in your GetHashCode() implementation.
Guess what... your object is permanently lost in the collection since the collection uses GetHashCode() to find it! You've effectively changed the hashcode value from what was originally placed in the collection. Probably not what you wanted.
Liviu Trifoi solution: Using CompareNETObjects library.
GitHub - NuGet package - Tutorial.
I think this method is quite neat, it avoids repetition or adding anything to classes. What more are you looking for?
The only alternative would be to generate a state dictionary for the old and new objects, and write a comparison for them. The code for generating the state dictionary could reuse any serialisation you have for storing this data in the database.
The my way of Expression tree compile version. It should faster than PropertyInfo.GetValue.
static class ObjDiffCollector<T>
{
private delegate DiffEntry DiffDelegate(T x, T y);
private static readonly IReadOnlyDictionary<string, DiffDelegate> DicDiffDels;
private static PropertyInfo PropertyOf<TClass, TProperty>(Expression<Func<TClass, TProperty>> selector)
=> (PropertyInfo)((MemberExpression)selector.Body).Member;
static ObjDiffCollector()
{
var expParamX = Expression.Parameter(typeof(T), "x");
var expParamY = Expression.Parameter(typeof(T), "y");
var propDrName = PropertyOf((DiffEntry x) => x.Prop);
var propDrValX = PropertyOf((DiffEntry x) => x.ValX);
var propDrValY = PropertyOf((DiffEntry x) => x.ValY);
var dic = new Dictionary<string, DiffDelegate>();
var props = typeof(T).GetProperties();
foreach (var info in props)
{
var expValX = Expression.MakeMemberAccess(expParamX, info);
var expValY = Expression.MakeMemberAccess(expParamY, info);
var expEq = Expression.Equal(expValX, expValY);
var expNewEntry = Expression.New(typeof(DiffEntry));
var expMemberInitEntry = Expression.MemberInit(expNewEntry,
Expression.Bind(propDrName, Expression.Constant(info.Name)),
Expression.Bind(propDrValX, Expression.Convert(expValX, typeof(object))),
Expression.Bind(propDrValY, Expression.Convert(expValY, typeof(object)))
);
var expReturn = Expression.Condition(expEq
, Expression.Convert(Expression.Constant(null), typeof(DiffEntry))
, expMemberInitEntry);
var expLambda = Expression.Lambda<DiffDelegate>(expReturn, expParamX, expParamY);
var compiled = expLambda.Compile();
dic[info.Name] = compiled;
}
DicDiffDels = dic;
}
public static DiffEntry[] Diff(T x, T y)
{
var list = new List<DiffEntry>(DicDiffDels.Count);
foreach (var pair in DicDiffDels)
{
var r = pair.Value(x, y);
if (r != null) list.Add(r);
}
return list.ToArray();
}
}
class DiffEntry
{
public string Prop { get; set; }
public object ValX { get; set; }
public object ValY { get; set; }
}

Looking for a more elegant way to perform custom get/set functionality on class properties

I'm trying to find a way to refine some code that I have. I work with a 3rd party API that has a REALLY complicated API request object (I'll call it ScrewyAPIObject) that has tons of repetition in it. Every time you want to set a particular property, it can take a page worth of code. So I built a library to provide a simplified wrapper around the setting/getting of its properties (and to handle some value preprocessing).
Here's a stripped-down view of how it works:
public abstract class LessScrewyWrapper
{
protected ScrewyAPIRequest _screwy = new ScrewyAPIRequest();
public void Set(string value)
{
Set(_getPropertyName(), value);
}
public void Set(string property, string value)
{
// Preprocess value and set the appropriate property on _screwy. This part
// has tons of code, but we'll just say it looks like this:
_screwy.Fields[property] = "[" + value + "]";
}
protected string _getPropertyName()
{
// This method looks at the Environment.StackTrace, finds the correct set_ or
// get_ method call and extracts the property name and returns it.
}
public string Get()
{
// Get the property name being access
string property = _getPropertyName();
// Search _screwy's structure for the value and return it. Again, tons of code,
// so let's just say it looks like this:
return _screwy.Fields[property];
}
public ScrewyAPIRequest GetRequest()
{
return _screwy;
}
}
Then I have a child class that represents one specific type of the screwy API request (there are multiple kinds that all have the same structure but different setups). Let's just say this one has two string properties, PropertyA and PropertyB:
public class SpecificScrewyAPIRequest : LessScrewyWrapper
{
public string PropertyA
{
get { return Get(); }
set { Set(value); }
}
public string PropertyB
{
get { return Get(); }
set { Set(value); }
}
}
Now when I want to go use this library, I can just do:
SpecificScrewyAPIRequest foo = new SpecificScrewyAPIRequest();
foo.PropertyA = "Hello";
foo.PropertyB = "World";
ScrewyAPIRequest request = foo.GetRequest();
This works fine and dandy, but there are different kinds of data types, which involves using generics in my Set/Get methods, and it just makes the child classes look a little kludgy when you're dealing with 50 properties and 50 copies of Get() and Set() calls.
What I'd LIKE to do is simply define fields, like this:
public class SpecificScrewyAPIRequest : LessScrewyWrapper
{
public string PropertyA;
public string PropertyB;
}
It would make the classes look a LOT cleaner. The problem is that I don't know of a way to have .NET make a callback to my custom handlers whenever the values of the fields are accessed and modified.
I've seen someone do something like this in PHP using the __set and __get magic methods (albeit in a way they were not intended to be used), but I haven't found anything similar in C#. Any ideas?
EDIT: I've considered using an indexed approach to my class with an object-type value that is cast to its appropriate type afterwards, but I'd prefer to retain the approach where the property is defined with a specific type.
Maybe in your case DynamicObject is a suitable choice:
public class ScrewyDynamicWrapper : DynamicObject
{
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
// get your actual value based on the property name
Console.WriteLine("Get Property: {0}", binder.Name);
result = null;
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
// set your actual value based on the property name
Console.WriteLine("Set Property: {0} # Value: {2}", binder.Name, value);
return true;
}
}
And define your wrapper objects:
public class ScrewyWrapper
{
protected dynamic ActualWrapper = new ScrewyDynamicWrapper();
public int? PropertyA
{
get { return ActualWrapper.PropertyA; }
set { ActualWrapper.PropertyA = value; }
}
public string PropertyB
{
get { return ActualWrapper.PropertyB; }
set { ActualWrapper.PropertyB = value; }
}
}
However, you can't rely on the property type inside ScrewyDynamicWrapper with this approach, so it depends on your actual API requirements - maybe it won't work for you.
Instead of fields, If you define as property in class, It will be more easy.
public class SpecificScrewyAPIRequest
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
}
Then you can create extension generic method to return ScrewyAPIRequest object.
public static class Extensions
{
public static ScrewyAPIRequest GetRequest<T>(this T obj)
{
ScrewyAPIRequest _screwy = new ScrewyAPIRequest();
var test= obj.GetType().GetProperties();
foreach (var prop in obj.GetType().GetProperties())
{
_screwy.Fields[prop.Name] = prop.GetValue(obj, null);
}
return _screwy;
}
}
Now you can easily get ScrewyAPIRequest from any class object.
Your code will look like following.
SpecificScrewyAPIRequest foo = new SpecificScrewyAPIRequest();
foo.PropertyA = "Hello";
foo.PropertyB = "World";
ScrewyAPIRequest request = foo.GetRequest();

Get and set value from bindinglist<T> with coordinates c#

I'm having trouble getting and setting the values of an item in a bindinglist with coordinates when the type vary.
For example, let's say I have three classes:
public class Client{
public string Name{ get; set; }
}
public class Debt{
public string AccountType{ get; set; }
public int DebtValue { get; set; }
}
public class Accounts{
public string Owner{ get; set; }
public int AccountNumber { get; set; }
public bool IsChekingAccount { get; set; }
}
and then, three bindinglists (imagine they are populated):
public BindingList<Client> listOne;
public BindingList<Debt> listTwo;
public BindingList<Accounts> listThree;
I'm trying to create an extension method that returns an Object with the value requested, or sets the value if it is provided.
public static Object GetValueByCoordinates(this IBindingList list, int x, int y) { /*some magic*/ }
public static Object SetValueByCoordinates(this IBindingList list, int x, int y, Object value) { /*some other magic*/ }
So, for instance, I need to be able to set the value of the item (2,3) in the listThree, and the value (1,1) in listTwo:
listThree.SetValueByCoordinates(2,3,false);
listThree.SetValueByCoordinates(1,1,"My self");
or get the value (1,1) and (2,2) from listOne and listTwo:
string result = listOne.GetValueByCoordinates(1,1).ToString();
intresult = Convert.ToInt32(listOne.GetValueByCoordinates(1,1));
How would you achieve such behavior? i was thinking of using reflection, but I know little to nothing about it.
please note that the methods MUST be called that way, so using something like this must be avoided
public static Object GetValueByCoordinates<T>(this BindingList<T> list, int x, int y) { /*some magic*/ }
Any help will be appreciated.
As mentioned, I am very skeptical that the approach you're asking for help with is likely to be the best or most appropriate way to address whatever the broader issue you're trying to solve is. It can be done (and without very much difficulty), but the resulting code is difficult to maintain, error-prone, and not very readable (which leads to the first two problems).
That said, there are lots of different ways to implement the specific behavior you're asking for. And even if this is not the best way to solve your current problem, the basic techniques are useful to know for other types of problems. With that in mind, here are two of the most obvious ways you might address your problem.
Manually configure a mapping from indexes to getters and setters:
IMHO this is the most preferable way. Not because it's elegant or easy to extend, but specifically because it's not either of those things. Requiring code maintainers to explicitly create the data structure elements to support each type and property that you want to handle will discourage a proliferation of this technique for other related problems, and even for the current problem. It could even encourage someone to spend a little more time thinking about the broader problem so as to find a better strategy.
This approach does have the advantage that it is reasonably performant. Because the code is generated at compile time, the only real overhead is the boxing that occurs for value types. There's some casting but for the reference types that overhead should be practically unmeasurable, and even the boxing overhead may not show up on a profile, depending on how intensively this code might be used.
This particular solution looks like this:
static class ManualIndexedProperty
{
public static void SetValueByCoordinates(this IBindingList list, int x, int y, object value)
{
object o = list[x];
_typeToSetter[o.GetType()][y](o, value);
}
public static object GetValueByCoordinates(this IBindingList list, int x, int y)
{
object o = list[x];
return _typeToGetter[o.GetType()][y](o);
}
private static readonly Dictionary<Type, Func<object, object>[]> _typeToGetter =
new Dictionary<Type, Func<object, object>[]>()
{
{
typeof(Client),
new Func<object, object>[]
{
o => ((Client)o).Name
}
},
{
typeof(Debt),
new Func<object, object>[]
{
o => ((Debt)o).AccountType,
o => ((Debt)o).DebtValue,
}
},
{
typeof(Accounts),
new Func<object, object>[]
{
o => ((Accounts)o).Owner,
o => ((Accounts)o).AccountNumber,
o => ((Accounts)o).IsChekingAccount,
}
},
};
private static readonly Dictionary<Type, Action<object, object>[]> _typeToSetter =
new Dictionary<Type, Action<object, object>[]>()
{
{
typeof(Client),
new Action<object, object>[]
{
(o1, o2) => ((Client)o1).Name = (string)o2
}
},
{
typeof(Debt),
new Action<object, object>[]
{
(o1, o2) => ((Debt)o1).AccountType = (string)o2,
(o1, o2) => ((Debt)o1).DebtValue = (int)o2,
}
},
{
typeof(Accounts),
new Action<object, object>[]
{
(o1, o2) => ((Accounts)o1).Owner = (string)o2,
(o1, o2) => ((Accounts)o1).AccountNumber = (int)o2,
(o1, o2) => ((Accounts)o1).IsChekingAccount = (bool)o2,
}
},
};
}
Two dictionaries are declared, one each for setting and getting property values. The dictionaries map the element object's type to an array of delegate instances to perform the actual work. Each delegate instance references an anonymous method which has been hand-coded to perform the necessary operation.
One major advantage to this approach is that it is explicit and obvious what index corresponds to what property for each type.
This approach will be tedious and time-consuming to set up if you are dealing with any significant number of types and/or properties. But IMHO that's a good thing. As I noted above, hopefully the pain of this approach can help convince someone to abandon the idea of accessing the properties by index altogether. :)
If this kind of tedium is unacceptable and yet you still insist on the indexed-property-access approach, then you can in fact use reflection as an alternative…
Use reflection to access the properties:
This technique is more dynamic. Once implemented, it works for any type object without modification, and does not require additional work to support new types.
One major disadvantage is that in order to produce consistent, predictable results, it sorts the properties by name. This ensures that changes in the C# compiler and/or CLR won't break the code, but it means you can't add or remove properties from a type without updating the code that is accessing those properties by index.
In my demo usage code (see further below), I address this maintenance issue by declaring enum types that provide int values for property names. This would be a good way to help reduce the maintenance overhead if the code is actually referring to the properties with literal index values.
However, it's possible your scenario involves dynamically accessing the property values by index, e.g. in a serialization scenario or similar. In that case, you will also need to add something that can remap or otherwise deal with changes in the index values should properties be added or removed to the types.
Frankly, either way this issue of the types indexes changing is one big reason I'd strongly recommend against this indexed access to properties in the first place. But again, if you insist…
static class ReflectionIndexedProperty
{
public static void SetValueByCoordinates(this IBindingList list, int x, int y, object value)
{
object o = list[x];
GetProperty(o, y).SetValue(o, value);
}
public static object GetValueByCoordinates(this IBindingList list, int x, int y)
{
object o = list[x];
return GetProperty(o, y).GetValue(o);
}
private static PropertyInfo GetProperty(object o, int index)
{
Type type = o.GetType();
PropertyInfo[] properties;
if (!_typeToProperty.TryGetValue(type, out properties))
{
properties = type.GetProperties();
Array.Sort(properties, (p1, p2) => string.Compare(p1.Name, p2.Name, StringComparison.OrdinalIgnoreCase));
_typeToProperty[type] = properties;
}
return properties[index];
}
private static readonly Dictionary<Type, PropertyInfo[]> _typeToProperty = new Dictionary<Type, PropertyInfo[]>();
}
In this version, the code retrieves the array of PropertyInfo objects for a given type, sorts that array by name, retrieves the appropriate PropertyInfo object for the given index, and then uses that PropertyInfo object to set or get the property value, as appropriate.
Reflection incurs a significant run-time performance overhead. This particular implementation mitigates some of that overhead by caching the sorted arrays of PropertyInfo objects. That way, they only need to be created once, the first time the code has to handle an object of the given type.
Demo code:
As I mentioned, to make it easier to compare the two approaches without having to go to each method call and hand-change an integer literal used for the call, I created some simple enum types to represent the property indexes. I also wrote some code to initialize some lists that could be tested.
Note: one very important thing to point out is that in your question you were not very consistent about how you were indexing the properties. In my code example, I have chose to stick with a 0-based index (consistent with the natural indexing used in C# arrays and other collections). You can of course use a different base (e.g. 1-based indexing), but you will need to make sure you are entirely consistent throughout the code (including subtracting 1 from the passed-in index when actually indexing an array).
My demo code looks like this:
class Program
{
static void Main(string[] args)
{
BindingList<Client> listOne = new BindingList<Client>()
{
new Client { Name = "ClientName1" },
new Client { Name = "ClientName2" },
new Client { Name = "ClientName3" },
};
BindingList<Debt> listTwo = new BindingList<Debt>()
{
new Debt { AccountType = "AccountType1", DebtValue = 29 },
new Debt { AccountType = "AccountType2", DebtValue = 31 },
new Debt { AccountType = "AccountType3", DebtValue = 37 },
};
BindingList<Accounts> listThree = new BindingList<Accounts>()
{
new Accounts { Owner = "Owner1", AccountNumber = 17, IsChekingAccount = false },
new Accounts { Owner = "Owner2", AccountNumber = 19, IsChekingAccount = true },
new Accounts { Owner = "Owner3", AccountNumber = 23, IsChekingAccount = true },
};
LogList(listThree);
listThree.SetValueByCoordinates(2, (int)AccountsProperty.IsChekingAccount, false);
listThree.SetValueByCoordinates(1, (int)AccountsProperty.Owner, "My self");
LogList(listThree);
string result1 = (string)listOne.GetValueByCoordinates(0, (int)ClientProperty.Name);
int result2 = (int)listTwo.GetValueByCoordinates(1, (int)DebtProperty.DebtValue);
LogList(listOne);
LogList(listTwo);
Console.WriteLine("result1: " + result1);
Console.WriteLine("result2: " + result2);
}
static void LogList<T>(BindingList<T> list)
{
foreach (T t in list)
{
Console.WriteLine(t);
}
Console.WriteLine();
}
}
Note that I use simple casting to convert from object to the specific type, both with setting property values and getting them. This is a much better approach than e.g. calling ToString() or Convert.ToInt32(); you know exactly what the type is supposed to be, and it's either an actual instance of that type (for reference types) or a boxed instance (for value types), and either way a cast does exactly what you need.
I also added ToString() overrides to your example classes to make it easier to see the output:
public class Client
{
public string Name { get; set; }
public override string ToString()
{
return "{" + Name + "}";
}
}
public class Debt
{
public string AccountType { get; set; }
public int DebtValue { get; set; }
public override string ToString()
{
return "{" + AccountType + ", " + DebtValue + "}";
}
}
public class Accounts
{
public string Owner { get; set; }
public int AccountNumber { get; set; }
public bool IsChekingAccount { get; set; }
public override string ToString()
{
return "{" + Owner + ", " + AccountNumber + ", " + IsChekingAccount + "}";
}
}
Finally, here are the enum declarations used:
Manual indexing:
enum ClientProperty
{
Name = 0
}
enum DebtProperty
{
AccountType = 0,
DebtValue = 1
}
enum AccountsProperty
{
Owner = 0,
AccountNumber = 1,
IsChekingAccount = 2,
}
Reflection/sorted by name:
enum ClientProperty
{
Name = 0
}
enum DebtProperty
{
AccountType = 0,
DebtValue = 1
}
enum AccountsProperty
{
AccountNumber = 0,
IsChekingAccount = 1,
Owner = 2,
}
Of course, these could both have been the same values. That is, while you don't have control over the sort order, once the property names are given, the manual version could have declared the manually-written lambdas in sorted-by-name order so that the same indexes would have worked either way. It doesn't matter too much what you decide to do; it just has to be consistent.
Final thoughts…
Have I mentioned yet how strongly I would recommend against building any significant amount of code around this technique? It's not at all clear what your actual bigger-picture problem you're trying to solve is, but there are just a lot of different ways for this to go wrong, and it is likely to lead to lots of hard-to-find, time-consuming-to-fix bugs in the code.
In terms of performance, the above should not be too bad as long as you are not executing the code in a tight loop for huge numbers of objects and property values. The manual (first) example in particular should be relatively fast. It is possible to achieve the generalized design of the reflection-based approach with the minimal overhead of the manual approach by using the Expression type. That's a bit more complicated, but would have the advantage that you can generate expressions dynamically that wind up being effectively the compiled-code implementation of the manual approach.

Is there a jQuery extend in c#?

var _Contact = new ContactLstModel {
ContactName="xxxxxx",
EmailAddr="yyyyyy",
ContactNo="ddddddd",
SelectedContactType="dddd"
};
var _ContactOption= new ContactLstModel{
ContactType= new List<SelectListItem>(){
new SelectListItem{
Text="sss",Value="ddd"
}
}
};
as you can see both are of the same model ContactLstModel. Now how do I combine both into one?
Like in jQuery, we have $.extend(dest,source);
Is there an equivalent in C#?
There is not a built-in equivalent of $.extend in C# and .NET 4.5.
However you can find many examples of people trying to achieve that kind of behavior using reflection in .NET. There are others who use serialization (JSON.NET etc.) to achieve similar behaviors . Another approach would be to use IOC containers like Automapper.
Here is an example how to merge your first object into the second object using Automapper IOC:
var expr = Mapper.CreateMap<ContactLstModel, ContactLstModel>().ForMember("ContactType", (conf) => { conf.Ignore(); });
var merged = Mapper.Map<ContactLstModel, ContactLstModel>(_Contact, _ContactOption);
With Automapper you can control how to map each single property from source to destination.
If you don't want external library dependencies, and want full control you can use a pure Reflection approach.
For example you could use something similar as the CopyValues method from this link and merge the second object properties with the first one using reflection.
CopyValues<ContactLstModel>(_Contact, _ContactOption);
So this line of code will copy the ContactType property values from the second object into the first one.
CopyValues uses reflection to loop through the properties of the objects:
public static void CopyValues<T>(T target, T source)
{
Type t = typeof(T);
var properties = t.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);
foreach (var prop in properties)
{
var value = prop.GetValue(source, null);
if (value != null)
prop.SetValue(target, value, null);
}
}
Of course this does not support everything jquery extend does (merging, shallow and deep cloning into a new object etc.), but it can satisfy your current needs. You can extend on these principles and build a more comprehensive solution.
However have in mind that C# is not a language like Javascript, and the cost of doing reflection is much higher in C#, while in Javascript the properties of a prototype can be listed with a cheap for-in iteration, or with a call to Object.keys().
You could do it with an extension method:
public static class ContactModelExtensions {
public static ContactModel Extend(this ContactModel first, ContactModel replacement) {
if (!replacement.ContactsName.IsNullOrEmpty()) // or whatever criteria you want
{
first.ContactsName = replacement.ContactsName;
}
// similar assignment for all other properties
return first; // since we return the first one, properties not set in override
// will be untouched
}
}
Now, you can just
var extendedContact = _Contact.Extend(_ContactOptions);
to get it done.
You can use some frameworks for do it. For example with ValueInjecter:
public class NoNullsInjection : ConventionInjection
{
protected override bool Match(ConventionInfo c)
{
return c.SourceProp.Name == c.TargetProp.Name
&& c.SourceProp.Value != null;
}
}
class A
{
public string a { get; set; }
public string b { get; set; }
}
static void Main(string[] args)
{
A a1 = new A() { a = "123" };
A a2 = new A() { b = "456" };
A c = new A();
c.InjectFrom(new NoNullsInjection(),a1,a2);
// "c" now have a="123", b="456"
}

How to instantiate PrivateType of inner private class

I was trying to setup a unit test for a private inner class, but had very little success:
namespace Stats.Model
{
public class DailyStat
{
private class DailyStatKey // The one to test
{
private DateTime date;
public DateTime Date
{
get { return date; }
set { date = value.Date; }
}
public StatType Type { get; set; }
public override int GetHashCode()
{
return Date.Year * 1000000 +
Date.Month * 10000 +
Date.Day * 100 +
(int)Type;
}
public override bool Equals(object obj)
{
DailyStatKey otherKey = obj as DailyStatKey;
if (otherKey == null)
return false;
return (this.Date == otherKey.Date && this.StatType == otherKey.StatType);
}
}
}
}
I tried this code:
PrivateType statKeyType = new PrivateType("Stats.Model", "Stats.Model.DailyStat.DailyStatKey");
as well as
PrivateType statKeyType = new PrivateType("Stats.Model", "DailyStat.DailyStatKey");
To no avail.
The assembly's name is "Stats.Model", and to me the type name looks correct too, but I just get an exception: "System.TypeLoadException: Could not load type"
So what am I doing wrong ?
PrivateType, to the best of my knowledge, is reflection based, and I'd guess it's pretty much intended for this scenario, as you cannot have a private class directly beneath a namespace.
EDIT:
Added full implementation of DailyStatKey. What I want to test is the uniqueness of my GetHashCode method. As you can see I try to fit a date + type into a single int.
Found a solution myself:
var parentType = typeof(DailyStat);
var keyType = parentType.GetNestedType("DailyKeyStat", BindingFlags.NonPublic);
//edited to use GetNestedType instead of just NestedType
var privateKeyInstance = new PrivateObject(Activator.CreateInstance(keyType, true));
privateKeyInstance.SetProperty("Date", DateTime.Now);
privateKeyInstance.SetProperty("Type", StatType.Foo);
var hashCode = (int)privateKeyInstance.Invoke("GetHashCode", null);
You can also use PrivateType directly as well:
PrivateType statKeyType = new PrivateType("Stats.Model", "Stats.Model.DailyStat+DailyStatKey");
Nested classes have a string format that's different from their namespace (which is Stats.Model.DailyStat.DailyStatKey) so the usage isn't obvious.
Since it is private the only class that can create the instance is DailyStat itself. Unless you make it non private reflection (activator) would be your only choice if you want to create the class although that would not be a good idea as you wont be able to use it directly unless you are able to cast it to a public enough type or interface
EDIT:
Since you are trying to do this for unit testing then effectively you shouldnt test this class as it is private. You would only be able to test it through any public interface of DailyStat.
You can code a public "GetDailyStatKey" method on parent class.
public class DailyStat
{
private class DailyStatKey // The one to test
{
}
public DailyStatKey GetDailyStatKey()
{
return new DailyStatKey();
}
}
Now you can write:
DailyStat v = new DailyStat();
var x = v.GetDailyStatKey();

Categories

Resources