Getting all keys and their values from ObjectStateEntry in Entity Framework - c#

For audit logging purpose I override SaveChanges() method in EF 4.1 Database-First approach .
I have all ObjectStateEntry object and I'm wondering if I could get all keys and their values from each ObjectStateEntry .
IEnumerable<ObjectStateEntry> changes = this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified);
foreach (ObjectStateEntry stateEntryEntity in changes)
{
if (!stateEntryEntity.IsRelationship &&
stateEntryEntity.Entity != null &&
!(stateEntryEntity.Entity is DBAudit))
{
list<object , object> KeyValues = GetAllKeyValues(stateEntryEntity );
//Do log all keyvalues
}
}

I haven't tested it but something like this should work:
private Dictionary<string, object> GetAllKeyValues(ObjectStateEntry entry)
{
var keyValues = new Dictionary<string, object>();
var currentValues = entry.CurrentValues;
for (int i = 0; i < currentValues.FieldCount; i++)
{
keyValues.Add(currentValues.GetName(i), currentValues.GetValue(i));
}
return keyValues;
}

Try using ObjectStateEntry.EntityKey and EntityKey.EntityKeyValues:
var keyValues = stateEntityEntry.EntityKey.EntityKeyValues;
which returns an array of EntityKeyMember. You can then use the Key and Value properties, which return a string and object respectively.

Here is my solution in the form of an extension method.
public static class ExtensionMethods
{
public static IReadOnlyDictionary<string, object> GetKeyValues(this ObjectStateEntry instance)
{
var keyMemberNames = instance
.EntitySet
.ElementType
.KeyMembers
.Select(x => x.Name)
.ToList();
var currentValues = instance.CurrentValues;
var result = new Dictionary<string, object>();
for (var i = 0; i < currentValues.FieldCount; i++)
{
var name = currentValues.GetName(i);
if (!keyMemberNames.Contains(name))
continue;
var value = currentValues.GetValue(i);
result.Add(name, value);
}
return result;
}
public static IReadOnlyDictionary<string, object> GetValues(this ObjectStateEntry instance)
{
var currentValues = instance.CurrentValues;
var result = new Dictionary<string, object>();
for (var i = 0; i < currentValues.FieldCount; i++)
{
var name = currentValues.GetName(i);
var value = currentValues.GetValue(i);
result.Add(name, value);
}
return result;
}
}

Related

Neater way to modify values in ModelBinder

Currently, I have a modelbinder like this. This does not work for nested classes, lists and dictionaries. Is there a way to bind model from form and then change values nicely.
public class AuditModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext modelBindingContext)
{
char[] delimeter = { '|' };
if (modelBindingContext == null)
{
throw new ArgumentNullException(nameof(modelBindingContext));
}
// var modelName = modelBindingContext.ModelName; // returns empty string
// ValueProviderResult valueResult = modelBindingContext.ValueProvider.GetValue(modelName); // doesn't work
var enumerable = (IEnumerable)modelBindingContext.ValueProvider;
var formValueProvider = enumerable.OfType<FormValueProvider>().Single();
var metadata = modelBindingContext.ModelMetadata;
var type = metadata.UnderlyingOrModelType;
var fields = typeof(FormValueProvider).GetField(
"_values",
BindingFlags.NonPublic | BindingFlags.Instance
);
var formCollection = fields.GetValue(formValueProvider).ToJson();
var listOfData = JsonConvert.DeserializeObject<List<KeyValuePair<string, object>>>(formCollection);
var dictionary = new Dictionary<string, object>();
foreach (var data in listOfData)
{
var key = data.Key;
var value = GetValue(modelBindingContext, data.Key, (string)((JToken)data.Value).FirstOrDefault());
dictionary[key] = value;
}
var model = JsonConvert.DeserializeObject(dictionary.ToJson(), type);
if (modelBindingContext.ModelType.GetInterfaces().Contains(typeof(IControl)))
{
var qc = model as IControl;
if (qc != null)
{
var request = modelBindingContext.HttpContext.Request;
string control = request.Form["control"];
if (!string.IsNullOrEmpty(control))
{
string[] components = control.Split(delimeter);
qc.Field1 = Convert.ToInt32(components[0]);
qc.Field2 = components[1];
qc.Fields.Add(components[2]);
}
}
}
modelBindingContext.Result = ModelBindingResult.Success(model);
return Task.CompletedTask;
}

