How do I reference a field in an ExpandoObject dynamically? - c#

Is there a way to dynamically access the property of an expando using a "IDictionary" style lookup?
var messageLocation = "Message";
dynamic expando = new ExpandoObject();
expando.Message = "I am awesome!";
Console.WriteLine(expando[messageLocation]);

You have to cast the ExpandoObject to IDictionary<string, object> :
var messageLocation = "Message";
dynamic expando = new ExpandoObject();
expando.Message = "I am awesome!";
var expandoDict = (IDictionary<string, object>)expando;
Console.WriteLine(expandoDict[messageLocation]);
(Also your expando variable must be typed as dynamic so property access is determined at runtime - otherwise your sample won't compile)

Related

field 'params' with an expando object in C#

I have the following in C#:
dynamic JsonObject = new ExpandoObject();
JsonObject.action = Action;
JsonObject.arguments = JsonArguments;
JsonObject.id = Id;
JsonObject.sig = Signature;
var Json = JsonConvert.SerializeObject(JsonObject);
and I need to change:
JsonObject.arguments = JsonArguments;
into:
JsonObject.params = JsonArguments;
but I can't use params as a field name with an expando object.
What would be a good workaround to build that json?
It's to use with deribit.com. They've released API V2 and changed some of the names, but I guess didn't think about that case.
You could convert the expando into a dictionary or use a dictionary directly, for sample:
var jsonObject = new ExpandoObject() as IDictionary<string, Object>;
jsonObject.Add("action", Action);
jsonObject.Add("params", JsonArguments);
jsonObject.Add("id", Id);
jsonObject.Add("sig", Signature);
var json = JsonConvert.SerializeObject(JsonObject);

Dynamic Expression not working on dynamic objects

I want to dynamically apply a predicates to a list of dynamic object. My solution is working well when I use actual objects but it does not work on dynamic objects and I can't figure out what is the problem.
Note: I searched Stackoverflow none of similar questions are using list of dynamic objects.
I have a list of dynamic objects like the following code. The list contains two dynamic object that have two properties (Name,CreateDate). I used JsonConvert class to create dynamic objects :
var lst = new List<dynamic>();
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("Name", "John");
dict.Add("CreateDate", DateTime.Now);
lst.Add(JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(dict)));
dict.Clear();
dict.Add("Name", "sara");
dict.Add("CreateDate", DateTime.Now);
lst.Add(JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(dict)));
dict.Clear();
As you see lst is a list of dynamic objects and have 2 items in it.
Now I want to filter list to get the item with the name Jonh (p=> p.Name == "john")
To do this I had the following approach:
ParameterExpression pe = Expression.Parameter(typeof(object), "p");
CallSiteBinder name = Binder.GetMember(CSharpBinderFlags.None, "Name", typeof(object),
new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
var pname = Expression.Dynamic(name, typeof(object), pe);
var right = Expression.Constant("John");
Expression e2 = Expression.Equal(pname, right);
var qu = Expression.Lambda<Func<dynamic, bool>>(e2, pe);
var lst2 = lst.AsQueryable().Where(qu).ToList();// Count()==0 !
The lst2 should contain 1 item but it contains 0 items. But if I change the original list(lst) to a type that has a Name property (let's say List<Person>) it lst2 correctly have 1 item.
UPDATE:
Even when I use ExpandoObject to create dynamic objects it still won't work :
dynamic obj = new ExpandoObject();
var dictionary = (IDictionary<string, object>)obj;
dictionary.Add("Name", "John");
dictionary.Add("CreateDate", DateTime.Now);
UPDATE 2:
As pionted out in the comments ExpandoObject actually works and the problem is with SqlDataReader. Here are what I have tried (see Not working comments in the following code) :
...
List<dynamic> result = new List<dynamic>();
While(dr.Read()){
dynamic obj = new ExpandoObject();
var dictionary = (IDictionary<string, object>)obj;
dictionary.Add("Name","John"); // <= this works fine
// dictionary.Add("Name",dr["Name"]); // <= Not working
// dictionary.Add("Name",dr["Name"].ToItsType()); // <= Not working
// dictionary.Add("Name",dr["Name"].ToString()); // <= Not working
dictionary.Add("CreateDate", DateTime.Now);
result.Add(obj);
}
...
I was able to reproduce the issue (after your UPDATE 2 which gave me the idea) by changing the ExpandoObject example code
dictionary.Add("Name", "John");
to
dictionary.Add("Name", new string("John".ToCharArray()));
to avoid constant string interning, which lead us to the issue in the dynamic expression code.
The dynamic expression type is object, hence Expression.Equal resolves to object operator ==, i.e. ReferenceEquals. That's why the example is working with constant strings and not with runtime created strings.
What you need here is to use actual property type. So simply cast (Expression.Convert) the result of the dynamic property accessor to the expected type:
var pname = Expression.Convert(Expression.Dynamic(name, typeof(object), pe), typeof(string));
Now the expressions which refer to pname expression will resolve with the correct type (in this particular case, Equal will resolve to the overloaded string == operator which correctly compares strings by value. Same for value types like int, DateTime etc.).
dynamic obj = new ExpandoObject();
dictionary.Add("Name", "John");
dictionary.Add("CreateDate", DateTime.Now);
try the above code. Conversion is not required and ExpandoObject should allow to add or remove dynamic objects.
Why not just use dynamic objects instead of dictionary.
Following code works like charm:
var lst = new List<dynamic>();
dynamic obj = new ExpandoObject();
obj.Name = "John";
obj.CreateDate = DateTime.Now;
lst.Add(obj);
obj = new ExpandoObject(); // re-instantiate the obj if you want to differentiate from the List itself
obj.Name = "Sara";
obj.CreateDate = DateTime.Now.AddMonths(-10);
lst.Add(obj);
foreach (var item in lst)
{
Console.WriteLine($"{item.Name} - {item.CreateDate}");
}
You can even filter the list dynamically
Console.WriteLine(lst.Find(i=>i.Name == "John").Name);
Hope it helps.
EDIT
You need to re-instantiate your dynamic obj on each adding. If you dont, your list will have nothing but 2 "Sara"s.
Update
Well, with a little bit work on this this solution got worked for me.
I used JsonConvert.DeserializeObject<ExpandoObject>(...) instead of dynamic. Then wrote a LookUp method for inspecting the element. I think first problem with your code is deserializing your serialized object as dynamic instead of ExpandoObject. After that correction, it was not that hard for the casting dictinaries and getting key-value oriented values.
Here is my code:
var lst = new List<dynamic>();
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("Name", "John");
dict.Add("CreateDate", DateTime.Now);
lst.Add(JsonConvert.DeserializeObject<ExpandoObject>(JsonConvert.SerializeObject(dict)));
dict.Clear();
dict.Add("Name", "Sara");
dict.Add("CreateDate", DateTime.Now);
lst.Add(JsonConvert.DeserializeObject<ExpandoObject>(JsonConvert.SerializeObject(dict)));
dict.Clear();
var res = LookUp(lst, "Name", "Sara");
And after that LookUp method
public static object LookUp(List<dynamic> lst, string propName, object value)
{
return lst.FindAll(i =>
{
var dic = i as IDictionary<string, object>;
return dic.Keys.Any(key => dic[key].ToString().Contains(value.ToString()));
});
}
Also if you dont want to cast it to dictionary here is an alternative method for it:
private static object GetProperty(dynamic target, string name)
{
var site =
CallSite<Func<CallSite, dynamic, object>>
.Create(Microsoft.CSharp.RuntimeBinder.Binder.GetMember(CSharpBinderFlags.None, name, target.GetType(),
new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)}));
return site.Target(site, target);
}
public static object LookUpAlt(List<dynamic> lst, string propName, object value)
{
return lst.FindAll(i => GetProperty(i, propName).Equals(value));
}

