Specifying dynamic properties for an object in C# - c#

I'm looking for a best practice to hold a dynamic set of properties for an object. The idea is to have a base object Person and allow users to add properties to it.
For example, I have a Person which has the basic properties of FirstName, LastName. User1 will add HairColor as string and User2 will add Height as int.
The point is to allow users to take the core object and dynamically add properties to it to match their needs, then I would want to persist it to DB and allow searching for those properties (MSSQL and SOLR).

From .Net 4.0 There is the ExpandoObject - that'll be your choice!
Before .Net 4.0 You can wrap a nice class with an hidden Dictionary<string, object> to hold your properties
EDIT Sample Code
In the sample below we create a class with some known properties and an expandable ExtraProperties
At the end we can iterate the ExpandoObject to get all its dynamically added values:
Note: ExpandoObject implements IEnumerable<KeyValuePair<string, object>>
class Program
{
static void Main(string[] args)
{
Person p1 = new Person();
p1.ExtraProperties.HairColor = "Green";
p1.ExtraProperties.DateOfGraduation = DateTime.UtcNow;
foreach (var prop in p1.ExtraProperties)
{
Console.WriteLine(prop.Key + ": " + prop.Value);
}
}
}
public class Person
{
private System.Dynamic.ExpandoObject _extraProperties = new System.Dynamic.ExpandoObject();
public string Name { get; set; }
public DateTime BornDate { get; set; }
public dynamic ExtraProperties
{
get { return _extraProperties; }
}
}

And to get the Expando Object to Solr you could use Sornet with fully loose mapping.

I had a similar use case I've solved with this class
public class User
{
#region Private Fields
private readonly Dictionary<string, string> _keyValues = new Dictionary<string, string>();
#endregion
#region Public Properties
/// <summary>
/// Gets the field names.
/// </summary>
/// <value>
/// The field names.
/// </value>
public IEnumerable<string> FieldNames
{
get { return _keyValues.Keys; }
}
#endregion
#region Public Methods
/// <summary>
/// Gets or sets the <see cref="System.String" /> for the specified fieldName.
/// </summary>
/// <value>
/// The <see cref="System.String" />.
/// </value>
/// <param name="fieldName">The field name.</param>
/// <returns>The value for the field if it could be found; otherwise null</returns>
public string this[string fieldName]
{
get
{
string value;
return _keyValues.TryGetValue(fieldName, out value) ? value : null;
}
set { _keyValues.Add(fieldName, value); }
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
string res = string.Empty;
foreach (KeyValuePair<string, string> pair in _keyValues)
{
res += string.Format("{0}={1};", pair.Key, pair.Value);
}
return res.TrimEnd(';');
}
#endregion
}
Note that all properties will be of type string this case. All properties can be accessed with an indexer with e.g. user["Name"]

Related

Create variable of a generic class from a generic class