Generic search implementation in EF Core

I'm trying to implement a generic search method which can be used with all entities of DB.
public static object HandleSearch(object objList, string searchText)
{
Dictionary<string, object> ht = null;
List<Dictionary<string, object>> returnList = new List<Dictionary<string, object>>();
var a = objList as ICollection;
object data = null;
Type tp = null;
foreach (object obj in a)
{
ht = (Dictionary<string, object>)obj;
foreach (string key in ht.Keys)
{
data = ht[key];
tp = data.GetType();
if (tp == typeof(DateTime))
{
if (((DateTime)data).ToString("dd/MM/yyyy HH:mm:ss").Contains(searchText))
{
returnList.Add(ht);
break;
}
else if (data.ToString().ToLower().Contains(searchText.ToLower()))
{
returnList.Add(ht);
break;
}
}
}
}
return returnList;
}
I should call this as
var x = _service.GetAll(eo);
var c = GeaUtility.HandleSearch(x, "29/02");
When I try it gives me "unable to cast from List to List<Dictionary<string, object>>.
How can I solve? Any ideas?

Logging entities change using SessionInterceptor in orchard

I wanted to log changes of certain entities (marked with attribute) so, I created AbstractSessionInterceptor's descendant to get access to entity changes. Also I want to know who did this changes, so I need to access current user, so through IWorkContextAccessor I'm creating IWorkContextScope, getting WorkContext and trying to get user, when existing entity is being edited I'm able to access current user, when new entity is created with contentmanager I'm getting timeout exception.. Then I getting WorkContext via IWorkContextAccessor.GetContext() I'm get infinite loop (interceptor is being called again and again). Any Ideas and suggestion would be appreciated.
Thanks.
Source:
public class AccountInterceptor : AbstractSessionInterceptor
{
private IProtocolLogger _logger;
private readonly Type _mainAttrType = typeof(ProtocolAttribute);
private readonly Type _fieldAttrType = typeof(ProtocolFieldAttribute);
private readonly IWorkContextAccessor _contextAccessor;
ISessionFactoryHolder _sessionFactoryHolder;
public AccountInterceptor(IWorkContextAccessor contextAccessor, ISessionFactoryHolder sessionFactoryHolder)
{
_contextAccessor = contextAccessor;
_sessionFactoryHolder = sessionFactoryHolder;
}
public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, NHibernate.Type.IType[] types)
{
var t = entity.GetType();
var attributes = t.GetCustomAttributes(_mainAttrType, true);
if (attributes.Length != 0)
{
IWorkContextScope scope = _contextAccessor.CreateWorkContextScope();
WorkContext context = scope.WorkContext;
if (context != null)
{
var attr = (ProtocolAttribute)attributes.FirstOrDefault();
var currentDic = currentState.Select((s, i) => new { S = s, Index = i }).ToDictionary(x => x.Index, x => x.S);
var prvDic = previousState.Select((s, i) => new { S = s, Index = i }).ToDictionary(x => x.Index, x => x.S);
var diff = compare(currentDic, prvDic);
if (!attr.LogAllData)
{
List<string> properties = new List<string>();
foreach (var propety in t.GetProperties())
{
var propertyAttributes = propety.GetCustomAttributes(_fieldAttrType, true);
if (propertyAttributes.Length != 0)
properties.Add(propety.Name);
}
if (properties.Count != 0)
{
var necesseryProps = propertyNames.Select((s, i) => new { S = s, Index = i }).Where(p => properties.Contains(p.S)).ToDictionary(x => x.Index, x => x.S);
TupleList<int, object, object> ToRemove = new TupleList<int, object, object>();
foreach (var tuple in diff)
{
if (!necesseryProps.Keys.Contains(tuple.Item1))
{
ToRemove.Add(tuple);
}
}
ToRemove.ForEach(d => diff.Remove(d));
}
}
if (diff.Count != 0)
{
_logger = ProtocolLogger.GetInstance();
var sessionFactory = _sessionFactoryHolder.GetSessionFactory();
var session = sessionFactory.OpenSession();
var user = GetCurrentUser(session, context.HttpContext);
string propertiesFormat = GetPropertiesStringFormat(diff, propertyNames);
object[] param = new object[] { DateTime.Now, entity, propertyNames };
string entityId = string.Empty;
try
{
if (entity is IAuditable)
{
entityId = ((IAuditable)entity).Id.ToString();
}
}
catch (Exception)
{
entityId = entity.ToString();
}
foreach (var pair in diff)
{
ProtocolPropertyInfo info = new ProtocolPropertyInfo(propertyNames[pair.Item1], Convert.ToString(pair.Item2), Convert.ToString(pair.Item3));
_logger.Log(user, entity, entityId, session, context, Operation.Write, info);
}
session.Flush();
session.Close();
}
}
}
return base.OnFlushDirty(entity, id, currentState, previousState, propertyNames, types);
}
private object GetCurrentUser(ISession session, HttpContextBase httpContext)
{
if (httpContext == null || !httpContext.Request.IsAuthenticated || !(httpContext.User.Identity is FormsIdentity))
{
return null;
}
var formsIdentity = (FormsIdentity)httpContext.User.Identity;
var userData = formsIdentity.Ticket.UserData ?? "";
// the cookie user data is {userId};{tenant}
var userDataSegments = userData.Split(';');
if (userDataSegments.Length != 2)
{
return null;
}
var userDataId = userDataSegments[0];
var userDataTenant = userDataSegments[1];
int userId;
if (!int.TryParse(userDataId, out userId))
{
return null;
}
Type regType = Assembly.Load("Orchard.Users").GetTypes().First(t => t.Name == "UserPartRecord");
var user = session.Get(regType, userId);
return user;
}
private string GetPropertiesStringFormat(TupleList<int, object, object> diffDic, string[] propertyNames)
{
StringBuilder result = new StringBuilder();
foreach (var pair in diffDic)
{
result.AppendFormat("Property name {0}, New value {1}, Old value {2}", propertyNames[pair.Item1], pair.Item2, pair.Item3);
}
return result.ToString();
}
private TupleList<int, object, object> compare(Dictionary<int, object> dic1, Dictionary<int, object> dic2)
{
var diff = new TupleList<int, object, object>();
foreach (KeyValuePair<int, object> pair in dic1)
{
if (!Equals(pair.Value, dic2[pair.Key]))
{
diff.Add(pair.Key, pair.Value, dic2[pair.Key]);
}
}
return diff;
}
}
Never ever start new work context inside your interceptor - infinite loop is guaranteed. And in fact, you don't have to. Each interceptor is already instantiated per work context, so you can inject dependencies via ctor, as usual.
To access current user you can either:
inject IOrchardServices and use .WorkContext.CurrentUser property, or
or use contextAccessor.GetContext() to get context and then call CurrentUser on it.
Also, be careful with performing database operations from inside the interceptor as those will most likely result in infinite loops and throw stack overflow exceptions.