Dynamically creating an object with dynamic children using data at runtime with ExpandoObject in C#

I've created a dynamic object and set properties and values to it at runtime using ExpandoObject
dynamic parentDynamic = new ExpandoObject();
var parentName = "GroupOne";
((IDictionary<String, Object>)parentDynamic)[parentName] = "default";
Console.WriteLine(parentDynamic.GroupOne);
The Console successfully outputs "default" as expected.
I've also created a child object with multiple properties in the same manner
dynamic childDynamic = new ExpandoObject();
var childProperty1 = "FirstName";
var childProperty2 = "LastName";
var childProperty3 = "Occupation";
((IDictionary<String, Object>)childDynamic)[childProperty1] = "John";
((IDictionary<String, Object>)childDynamic)[childProperty2] = "Smith";
((IDictionary<String, Object>)childDynamic)[childProperty3] = "Plumber";
Console.WriteLine(childDynamic.Occupation);
The Console successfully outputs "Plumber" as expected.
Where I am getting in a jam is when I attempt to add the childDynamic object to the parentDynamic object and give it a name at runtime. Here is my latest failed attempt:
var childName = "ChildOne";
((IDictionary<String, Object>)((IDictionary<String, Object>)parentDynamic)[parentName])[childName] = childDynamic;
Console.Write(parentDynamic.GroupOne.ChildOne.Occupation);
The error I am getting when attempting the assignment is: Unable to cast object of type 'System.String' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.
Essentially I would like to be able access parentDynamic.GroupOne.ChildOne.Occupation and get back "Plumber" or parentDynamic.GroupOne.ChildOne.FirstName and get back "John"
Originally I was trying to make my assignments all at once like so
parentDynamic["GroupOne"]["ChildOne"]["Occupation"] = "Plumber"
But I get the error Cannot apply indexing with [] to an expression of type 'System.Dynamic.ExpandoObject' Which is why I went down the path of creating a parent and child object and casting them as Dictionary objects first. Ideally I would like to just do something like the above as it's MUCH simpler.
In order to be able to use parentDynamic.GroupOne.ChildOne syntax, GroupOne property should also be dynamic ExpandoObject while in your case it is a string.
Something like this:
dynamic parentDynamic = new ExpandoObject();
parentDynamic.GroupOne = new ExpandoObject();
parentDynamic.GroupOne.ChildOne = new ExpandoObject();
parentDynamic.GroupOne.ChildOne.FirstName = "John";
parentDynamic.GroupOne.ChildOne.LastName = "Smith";
parentDynamic.GroupOne.ChildOne.Occupation = "Plumber";
or with IDictionary<string, object> casts:
IDictionary<string, object> parent = new ExpandoObject();
IDictionary<string, object> group = new ExpandoObject();
IDictionary<string, object> child = new ExpandoObject();
child["FirstName"] = "John";
child["LastName"] = "Smith";
child["Occupation"] = "Plumber";
parent["GroupOne"] = group;
group["ChildOne"] = child;
dynamic parentDynamic = parent;
Console.WriteLine(parentDynamic.GroupOne.ChildOne.Occupation);