I want to create a class that can keep a number between to values. Here for I have created my first two generic classes.
The first called LimitRang and keep two limit rang variables; one for the lower rang and for the top rang. The second called NumberLimitRang and keep the number and the first class LimitRang.
When I try to create the variable mvarRang, how is a LimitRang var, in the constructor of NumberLimitRang I receive the error : 'Cannot implicitly convert type 'VariableTypes.Supplement.LimitRang' to 'T'.
My code for LimitRang:
namespace VariableTypes.Supplement
{
/// <summary>
/// Manage the boundaries for a number.
/// </summary>
/// <typeparam name="T">The numberic type for the limit parameters</typeparam>
public class LimitRang<T> where T : IComparable
{
private T mvarLowestLimitNumber;
private T mvarHighestLimitNumber;
/// <summary>
/// The default constructor (between 0 and 100)
/// </summary>
public LimitRang()
{
if (Functions.IsNumericType(typeof(T)))
{
try
{
mvarLowestLimitNumber = (T)Convert.ChangeType(0, typeof(T));
mvarHighestLimitNumber = (T)Convert.ChangeType(100, typeof(T));
}
catch
{
mvarLowestLimitNumber = default(T);
mvarHighestLimitNumber = default(T);
}
}
}
}
}
My code for NumberLimitRang:
namespace VariableTypes
{
/// <summary>
/// Can contain a number that need to be between or equal to two limit numbers
/// </summary>
public class NumberLimitRang<T> where T : IComparable
{
private Supplement.LimitRang<T> mvarRang;
private T mvarNumber;
/// <summary>
/// The default constructor (between 0 and 100/Number = 0)
/// </summary>
public NumberLimitRang(T mvarRang)
{
mvarRang = new Supplement.LimitRang<T>();
mvarNumber = (T)Convert.ChangeType(0, typeof(T));
}
}
}
Even when I replace the two T's into int, I still receive the error:
- private Supplement.LimitRang<int> mvarRang;
- mvarRang = new Supplement.LimitRang<int>();
Can you tell me what I do wrong?
Thx a lot
Problem is here:
public NumberLimitRang(T mvarRang)
{
mvarRang = new LimitRang<T>();
mvarNumber = (T)Convert.ChangeType(0, typeof(T));
}
You pass mvarRang as an argument and you have field with name mvarRang. But in method NumberLimitRang compiler uses mvarRang as argument, wich is type of T and tryes to replace it's value with new LimitRang<T>();.
So, first of all, rename field or argument. For example:
public class NumberLimitRang<T> where T : IComparable
{
private LimitRang<T> _mvarRang;
private T _mvarNumber;
/// <summary>
/// The default constructor (between 0 and 100/Number = 0)
/// </summary>
public NumberLimitRang(T mvarRang)
{
_mvarRang = new LimitRang<T>();
_mvarNumber = (T)Convert.ChangeType(0, typeof(T));
}
}
It's good practice to name fields with _ in the beginning.
But now, your argument mvarRang is unused. Revise your logic in code.
public NumberLimitRang(T mvarRang)
{
mvarRang = new Supplement.LimitRang<T>();
mvarNumber = (T)Convert.ChangeType(0, typeof(T));
}
The constructor takes a variable mvarRang of type T. This declaration hides the instance member mvarRang of the type LimitRang<T>.
Either change the parameter name, or refer to the instance member explicitly using this:
public NumberLimitRang(T mvarRang)
{
this.mvarRang = new Supplement.LimitRang<T>();
mvarNumber = (T)Convert.ChangeType(0, typeof(T));
}

Is there a way to make JavaScriptSerializer ignore properties of a certain generic type?