How to get property name and value from generic model with generic list?

Using the following model as an example.
public class FooModel
{
public FooModel()
{
Bars= new List<BarModel>();
}
[ManyToMany]
public IList<BarModel> Bars{ get; set; }
}
public class BarModel
{
public int Id { get; set; }
}
I need to extrapolate the List<BarModel> from a fooModel object, and build up a Dictionary<string, object> from each BarModel in the list.
Let's say I create the following object.
var fooModel = new FooModel();
var bar1 = new BarModel {Id = 1};
var bar2 = new BarModel {Id = 2};
fooModel.Bars = new List<BarModel>{bar1,bar2};
And now I want to get all properties within Foo that have the [ManyToMany] attribute.
// First I call the method and pass in the model
DoSomething(fooModel);
// Next I extract some values (used elsewhere)
public DoSomething<TModel>(IModel model){
var dbProvider = ...;
var mapper = new AutoMapper<TModel>();
var tableName = GetTableName( typeof( TModel ) );
UpdateJoins( dbProvider, fooModel, tableName, mapper );
}
// Finally I begin dealing with the collection.
private static void UpdateJoins<TModel> ( IDbProvider dbProvider, TModel model, string tableName, IAutoMapper<TModel> mapper ) where TModel : class, new()
{
foreach (
var collection in
model.GetType()
.GetProperties()
.Where( property => property.GetCustomAttributes( typeof( ManyToManyAttribute ), true ).Any() ) )
{
if ( !IsGenericList( collection.PropertyType ) )
throw new Exception( "The property must be a List" );
// Stuck Here - pseudo code
//====================
foreach (loop the collection)
var collectionName = ...; // Bar
var nestedPropertyName = ...; // Id
var rightKey = collectionName + nestedPropertyName; // BarId
var nestedPropertyValue = ...; // 1
}
}
In the example above, the OUTER foreach is only going to run ONCE because there is only one Property within FooModel that is decorated with the [ManyToMany] attribute.
Therefore PropertyInfo property is a List<BarModel>
How do I do the above INNER foreach and extract the required data?
This may get you on the right track. The idea is if you encounter a [ManyToMany] / generic list you reflect it using recursive call to the same method and then flatten the returned values to form a unique key. You probably will need to tweak it to suit your problem. The below code returns a dictionary with formatted key strings built from collection names, indexes and property names. E.G:
Bars[0].Id = 1
Bars[1].Id = 2
Code:
//This is just a generic wrapper for the other Reflect method
private static Dictionary<string, string> Reflect<TModel>(TModel Model)
{
return Reflect(Model.GetType(), Model);
}
private static Dictionary<string, string> Reflect(Type Type, object Object)
{
var result = new Dictionary<string, string>();
var properties = Type.GetProperties();
foreach (var property in properties)
{
if (
property.GetCustomAttributes(typeof(ManyToManyAttribute), true).Any() &&
property.PropertyType.GetGenericTypeDefinition() == typeof(IList<>))
{
var genericType = property.PropertyType.GetGenericArguments().FirstOrDefault();
var listValue = (IEnumerable)property.GetValue(Object, null);
int i = 0;
foreach (var value in listValue)
{
var childResult = Reflect(genericType, value);
foreach (var kvp in childResult)
{
var collectionName = property.Name;
var index = i;
var childPropertyName = kvp.Key;
var childPropertyValue = kvp.Value;
var flattened = string.Format("{0}[{1}].{2}", collectionName, i, childPropertyName);
result.Add(flattened, childPropertyValue);
}
i++;
}
}
else
{
result.Add(property.Name, property.GetValue(Object, null).ToString());
}
}
return result;
}

