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

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

Related

OrderedDictionary is not being saved when saving Settings

In my application I've implemented a few Controls to browse data in different ways. In every Control I display a TreeView to allow the user to go from a folder to another.
I would like my Controls to "remember" the last selected tree, in a generic way (I mean that if, in the future I add another Control I don't want to do a lot of adaptations). So I added an OrderedDictionary in the Settings. I use the Control's Type Name as a key and the Node's path as value.
As I was unable to set a default value for this dictionary I used this trick:
Settings.cs :
public OrderedDictionary Paths
{
get
{
return LastsPaths ?? (LastsPaths = new OrderedDictionary());
}
set
{
this["LastsPaths"] = value;
}
}
Settings.Designer.cs:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.Collections.Specialized.OrderedDictionary LastsPaths {
get {
return ((global::System.Collections.Specialized.OrderedDictionary)(this["LastsPaths"]));
}
set {
this["LastsPaths"] = value;
}
}
I do call Save each time I add/update a value, the user.config file timestamps change, but the content stays the same:
<setting name="LastsPaths" serializeAs="Xml">
<value />
</setting>
It doesn't work with:
App in debug mode;
App in release mode;
App installed.
How can I fix this?
It seems OrderedDictionary (and generic dictionaries in general) are not XML serializable.
You can wrap it in another class that does the serialization manually. In that way you don't expose the dictionary directly to the XML serializer. You have to implement IXmlSerializable to achieve this.
This might be enough to get you started. This inherits IXMLSerializable which is needed during the Save call.
[XmlRoot("PreviouslyVisitedPaths")]
public class PreviouslySelectedPaths : OrderedDictionary, IXmlSerializable
{
#region Implementation of IXmlSerializable
/// <summary>
/// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class.
/// </summary>
/// <returns>
/// An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.
/// </returns>
public XmlSchema GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized. </param>
public void ReadXml(XmlReader reader)
{
var keySerializer = new XmlSerializer(typeof(object));
var valueSerializer = new XmlSerializer(typeof(object));
var wasEmpty = reader.IsEmptyElement;
reader.Read();
if(wasEmpty)
{
return;
}
while(reader.NodeType != XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
var key = keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
var value = valueSerializer.Deserialize(reader);
reader.ReadEndElement();
Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized. </param>
public void WriteXml(XmlWriter writer)
{
var keySerializer = new XmlSerializer(typeof(object));
var valueSerializer = new XmlSerializer(typeof(object));
foreach(var key in Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
var value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
#endregion
}
}
You would then change your code to this:
public PreviouslySelectedPaths Paths
{
get
{
return LastsPaths ?? (LastsPaths = new PreviouslySelectedPaths());
}
set
{
this["LastsPaths"] = value;
}
}
You would also need to make LastsPaths type PreviouslySelectedPaths.
This is just to get your started you may need to tweek the IXMLSerializable methods and fill in logic for GetSchema().

How to apply indenting serialization only to some properties?

I want to serialize .NET objects to JSON in a human-readable way, but I would like to have more control about whether an object's properties or array's elements end up on a line of their own.
Currently I'm using JSON.NET's JsonConvert.SerializeObject(object, Formatting, JsonSerializerSettings) method for serialization, but it seems I can only apply the Formatting.Indented (all elements on individual lines) or Formatting.None (everything on a single line without any whitespace) formatting rules globally for the entire object. Is there a way to globally use indenting by default, but turn it off for certain classes or properties, e.g. using attributes or other parameters?
To help you understand the problem, here are some output examples. Using Formatting.None:
{"array":["element 1","element 2","element 3"],"object":{"property1":"value1","property2":"value2"}}
Using Formatting.Indented:
{
"array": [
"element 1",
"element 2",
"element 3"
],
"object": {
"property1": "value1",
"property2":"value2"
}
}
What I would like to see:
{
"array": ["element 1","element 2","element 3"],
"object": {"property1":"value1","property2":"value2"}
}
(I realize my question may be slightly related to this one, but the comments there totally miss the point and don't actually provide a valid answer.)
One possibility would be to write a custom Json converter for the specific types you need special handling and switch the formatting for them:
class Program
{
static void Main()
{
var root = new Root
{
Array = new[] { "element 1", "element 2", "element 3" },
Object = new Obj
{
Property1 = "value1",
Property2 = "value2",
},
};
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
};
settings.Converters.Add(new MyConverter());
string json = JsonConvert.SerializeObject(root, settings);
Console.WriteLine(json);
}
}
public class Root
{
public string[] Array { get; set; }
public Obj Object { get; set; }
}
public class Obj
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
class MyConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string[]) || objectType == typeof(Obj);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue(JsonConvert.SerializeObject(value, Formatting.None));
}
}
This will output:
{
"Array": ["element 1","element 2","element 3"],
"Object": {"Property1":"value1","Property2":"value2"}
}
I also used a converter for this (as per Darin Dimitrov's answer), but instead of calling WriteRawValue() I use the serializer for each element; which ensures any custom converters that apply to the element type will be used.
Note however that this converter is only operating on Arrays of a handful of primitive types, it's not using the Newtonsoft.Json logic for determining what should be serialized as an array and what a primitive type is, basically because that code is internal and I wanted to avoid maintaining a copy of it.
Overall I get the feeling that converters aren't intended to be used for formatting tasks such as this, but I think they're the only option in the current API. Ideally the API would offer a few more formatting options or perhaps better support for custom formatting within the converter API.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace JsonProto
{
/// <summary>
/// A JsonConverter that modifies formatting of arrays, such that the array elements are serialised to a single line instead of one element per line
/// preceded by indentation whitespace.
/// This converter handles writing JSON only; CanRead returns false.
/// </summary>
/// <remarks>
/// This converter/formatter applies to arrays only and not other collection types. Ideally we would use the existing logic within Newtonsoft.Json for
/// identifying collections of items, as this handles a number of special cases (e.g. string implements IEnumerable over the string characters). In order
/// to avoid duplicating in lots of logic, instead this converter handles only Arrays of a handful of selected primitive types.
/// </remarks>
public class ArrayNoFormattingConverter : JsonConverter
{
# region Static Fields
static HashSet<Type> _primitiveTypeSet =
new HashSet<Type>
{
typeof(char),
typeof(char?),
typeof(bool),
typeof(bool?),
typeof(sbyte),
typeof(sbyte?),
typeof(short),
typeof(short?),
typeof(ushort),
typeof(ushort?),
typeof(int),
typeof(int?),
typeof(byte),
typeof(byte?),
typeof(uint),
typeof(uint?),
typeof(long),
typeof(long?),
typeof(ulong),
typeof(ulong?),
typeof(float),
typeof(float?),
typeof(double),
typeof(double?),
typeof(decimal),
typeof(decimal?),
typeof(string),
typeof(DateTime),
typeof(DateTime?),
};
#endregion
#region Properties
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
// Note. Ideally this would match the test for JsonContractType.Array in DefaultContractResolver.CreateContract(),
// but that code is all internal to Newtonsoft.Json.
// Here we elect to take over conversion for Arrays only.
if(!objectType.IsArray) {
return false;
}
// Fast/efficient way of testing for multiple possible primitive types.
Type elemType = objectType.GetElementType();
return _primitiveTypeSet.Contains(elemType);
}
/// <summary>
/// Gets a value indicating whether this <see cref="JsonConverter"/> can read JSON.
/// </summary>
/// <value>Always returns <c>false</c>.</value>
public override bool CanRead
{
get { return false; }
}
#endregion
#region Public Methods
/// <summary>
/// Reads the JSON representation of the object. (Not implemented on this converter).
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Formatting formatting = writer.Formatting;
writer.WriteStartArray();
try
{
writer.Formatting = Formatting.None;
foreach(object childValue in ((System.Collections.IEnumerable)value)) {
serializer.Serialize(writer, childValue);
}
}
finally
{
writer.WriteEndArray();
writer.Formatting = formatting;
}
}
#endregion
}
}

Specifying dynamic properties for an object in 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"]

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.

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"

Categories

Resources