I am using the Entity Framework for my models, and i have need to serialize them to JSON. The problem is that EF includes all these really nice navigational collections (For instance my User model has an Orders property on it) and when I go to serialize these objects the serializer tries to get the value for those collections and EF yells at me for trying to use a disposed context
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
I know I can decorate my properties with [ScriptIgnore] to make the serializer leave them alone, but thats a problem with EF as it generates the code for those properties.
Is there a way to make the serializer not serialize properties that are of the generic type EntityCollection<>?
Alternatively is there a way to do this with another robust json library like JSON.Net?
You can declare a custom contract resolver which indicates which properties to ignore. Here's a general-purpose "ignorable", based on the answer I found here:
/// <summary>
/// Special JsonConvert resolver that allows you to ignore properties. See https://stackoverflow.com/a/13588192/1037948
/// </summary>
public class IgnorableSerializerContractResolver : DefaultContractResolver {
protected readonly Dictionary<Type, HashSet<string>> Ignores;
public IgnorableSerializerContractResolver() {
this.Ignores = new Dictionary<Type, HashSet<string>>();
}
/// <summary>
/// Explicitly ignore the given property(s) for the given type
/// </summary>
/// <param name="type"></param>
/// <param name="propertyName">one or more properties to ignore. Leave empty to ignore the type entirely.</param>
public void Ignore(Type type, params string[] propertyName) {
// start bucket if DNE
if (!this.Ignores.ContainsKey(type)) this.Ignores[type] = new HashSet<string>();
foreach (var prop in propertyName) {
this.Ignores[type].Add(prop);
}
}
/// <summary>
/// Is the given property for the given type ignored?
/// </summary>
/// <param name="type"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
public bool IsIgnored(Type type, string propertyName) {
if (!this.Ignores.ContainsKey(type)) return false;
// if no properties provided, ignore the type entirely
if (this.Ignores[type].Count == 0) return true;
return this.Ignores[type].Contains(propertyName);
}
/// <summary>
/// The decision logic goes here
/// </summary>
/// <param name="member"></param>
/// <param name="memberSerialization"></param>
/// <returns></returns>
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) {
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (this.IsIgnored(property.DeclaringType, property.PropertyName)) {
property.ShouldSerialize = instance => { return false; };
}
return property;
}
}
And usage:
var jsonResolver = new IgnorableSerializerContractResolver();
// ignore single property
jsonResolver.Ignore(typeof(Company), "WebSites");
// ignore single datatype
jsonResolver.Ignore(typeof(System.Data.Objects.DataClasses.EntityObject));
var jsonSettings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver };
If the idea is simply to return those objects to the client side why don't you just return what you need using anonymous classes?
Assuming you have this ugly heavy list of EntityFrameworkClass objects, you could do this:
var result = (from c in List<EntityFrameworkClass>
select new {
PropertyINeedOne=c.EntityFrameworkClassProperty1,
PropertyINeedTwo=c.EntityFrameworkClassProperty2
}).ToList();
This is my little contribution. Some changes to #drzaus answer.
Description: Some resharped changes and Fluent enabled. And a little fix to use PropertyType instead of DeclaringType.
public class IgnorableSerializerContractResolver : DefaultContractResolver
{
protected readonly Dictionary<Type, HashSet<string>> Ignores;
public IgnorableSerializerContractResolver()
{
Ignores = new Dictionary<Type, HashSet<string>>();
}
/// <summary>
/// Explicitly ignore the given property(s) for the given type
/// </summary>
/// <param name="type"></param>
/// <param name="propertyName">one or more properties to ignore. Leave empty to ignore the type entirely.</param>
public IgnorableSerializerContractResolver Ignore(Type type, params string[] propertyName)
{
// start bucket if DNE
if (!Ignores.ContainsKey(type))
Ignores[type] = new HashSet<string>();
foreach (var prop in propertyName)
{
Ignores[type].Add(prop);
}
return this;
}
/// <summary>
/// Is the given property for the given type ignored?
/// </summary>
/// <param name="type"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
public bool IsIgnored(Type type, string propertyName)
{
if (!Ignores.ContainsKey(type)) return false;
// if no properties provided, ignore the type entirely
return Ignores[type].Count == 0 || Ignores[type].Contains(propertyName);
}
/// <summary>
/// The decision logic goes here
/// </summary>
/// <param name="member"></param>
/// <param name="memberSerialization"></param>
/// <returns></returns>
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (IsIgnored(property.PropertyType, property.PropertyName))
{
property.ShouldSerialize = instance => false;
}
return property;
}
}
usage:
// Ignore by type, regardless property name
var jsonResolver = new IgnorableSerializerContractResolver().Ignore(typeof(PropertyName))
var jsonSettings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver };
Adding on to #drzaus's answer, I modified the IsIgnored method to make it more generic -
public bool IsIgnored(Type type, string propertyName)
{
var ignoredType = this.Ignores.Keys.FirstOrDefault(t => type.IsSubclassOf(t) || type == t || t.IsAssignableFrom(type));
//if (!this.Ignores.ContainsKey(type)) return false;
if (ignoredType == null) return false;
// if no properties provided, ignore the type entirely
if (this.Ignores[ignoredType].Count == 0) return true;
return this.Ignores[ignoredType].Contains(propertyName);
}
And its usage:
var jsonResolver = new IgnorableSerializerContractResolver();
jsonResolver.Ignore(typeof(BaseClassOrInterface), "MyProperty");
The above helped me make a generic serializer for converting Thrift objects to standard JSON. I wanted to ignore the __isset property while serializing objects of classes that implement the Thrift.Protocol.TBase interface.
Hope it helps.
PS - I know converting a Thrift object to standard JSON defeats its purpose, but this was a requirement for interfacing with a legacy system.
If you use JSON.NET you can use attributes like JsonIgnore to ignore certain properties. I use this feature when serializing objects loaded via NHibernate.
I think there is a possibility to add conventions, too. Maybe you can implement a filter for your EF properties.