How to convert object to Dictionary<TKey, TValue> in C#?

How do I convert a dynamic object to a Dictionary<TKey, TValue> in C# What can I do?
public static void MyMethod(object obj)
{
if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
{
// My object is a dictionary, casting the object:
// (Dictionary<string, string>) obj;
// causes error ...
}
else
{
// My object is not a dictionary
}
}
The above answers are all cool. I found it easy to json serialize the object and deserialize as a dictionary.
var json = JsonConvert.SerializeObject(obj);
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
I don't know how performance is effected but this is much easier to read. You could also wrap it inside a function.
public static Dictionary<string, TValue> ToDictionary<TValue>(object obj)
{
var json = JsonConvert.SerializeObject(obj);
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, TValue>>(json);
return dictionary;
}
Use like so:
var obj = new { foo = 12345, boo = true };
var dictionary = ToDictionary<string>(obj);
I use this helper:
public static class ObjectToDictionaryHelper
{
public static IDictionary<string, object> ToDictionary(this object source)
{
return source.ToDictionary<object>();
}
public static IDictionary<string, T> ToDictionary<T>(this object source)
{
if (source == null)
ThrowExceptionWhenSourceArgumentIsNull();
var dictionary = new Dictionary<string, T>();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
AddPropertyToDictionary<T>(property, source, dictionary);
return dictionary;
}
private static void AddPropertyToDictionary<T>(PropertyDescriptor property, object source, Dictionary<string, T> dictionary)
{
object value = property.GetValue(source);
if (IsOfType<T>(value))
dictionary.Add(property.Name, (T)value);
}
private static bool IsOfType<T>(object value)
{
return value is T;
}
private static void ThrowExceptionWhenSourceArgumentIsNull()
{
throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
}
}
the usage is just to call .ToDictionary() on an object
Hope it helps.
public static KeyValuePair<object, object > Cast<K, V>(this KeyValuePair<K, V> kvp)
{
return new KeyValuePair<object, object>(kvp.Key, kvp.Value);
}
public static KeyValuePair<T, V> CastFrom<T, V>(Object obj)
{
return (KeyValuePair<T, V>) obj;
}
public static KeyValuePair<object , object > CastFrom(Object obj)
{
var type = obj.GetType();
if (type.IsGenericType)
{
if (type == typeof (KeyValuePair<,>))
{
var key = type.GetProperty("Key");
var value = type.GetProperty("Value");
var keyObj = key.GetValue(obj, null);
var valueObj = value.GetValue(obj, null);
return new KeyValuePair<object, object>(keyObj, valueObj);
}
}
throw new ArgumentException(" ### -> public static KeyValuePair<object , object > CastFrom(Object obj) : Error : obj argument must be KeyValuePair<,>");
}
From the OP:
Instead of converting my whole Dictionary, i decided to keep my obj
dynamic the whole time. When i access the keys and values of my
Dictionary with a foreach later, i use foreach(dynamic key in
obj.Keys) and convert the keys and values to strings simply.
Another option is to use NewtonSoft.JSON.
var dictionary = JObject.FromObject(anObject).ToObject<Dictionary<string, object>>();
If you don't mind LINQ Expressions;
public static Dictionary<string, object> ConvertFromObjectToDictionary(object arg)
{
return arg.GetType().GetProperties().ToDictionary(property => property.Name, property => property.GetValue(arg));
}
this should work:
for numbers, strings, date, etc.:
public static void MyMethod(object obj)
{
if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
{
IDictionary idict = (IDictionary)obj;
Dictionary<string, string> newDict = new Dictionary<string, string>();
foreach (object key in idict.Keys)
{
newDict.Add(key.ToString(), idict[key].ToString());
}
}
else
{
// My object is not a dictionary
}
}
if your dictionary also contains some other objects:
public static void MyMethod(object obj)
{
if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
{
IDictionary idict = (IDictionary)obj;
Dictionary<string, string> newDict = new Dictionary<string, string>();
foreach (object key in idict.Keys)
{
newDict.Add(objToString(key), objToString(idict[key]));
}
}
else
{
// My object is not a dictionary
}
}
private static string objToString(object obj)
{
string str = "";
if (obj.GetType().FullName == "System.String")
{
str = (string)obj;
}
else if (obj.GetType().FullName == "test.Testclass")
{
TestClass c = (TestClass)obj;
str = c.Info;
}
return str;
}
public static void MyMethod(object obj){
Dictionary<string, string> dicEditdata = data as Dictionary<string, string>;
string abc=dicEditdata["id"].ToString();}
suppose---
if you place the cursor over the object(obj) while debugging and
if you get an object with the value {['id':'ID1003']}
then you can use the value as
string abc=dicEditdata["id"].ToString();
Assuming key can only be a string but value can be anything try this
public static Dictionary<TKey, TValue> MyMethod<TKey, TValue>(object obj)
{
if (obj is Dictionary<TKey, TValue> stringDictionary)
{
return stringDictionary;
}
if (obj is IDictionary baseDictionary)
{
var dictionary = new Dictionary<TKey, TValue>();
foreach (DictionaryEntry keyValue in baseDictionary)
{
if (!(keyValue.Value is TValue))
{
// value is not TKey. perhaps throw an exception
return null;
}
if (!(keyValue.Key is TKey))
{
// value is not TValue. perhaps throw an exception
return null;
}
dictionary.Add((TKey)keyValue.Key, (TValue)keyValue.Value);
}
return dictionary;
}
// object is not a dictionary. perhaps throw an exception
return null;
}
I've done something like this and works for me.
using System.ComponentModel;
var dictionary = new Dictionary<string, string>();
foreach (var propDesc in TypeDescriptor.GetProperties(Obj))
{
if (!string.IsNullOrEmpty(propDesc.GetValue(Obj)))
{
dictionary.Add(propDesc.Name, propDesc.GetValue(Obj));
}
}
Also, another alternative and innovative solution is here.
var dictionary = new System.Web.Routing.RouteValueDictionary(Obj);
I hope this could work :)
// obj = new { a = "string", b = 0, c = true };
static Dictionary<string, object> ToDictionary(object obj)
{
int i = 0;
var props = obj.GetType().GetProperties();
return props.ToDictionary(k => props[i].Name, v => props[i++].GetValue(obj));
}
This code securely works to convert Object to Dictionary (having as premise that the source object comes from a Dictionary):
private static Dictionary<TKey, TValue> ObjectToDictionary<TKey, TValue>(object source)
{
Dictionary<TKey, TValue> result = new Dictionary<TKey, TValue>();
TKey[] keys = { };
TValue[] values = { };
bool outLoopingKeys = false, outLoopingValues = false;
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
{
object value = property.GetValue(source);
if (value is Dictionary<TKey, TValue>.KeyCollection)
{
keys = ((Dictionary<TKey, TValue>.KeyCollection)value).ToArray();
outLoopingKeys = true;
}
if (value is Dictionary<TKey, TValue>.ValueCollection)
{
values = ((Dictionary<TKey, TValue>.ValueCollection)value).ToArray();
outLoopingValues = true;
}
if(outLoopingKeys & outLoopingValues)
{
break;
}
}
for (int i = 0; i < keys.Length; i++)
{
result.Add(keys[i], values[i]);
}
return result;
}
This way for object array to Dictionary<string, object> List coverting
object[] a = new object[2];
var x = a.Select(f => (Dictionary<string, object>)f).ToList();
This way for single object to Dictionary<string, object> coverting
object a = new object;
var x = (Dictionary<string, object>)a;
You can create a generic extension method and then use it on the object like:
public static class Extensions
{
public static KeyValuePair<TKey, TValue> ToKeyValuePair<TKey, TValue>(this Object obj)
{
// if obj is null throws exception
Contract.Requires(obj != null);
// gets the type of the obj parameter
var type = obj.GetType();
// checks if obj is of type KeyValuePair
if (type.IsGenericType && type == typeof(KeyValuePair<TKey, TValue>))
{
return new KeyValuePair<TKey, TValue>(
(TKey)type.GetProperty("Key").GetValue(obj, null),
(TValue)type.GetProperty("Value").GetValue(obj, null)
);
}
// if obj type does not match KeyValuePair throw exception
throw new ArgumentException($"obj argument must be of type KeyValuePair<{typeof(TKey).FullName},{typeof(TValue).FullName}>");
}
and usage would be like:
KeyValuePair<string,long> kvp = obj.ToKeyValuePair<string,long>();
I use this simple method:
public Dictionary<string, string> objToDict(XYZ.ObjectCollection objs) {
var dict = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> each in objs){
dict.Add(each.Key, each.Value);
}
return dict;
}
You can use this:
Dictionary<object,object> mydic = ((IEnumerable)obj).Cast<object>().ToList().ToDictionary(px => px.GetType().GetProperty("Key").GetValue(px), pv => pv.GetType().GetProperty("Value").GetValue(pv));
string BaseUrl = "http://www.example.com";
HttpClient client = new HttpClient { BaseAddress = new Uri(BaseUrl) };
PropertyInfo[] properties = object.GetType().GetProperties();
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (PropertyInfo property in properties)
{
dictionary.Add(property.Name, property.GetValue(model, null).ToString());
}
foreach (string key in dictionary.Keys)
{
client.DefaultRequestHeaders.Add(key, dictionary[key]);
}
As I understand it, you're not sure what the keys and values are, but you want to convert them into strings?
Maybe this can work:
public static void MyMethod(object obj)
{
var iDict = obj as IDictionary;
if (iDict != null)
{
var dictStrStr = iDict.Cast<DictionaryEntry>()
.ToDictionary(de => de.Key.ToString(), de => de.Value.ToString());
// use your dictStrStr
}
else
{
// My object is not an IDictionary
}
}
object parsedData = se.Deserialize(reader);
System.Collections.IEnumerable stksEnum = parsedData as System.Collections.IEnumerable;
then will be able to enumerate it!
Simple way:
public IDictionary<T, V> toDictionary<T, V>(Object objAttached)
{
var dicCurrent = new Dictionary<T, V>();
foreach (DictionaryEntry dicData in (objAttached as IDictionary))
{
dicCurrent.Add((T)dicData.Key, (V)dicData.Value);
}
return dicCurrent;
}

Categories

Resources