Here is my code :
dynamic App = new ExpandoObject();
//App names are SAP, CRM and ERP
//App names - adding static
//App.SAP = new ExpandoObject();
//App.CRM = new ExpandoObject();
//App.ERP = new ExpandoObject();
The last 4 lines, I am adding an expando object static as i know the app names previously. But I want to do this dynamically.
I can do for the properties dynamically :
AddProperty(App.SAP, "Name", "sap name");
AddProperty(App.SAP, "UserID", "sap userid");
AddProperty(App.SAP, "EmailID", "userid@sap.com");
AddProperty(App.SAP, "GroupOf", "group1, group2, group3");
public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
{
// ExpandoObject supports IDictionary so we can extend it like this
var expandoDict = expando as IDictionary<string, object>;
if (expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
else
expandoDict.Add(propertyName, propertyValue);
}
but I need to add this object App.SAP to this App which is also an expandoobject, so I can add App.CRM or App.ERP dynamically later on.
>Solution :
You will get
ExpandoObjectdoesn’t have a definition forSAP…
with this approach:
AddProperty(App.SAP, "Name", "sap name");
as you didn’t declare the SAP in APP ExpandoObject.
Instead, you can try to modify the AddProperty method by providing the parentName and deal with the nested object.
AddProperty(App, "SAP", "Name", "sap name");
AddProperty(App, "SAP", "UserID", "sap userid");
AddProperty(App, "SAP", "EmailID", "userid@sap.com");
AddProperty(App, "SAP", "GroupOf", "group1, group2, group3");
public static void AddProperty(ExpandoObject expando, string parentName, string propertyName, object propertyValue)
{
// ExpandoObject supports IDictionary so we can extend it like this
var expandoDict = expando as IDictionary<string, object>;
if (expandoDict.ContainsKey(parentName))
{
((IDictionary<string, object>)expandoDict[parentName])[propertyName] = propertyValue;
}
else
{
dynamic child = new Dictionary<string, object>
{
{ propertyName, propertyValue }
};
expandoDict.Add(parentName, child);
}
}