Pass variable type to a method without enumerating

I want to be able to pass a variable type to a method, mainly so that I can pass an entity framework query to a method that will apply common includes of nested object.
This is what I want to do...
public Person GetPersonByID(int personID)
{
var query = from Perspn p in Context.Persons
where p.PersonID = personID
select p;
ObjectQuery<Person> personQuery = ApplyCommonIncludes<Person>(query);
return personQuery.FirstOrDefault();
}
public ObjectQuery<T> ApplyCommonIncludes<T>(SomeType query)
{
return ((ObjectQuery<T>)query)
.Include("Orders")
.Include("LoginHistory");
}
Seems to be you actually want SomeType to be ObjectQuery<T>, right?
public ObjectQuery<T> ApplyCommonIncludes<T>(ObjectQuery<T> query)
{
return query
.Include("Orders")
.Include("LoginHistory");
}
This is valid syntax. Is there any problem with this?
This ought to work and do delayed execution (I think this is what you mean by "without enumerating") until FirstOrDefault() is called.
I ended up creating a different approach. My repository now has a list of string used for Includes. To retain type safety for creating includes, I created the following class:
/// <summary>
/// Builds Includes
/// </summary>
public class IncludeBuilder
{
/// <summary>
/// List of parts for the Include
/// </summary>
private List<string> Parts;
/// <summary>
/// Creates a new IncludeBuilder
/// </summary>
private IncludeBuilder()
{
this.Parts = new List<string>();
}
/// <summary>
/// Creates a new IncludeBuilder
/// </summary>
public static IncludeBuilder Create()
{
return new IncludeBuilder();
}
/// <summary>
/// Adds a property name to the builder
/// </summary>
public IncludeBuilder AddPart<TEntity, TProp>(Expression<Func<TEntity, TProp>> expression)
{
string propName = ExpressionHelper.GetPropertyNameFromExpression(expression);
this.Parts.Add(propName);
return this;
}
/// <summary>
/// Gets a value of the include parts separated by
/// a decimal
/// </summary>
public override string ToString()
{
return string.Join(".", this.Parts.ToArray());
}
This allows me to do this...
myPersonRepository.AppendInclude(
IncludeBuilder.Create()
.AddPart((Person p) => p.Orders)
.AddPart((Order o) => o.Items));
The above statement passes expressions to the IncludeBuilder class which then translates the above into "Orders.Items".
I then created helper methods in my RepositoryBase that given an ObjectQuery, will apply the includes, execute the query, and return the result. Not quite what I was looking for, but works well.

How do I create dynamic properties in C#?

I am looking for a way to create a class with a set of static properties. At run time, I want to be able to add other dynamic properties to this object from the database. I'd also like to add sorting and filtering capabilities to these objects.
How do I do this in C#?
You might use a dictionary, say
Dictionary<string,object> properties;
I think in most cases where something similar is done, it's done like this.
In any case, you would not gain anything from creating a "real" property with set and get accessors, since it would be created only at run-time and you would not be using it in your code...
Here is an example, showing a possible implementation of filtering and sorting (no error checking):
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1 {
class ObjectWithProperties {
Dictionary<string, object> properties = new Dictionary<string,object>();
public object this[string name] {
get {
if (properties.ContainsKey(name)){
return properties[name];
}
return null;
}
set {
properties[name] = value;
}
}
}
class Comparer<T> : IComparer<ObjectWithProperties> where T : IComparable {
string m_attributeName;
public Comparer(string attributeName){
m_attributeName = attributeName;
}
public int Compare(ObjectWithProperties x, ObjectWithProperties y) {
return ((T)x[m_attributeName]).CompareTo((T)y[m_attributeName]);
}
}
class Program {
static void Main(string[] args) {
// create some objects and fill a list
var obj1 = new ObjectWithProperties();
obj1["test"] = 100;
var obj2 = new ObjectWithProperties();
obj2["test"] = 200;
var obj3 = new ObjectWithProperties();
obj3["test"] = 150;
var objects = new List<ObjectWithProperties>(new ObjectWithProperties[]{ obj1, obj2, obj3 });
// filtering:
Console.WriteLine("Filtering:");
var filtered = from obj in objects
where (int)obj["test"] >= 150
select obj;
foreach (var obj in filtered){
Console.WriteLine(obj["test"]);
}
// sorting:
Console.WriteLine("Sorting:");
Comparer<int> c = new Comparer<int>("test");
objects.Sort(c);
foreach (var obj in objects) {
Console.WriteLine(obj["test"]);
}
}
}
}
If you need this for data-binding purposes, you can do this with a custom descriptor model... by implementing ICustomTypeDescriptor, TypeDescriptionProvider and/or TypeCoverter, you can create your own PropertyDescriptor instances at runtime. This is what controls like DataGridView, PropertyGrid etc use to display properties.
To bind to lists, you'd need ITypedList and IList; for basic sorting: IBindingList; for filtering and advanced sorting: IBindingListView; for full "new row" support (DataGridView): ICancelAddNew (phew!).
It is a lot of work though. DataTable (although I hate it) is cheap way of doing the same thing. If you don't need data-binding, just use a hashtable ;-p
Here's a simple example - but you can do a lot more...
Use ExpandoObject like the ViewBag in MVC 3.
Create a Hashtable called "Properties" and add your properties to it.
I'm not sure you really want to do what you say you want to do, but it's not for me to reason why!
You cannot add properties to a class after it has been JITed.
The closest you could get would be to dynamically create a subtype with Reflection.Emit and copy the existing fields over, but you'd have to update all references to the the object yourself.
You also wouldn't be able to access those properties at compile time.
Something like:
public class Dynamic
{
public Dynamic Add<T>(string key, T value)
{
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("DynamicAssembly"), AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Dynamic.dll");
TypeBuilder typeBuilder = moduleBuilder.DefineType(Guid.NewGuid().ToString());
typeBuilder.SetParent(this.GetType());
PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(key, PropertyAttributes.None, typeof(T), Type.EmptyTypes);
MethodBuilder getMethodBuilder = typeBuilder.DefineMethod("get_" + key, MethodAttributes.Public, CallingConventions.HasThis, typeof(T), Type.EmptyTypes);
ILGenerator getter = getMethodBuilder.GetILGenerator();
getter.Emit(OpCodes.Ldarg_0);
getter.Emit(OpCodes.Ldstr, key);
getter.Emit(OpCodes.Callvirt, typeof(Dynamic).GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(typeof(T)));
getter.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getMethodBuilder);
Type type = typeBuilder.CreateType();
Dynamic child = (Dynamic)Activator.CreateInstance(type);
child.dictionary = this.dictionary;
dictionary.Add(key, value);
return child;
}
protected T Get<T>(string key)
{
return (T)dictionary[key];
}
private Dictionary<string, object> dictionary = new Dictionary<string,object>();
}
I don't have VS installed on this machine so let me know if there are any massive bugs (well... other than the massive performance problems, but I didn't write the specification!)
Now you can use it:
Dynamic d = new Dynamic();
d = d.Add("MyProperty", 42);
Console.WriteLine(d.GetType().GetProperty("MyProperty").GetValue(d, null));
You could also use it like a normal property in a language that supports late binding (for example, VB.NET)
I have done exactly this with an ICustomTypeDescriptor interface and a Dictionary.
Implementing ICustomTypeDescriptor for dynamic properties:
I have recently had a requirement to bind a grid view to a record object that could have any number of properties that can be added and removed at runtime. This was to allow a user to add a new column to a result set to enter an additional set of data.
This can be achieved by having each data 'row' as a dictionary with the key being the property name and the value being a string or a class that can store the value of the property for the specified row. Of course having a List of Dictionary objects will not be able to be bound to a grid. This is where the ICustomTypeDescriptor comes in.
By creating a wrapper class for the Dictionary and making it adhere to the ICustomTypeDescriptor interface the behaviour for returning properties for an object can be overridden.
Take a look at the implementation of the data 'row' class below:
/// <summary>
/// Class to manage test result row data functions
/// </summary>
public class TestResultRowWrapper : Dictionary<string, TestResultValue>, ICustomTypeDescriptor
{
//- METHODS -----------------------------------------------------------------------------------------------------------------
#region Methods
/// <summary>
/// Gets the Attributes for the object
/// </summary>
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return new AttributeCollection(null);
}
/// <summary>
/// Gets the Class name
/// </summary>
string ICustomTypeDescriptor.GetClassName()
{
return null;
}
/// <summary>
/// Gets the component Name
/// </summary>
string ICustomTypeDescriptor.GetComponentName()
{
return null;
}
/// <summary>
/// Gets the Type Converter
/// </summary>
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return null;
}
/// <summary>
/// Gets the Default Event
/// </summary>
/// <returns></returns>
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return null;
}
/// <summary>
/// Gets the Default Property
/// </summary>
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return null;
}
/// <summary>
/// Gets the Editor
/// </summary>
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return null;
}
/// <summary>
/// Gets the Events
/// </summary>
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return new EventDescriptorCollection(null);
}
/// <summary>
/// Gets the events
/// </summary>
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return new EventDescriptorCollection(null);
}
/// <summary>
/// Gets the properties
/// </summary>
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
List<propertydescriptor> properties = new List<propertydescriptor>();
//Add property descriptors for each entry in the dictionary
foreach (string key in this.Keys)
{
properties.Add(new TestResultPropertyDescriptor(key));
}
//Get properties also belonging to this class also
PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(this.GetType(), attributes);
foreach (PropertyDescriptor oPropertyDescriptor in pdc)
{
properties.Add(oPropertyDescriptor);
}
return new PropertyDescriptorCollection(properties.ToArray());
}
/// <summary>
/// gets the Properties
/// </summary>
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return ((ICustomTypeDescriptor)this).GetProperties(null);
}
/// <summary>
/// Gets the property owner
/// </summary>
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion Methods
//---------------------------------------------------------------------------------------------------------------------------
}
Note: In the GetProperties method I Could Cache the PropertyDescriptors once read for performance but as I'm adding and removing columns at runtime I always want them rebuilt
You will also notice in the GetProperties method that the Property Descriptors added for the dictionary entries are of type TestResultPropertyDescriptor. This is a custom Property Descriptor class that manages how properties are set and retrieved. Take a look at the implementation below:
/// <summary>
/// Property Descriptor for Test Result Row Wrapper
/// </summary>
public class TestResultPropertyDescriptor : PropertyDescriptor
{
//- PROPERTIES --------------------------------------------------------------------------------------------------------------
#region Properties
/// <summary>
/// Component Type
/// </summary>
public override Type ComponentType
{
get { return typeof(Dictionary<string, TestResultValue>); }
}
/// <summary>
/// Gets whether its read only
/// </summary>
public override bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets the Property Type
/// </summary>
public override Type PropertyType
{
get { return typeof(string); }
}
#endregion Properties
//- CONSTRUCTOR -------------------------------------------------------------------------------------------------------------
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public TestResultPropertyDescriptor(string key)
: base(key, null)
{
}
#endregion Constructor
//- METHODS -----------------------------------------------------------------------------------------------------------------
#region Methods
/// <summary>
/// Can Reset Value
/// </summary>
public override bool CanResetValue(object component)
{
return true;
}
/// <summary>
/// Gets the Value
/// </summary>
public override object GetValue(object component)
{
return ((Dictionary<string, TestResultValue>)component)[base.Name].Value;
}
/// <summary>
/// Resets the Value
/// </summary>
public override void ResetValue(object component)
{
((Dictionary<string, TestResultValue>)component)[base.Name].Value = string.Empty;
}
/// <summary>
/// Sets the value
/// </summary>
public override void SetValue(object component, object value)
{
((Dictionary<string, TestResultValue>)component)[base.Name].Value = value.ToString();
}
/// <summary>
/// Gets whether the value should be serialized
/// </summary>
public override bool ShouldSerializeValue(object component)
{
return false;
}
#endregion Methods
//---------------------------------------------------------------------------------------------------------------------------
}
The main properties to look at on this class are GetValue and SetValue. Here you can see the component being casted as a dictionary and the value of the key inside it being Set or retrieved. Its important that the dictionary in this class is the same type in the Row wrapper class otherwise the cast will fail. When the descriptor is created the key (property name) is passed in and is used to query the dictionary to get the correct value.
Taken from my blog at:
ICustomTypeDescriptor Implementation for dynamic properties
You should look into DependencyObjects as used by WPF these follow a similar pattern whereby properties can be assigned at runtime. As mentioned above this ultimately points towards using a hash table.
One other useful thing to have a look at is CSLA.Net. The code is freely available and uses some of the principles\patterns it appears you are after.
Also if you are looking at sorting and filtering I'm guessing you're going to be using some kind of grid. A useful interface to implement is ICustomTypeDescriptor, this lets you effectively override what happens when your object gets reflected on so you can point the reflector to your object's own internal hash table.
As a replacement for some of orsogufo's code, because I recently went with a dictionary for this same problem myself, here is my [] operator:
public string this[string key]
{
get { return properties.ContainsKey(key) ? properties[key] : null; }
set
{
if (properties.ContainsKey(key))
{
properties[key] = value;
}
else
{
properties.Add(key, value);
}
}
}
With this implementation, the setter will add new key-value pairs when you use []= if they do not already exist in the dictionary.
Also, for me properties is an IDictionary and in constructors I initialize it to new SortedDictionary<string, string>().
I'm not sure what your reasons are, and even if you could pull it off somehow with Reflection Emit (I' not sure that you can), it doesn't sound like a good idea. What is probably a better idea is to have some kind of Dictionary and you can wrap access to the dictionary through methods in your class. That way you can store the data from the database in this dictionary, and then retrieve them using those methods.
Why not use an indexer with the property name as a string value passed to the indexer?
Couldn't you just have your class expose a Dictionary object? Instead of "attaching more properties to the object", you could simply insert your data (with some identifier) into the dictionary at run time.
If it is for binding, then you can reference indexers from XAML
Text="{Binding [FullName]}"
Here it is referencing the class indexer with the key "FullName"