In C#, how do I remove a property from an ExpandoObject?

Say I have this object:
dynamic foo = new ExpandoObject();
foo.bar = "fizz";
foo.bang = "buzz";
How would I remove foo.bang for example?
I don't want to simply set the property's value to null--for my purposes I need to remove it altogether. Also, I realize that I could create a whole new ExpandoObject by drawing kv pairs from the first, but that would be pretty inefficient.
Cast the expando to IDictionary<string, object> and call Remove:
var dict = (IDictionary<string, object>)foo;
dict.Remove("bang");
You can treat the ExpandoObject as an IDictionary<string, object> instead, and then remove it that way:
IDictionary<string, object> map = foo;
map.Remove("Jar");
MSDN Example:
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");
You can cast it as an IDictionary<string,object>, and then use the explicit Remove method.
IDictionary<string,object> temp = foo;
temp.Remove("bang");

Assign the literal string as a property of a dynamic object during runtime and access it

How can I assign the fieldname of a sqldatareader during runtime dynamically to a dynamic object?
Lets assume I have read the fieldname of a SqlDataReader into a variable:
string sqlDataReaderFieldNameStringVariable = reader.GetName(index);
I can not say:
dynamic dyn = new ExpandoObject();
dyn.sqlDataReaderFieldNameStringVariable = "test";
How can I do that?
UPDATE:
still time to get a point ;-) I add my dyn object to a List of type ExpandoObject which is the return value of a method. When I access the list via data[0].test property does not exist while compile time ???
When I do this outside of the method returning the List:
dynamic bla = (ExpandoObject)data[0];
String shit = bla.Name;
Why do I have to cast it? Any workaround? Thanks Jon.
You have to cast your ExpandoObject dyn to IDictionary<string, object> first to do that:
dynamic dyn = new ExpandoObject();
var dynDict = dyn as IDictionary<string, object>;
dynDict[sqlDataReaderFieldNameStringVariable] = "test";
For most dynamic objects, it's tricky. Doable (using IDynamicMetaObjectProvider) but tricky. If you're really using ExpandoObject, it's simple because that implements IDictionary<string, object>:
dynamic dyn = new ExpandoObject();
var dictionaryView = (IDictionary<string, object>) dyn;
dictionaryView[sqlDataReaderFieldNameStringVariable] = "test";

Categories