Is there a serializable generic Key/Value pair class in .NET?

I'm looking for a key/value pair object that I can include in a web service.
I tried using .NET's System.Collections.Generic.KeyValuePair<> class, but it does not properly serialize in a web service. In a web service, the Key and Value properties are not serialized, making this class useless, unless someone knows a way to fix this.
Is there any other generic class that can be used for this situation?
I'd use .NET's System.Web.UI.Pair class, but it uses Object for its types. It would be nice to use a Generic class, if only for type safety.
Just define a struct/class.
[Serializable]
public struct KeyValuePair<K,V>
{
public K Key {get;set;}
public V Value {get;set;}
}
I don't think there is as Dictionary<> itself isn't XML serializable, when I had need to send a dictionary object via a web service I ended up wrapping the Dictionary<> object myself and adding support for IXMLSerializable.
/// <summary>
/// Represents an XML serializable collection of keys and values.
/// </summary>
/// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the values in the dictionary.</typeparam>
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
#region Constants
/// <summary>
/// The default XML tag name for an item.
/// </summary>
private const string DEFAULT_ITEM_TAG = "Item";
/// <summary>
/// The default XML tag name for a key.
/// </summary>
private const string DEFAULT_KEY_TAG = "Key";
/// <summary>
/// The default XML tag name for a value.
/// </summary>
private const string DEFAULT_VALUE_TAG = "Value";
#endregion
#region Protected Properties
/// <summary>
/// Gets the XML tag name for an item.
/// </summary>
protected virtual string ItemTagName
{
get
{
return DEFAULT_ITEM_TAG;
}
}
/// <summary>
/// Gets the XML tag name for a key.
/// </summary>
protected virtual string KeyTagName
{
get
{
return DEFAULT_KEY_TAG;
}
}
/// <summary>
/// Gets the XML tag name for a value.
/// </summary>
protected virtual string ValueTagName
{
get
{
return DEFAULT_VALUE_TAG;
}
}
#endregion
#region Public Methods
/// <summary>
/// Gets the XML schema for the XML serialization.
/// </summary>
/// <returns>An XML schema for the serialized object.</returns>
public XmlSchema GetSchema()
{
return null;
}
/// <summary>
/// Deserializes the object from XML.
/// </summary>
/// <param name="reader">The XML representation of the object.</param>
public void ReadXml(XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
{
return;
}
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.ReadStartElement(ItemTagName);
reader.ReadStartElement(KeyTagName);
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement(ValueTagName);
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
/// <summary>
/// Serializes this instance to XML.
/// </summary>
/// <param name="writer">The writer to serialize to.</param>
public void WriteXml(XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement(ItemTagName);
writer.WriteStartElement(KeyTagName);
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement(ValueTagName);
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
#endregion
}
You will find the reason why KeyValuePairs cannot be serialised at this MSDN Blog Post
The Struct answer is the simplest solution, however not the only solution. A "better" solution is to write a Custom KeyValurPair class which is Serializable.
[Serializable]
public class SerializableKeyValuePair<TKey, TValue>
{
public SerializableKeyValuePair()
{
}
public SerializableKeyValuePair(TKey key, TValue value)
{
Key = key;
Value = value;
}
public TKey Key { get; set; }
public TValue Value { get; set; }
}
In the 4.0 Framework, there is also the addition of the Tuple family of classes that are serializable and equatable. You can use Tuple.Create(a, b) or new Tuple<T1, T2>(a, b).
A KeyedCollection is a type of dictionary that can be directly serialized to xml without any nonsense. The only issue is that you have to access values by: coll["key"].Value;
XmlSerializer doesn't work with Dictionaries. Oh, and it has problems with KeyValuePairs too
http://www.codeproject.com/Tips/314447/XmlSerializer-doesnt-work-with-Dictionaries-Oh-and
Use the DataContractSerializer since it can handle the Key Value Pair.
public static string GetXMLStringFromDataContract(object contractEntity)
{
using (System.IO.MemoryStream writer = new System.IO.MemoryStream())
{
var dataContractSerializer = new DataContractSerializer(contractEntity.GetType());
dataContractSerializer.WriteObject(writer, contractEntity);
writer.Position = 0;
var streamReader = new System.IO.StreamReader(writer);
return streamReader.ReadToEnd();
}
}
DataTable is my favorite collection for (solely) wrapping data to be serialized to JSON, since it's easy to expand without the need for an extra struct & acts like a serializable replacement for Tuple<>[]
Maybe not the cleanest way, but I prefer to include & use it directly in the classes (which shall be serialized), instead of declaring a new struct
class AnyClassToBeSerialized
{
public DataTable KeyValuePairs { get; }
public AnyClassToBeSerialized
{
KeyValuePairs = new DataTable();
KeyValuePairs.Columns.Add("Key", typeof(string));
KeyValuePairs.Columns.Add("Value", typeof(string));
}
public void AddEntry(string key, string value)
{
DataRow row = KeyValuePairs.NewRow();
row["Key"] = key; // "Key" & "Value" used only for example
row["Value"] = value;
KeyValuePairs.Rows.Add(row);
}
}
You can use Tuple<string,object>
see this for more details on Tuple usage : Working with Tuple in C# 4.0

Categories

Resources