Adding dynamic object to json - c#

first of all, thanks for reading. Furthermore, i need your help!
By the way, im using Newtonsoft.Json;
How can i add a string to this:
obj.namedTypes.Menu.fields.< string > = new ExpandoObject();
So i have this code at the moment:
internal class Program
{
private static void Main(string[] args)
{
Regex reg = new Regex(":addSubMenu\\((?<Description>.+),[a-z A-Z](\'|\")(?<Identifier>[a-zA-Z]+)(\'|\")\\)"); //Regular expression for finding the id and description i want.
dynamic obj = new ExpandoObject();
obj.global = new ExpandoObject();
obj.global.type = "table";
obj.global.fields = new ExpandoObject();
obj.global.fields.scriptConfig = new ExpandoObject();
obj.global.fields.scriptConfig.type = "function";
obj.global.fields.scriptConfig.args = new string[] {};
obj.global.fields.scriptConfig.description = "a simple description";
obj.global.fields.scriptConfig.returnTypes = new List<ExpandoObject>();
dynamic arguments = new ExpandoObject();
arguments.type = "ref";
arguments.name = "Menu";
obj.global.fields.scriptConfig.returnTypes.Add(arguments);
obj.namedTypes = new ExpandoObject();
obj.namedTypes.Menu = new ExpandoObject();
obj.namedTypes.Menu.type = "table";
obj.namedTypes.Menu.fields = new ExpandoObject();
Console.WriteLine(JsonConvert.SerializeObject(obj, Formatting.Indented));
MatchCollection matches = reg.Matches(File.ReadAllText("test.txt"));
string description;
string value;
foreach (Match m in matches)
{
description = m.Groups["Description"].ToString();
value = m.Groups["Identifier"].ToString();
/* I want to add the value as a object like this: ->
* obj.namedTypes.Menu.fields.<value> = new ExpandoObject();
* obj.namedTypes.Menu.fields.<value>.description = description;
*/
Console.WriteLine($"Description: {description}\nValue: {value}");
}
Console.ReadLine();
}
I want to add the value as a object like this: ->
obj.namedTypes.Menu.fields.<value> = new ExpandoObject();
obj.namedTypes.Menu.fields.<value>.description = description;

Try using Dictionary.
Your modified code would be -
//Initialization of Dictonary
obj.namedTypes.Menu.fields = new Dictionary<string,string>();
//Reading from File and iteration on matches
MatchCollection matches = reg.Matches(File.ReadAllText("test.txt"));
string description;
string value;
foreach (Match m in matches)
{
description = m.Groups["Description"].ToString();
value = m.Groups["Identifier"].ToString();
obj.namedTypes.Menu.fields.Add(description , value);
}
//End: Serialize the Whole stuff
Console.WriteLine(JsonConvert.SerializeObject(obj, Formatting.Indented));

Related

C# dynamic ExpandoObject Array

please tell me, how do I get the json like this:
dynamic packet = new ExpandoObject();
packet.type = "somethink";
packet.user = 12345;
packet.nets[0].amout = 123;
packet.nets[0].lower = 0;
packet.nets[1].amout = 345;
packet.nets[1].lower = 1;
string input = Newtonsoft.Json.JsonConvert.SerializeObject(packet);
Its not workig, error:
An unhandled exception of type "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException" in System.Core.dll
For more information: "System.Dynamic.ExpandoObject" does not contain definitions of "nets"
Thanks.
It's the ExpandoObject who's a dynamic object. The rest of properties should be other ExpandoObject instances or regular objects, arrays, collections...
For example:
packet.nets = new[]
{
new { amount = 123, lower = 0 },
new { amount = 345, lower = 1 }
}
Or:
packet.nets = new[]
{
new Dictionary<string, int> { { "amount", 345 }, { "lower", 0 } },
new Dictionary<string, int> { { "amount", 123 }, { "lower", 1 } }
}
There're many other approaches, including the use of instances of concrete classes.
Firstly, you need create nets in packet object, like this:
packet.nets = new dynamic[2];
And initialize the objects in nets, if you want with `ExpandoObject too:
packet.nets[0] = new ExpandoObject();
packet.nets[1] = new ExpandoObject();
Then is done, complete code:
dynamic packet = new ExpandoObject();
packet.type = "somethink";
packet.user = 12345;
packet.nets = new dynamic[2];
packet.nets[0] = new ExpandoObject();
packet.nets[0].amout = 123;
packet.nets[0].lower = 0;
packet.nets[1] = new ExpandoObject();
packet.nets[1].amout = 345;
packet.nets[1].lower = 1;
string input = Newtonsoft.Json.JsonConvert.SerializeObject(packet);
You first need to declare nets. For example
packet.nets = new Dictionary<int, dynamic>();
Then you'll need to instantiate the instances of nets
packet.nets[0] = new {amount = 123, lower = 0};
The result being
dynamic packet = new ExpandoObject();
packet.type = "somethink";
packet.user = 12345;
packet.nets = new Dictionary<int, dynamic>();
packet.nets[0] = new { amount = 123, lower = 0 };
packet.nets[1] = new { amount = 345, lower = 1 };

How to generate mdx query using C#?

I am new to mdx query and I am very curious about mdx query generation using C# so I searched for any demo or open source then I found Ranet.olap (https://ranetuilibraryolap.codeplex.com/) which is providing what I need.
After taking the dlls I tried to incorporate them in my code. I am pasting my full console code which should generate mdx query but it's not doing so, am I doing something wrong?
using System;
using System.Collections.Generic;
using Microsoft.AnalysisServices.AdomdClient;
using Ranet.Olap.Core.Managers;
using Ranet.Olap.Core.Metadata;
using Ranet.Olap.Core.Types;
namespace MDX
{
class Program
{
static void Main(string[] args)
{
startWork();
}
public static void startWork()
{
string connString = "Provider=MSOLAP.3; Data Source=localhost;Initial Catalog=AdventureWorkDW2008R2;Integrated Security=SSPI;";
CubeDef cubes;
AdomdConnection conn = new AdomdConnection(connString);
conn.Open();
cubes = conn.Cubes.Find("AdventureWorkCube");
Ranet.Olap.Core.Managers.MdxQueryBuilder mdx = new Ranet.Olap.Core.Managers.MdxQueryBuilder();
mdx.Cube = cubes.Caption;
List<Ranet.Olap.Core.Wrappers.AreaItemWrapper> listColumn = new List<Ranet.Olap.Core.Wrappers.AreaItemWrapper>();
List<Ranet.Olap.Core.Wrappers.AreaItemWrapper> listRow = new List<Ranet.Olap.Core.Wrappers.AreaItemWrapper>();
List<Ranet.Olap.Core.Wrappers.AreaItemWrapper> listData = new List<Ranet.Olap.Core.Wrappers.AreaItemWrapper>();
//Column area
Dimension dmColumn = cubes.Dimensions.Find("Dim Product");
Microsoft.AnalysisServices.AdomdClient.Hierarchy hColumn = dmColumn.Hierarchies["English Product Name"];
//hierarchy properties
List<PropertyInfo> lPropInfo = new List<PropertyInfo>();
foreach (var prop in hColumn.Properties)
{
PropertyInfo p = new PropertyInfo();
p.Name = prop.Name;
p.Value = prop.Value;
lPropInfo.Add(p);
}
Ranet.Olap.Core.Wrappers.AreaItemWrapper areaIColumn = new Ranet.Olap.Core.Wrappers.AreaItemWrapper();
areaIColumn.AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper;
areaIColumn.Caption = hColumn.Caption;
areaIColumn.CustomProperties = lPropInfo;
listColumn.Add(areaIColumn);
//Rows Area
Dimension dmRow = cubes.Dimensions.Find("Due Date");
Microsoft.AnalysisServices.AdomdClient.Hierarchy hRow = dmRow.Hierarchies["English Month Name"];
List<PropertyInfo> lRowPropInfo = new List<PropertyInfo>();
foreach (var prop in hRow.Properties)
{
PropertyInfo p = new PropertyInfo(prop.Name,prop.Value);
lRowPropInfo.Add(p);
}
Ranet.Olap.Core.Wrappers.AreaItemWrapper areaIRow = new Ranet.Olap.Core.Wrappers.AreaItemWrapper();
areaIRow.AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper;
areaIRow.Caption = hRow.Caption;
areaIRow.CustomProperties = lRowPropInfo;
listRow.Add(areaIRow);
//Measure Area or Data Area
Measure ms = cubes.Measures.Find("Order Quantity");
Ranet.Olap.Core.Wrappers.AreaItemWrapper areaIData = new Ranet.Olap.Core.Wrappers.AreaItemWrapper();
areaIData.AreaItemType = AreaItemWrapperType.Measure_AreaItemWrapper;
areaIData.Caption = ms.Caption;
List<PropertyInfo> lmpropInfo = new List<PropertyInfo>();
foreach (var prop in ms.Properties)
{
PropertyInfo p = new PropertyInfo(prop.Name, prop.Value);
lmpropInfo.Add(p);
}
areaIData.CustomProperties = lmpropInfo;
listData.Add(areaIData);
mdx.AreaWrappersColumns = listColumn;
mdx.AreaWrappersRows = listRow;
mdx.AreaWrappersData = listData;
string mdxQuery = mdx.GenerateMdxQuery();
conn.Close();
}
}
}
A simple example of the generation mdx query (only Ranet OLAP 3.7 version):
using System.Collections.Generic;
using Ranet.Olap.Core.Data;
using Ranet.Olap.Core.Managers;
using Ranet.Olap.Core.Types;
using Ranet.Olap.Core.Wrappers;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
startWork();
}
public static void startWork()
{
var mdx = new QueryBuilderParameters
{
CubeName = "[Adventure Works]",
SubCube = "",
MdxDesignerSetting = new MDXDesignerSettingWrapper(),
CalculatedMembers = new List<CalcMemberInfo>(),
CalculatedNamedSets = new List<CalculatedNamedSetInfo>(),
AreaWrappersFilter = new List<AreaItemWrapper>(),
AreaWrappersColumns = new List<AreaItemWrapper>(),
AreaWrappersRows = new List<AreaItemWrapper>(),
AreaWrappersData = new List<AreaItemWrapper>()
};
//define parameters
mdx.MdxDesignerSetting.HideEmptyColumns = false;
mdx.MdxDesignerSetting.HideEmptyRows = false;
mdx.MdxDesignerSetting.UseVisualTotals = false;
mdx.MdxDesignerSetting.SubsetCount = 0;
var itemCol1 = new Hierarchy_AreaItemWrapper
{
AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper,
UniqueName = "[Customer].[Customer Geography]"
};
mdx.AreaWrappersColumns.Add(itemCol1);
var itemRow1 = new Hierarchy_AreaItemWrapper
{
AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper,
UniqueName = "[Date].[Calendar]"
};
mdx.AreaWrappersRows.Add(itemRow1);
var itemData1 = new Measure_AreaItemWrapper();
itemData1.AreaItemType = AreaItemWrapperType.Measure_AreaItemWrapper;
itemData1.UniqueName = "[Measures].[Internet Order Count]";
mdx.AreaWrappersData.Add(itemData1);
string query = MdxQueryBuilder.Default.BuildQuery(mdx, null);
}
}
}
MDX Query result:
SELECT
HIERARCHIZE(HIERARCHIZE([Customer].[Customer Geography].Levels(0).Members)) DIMENSION PROPERTIES PARENT_UNIQUE_NAME, HIERARCHY_UNIQUE_NAME, CUSTOM_ROLLUP, UNARY_OPERATOR, KEY0 ON 0,
HIERARCHIZE(HIERARCHIZE([Date].[Calendar].Levels(0).Members)) DIMENSION PROPERTIES PARENT_UNIQUE_NAME, HIERARCHY_UNIQUE_NAME, CUSTOM_ROLLUP, UNARY_OPERATOR, KEY0 ON 1
FROM
[Adventure Works]
WHERE ([Measures].[Internet Order Count])
CELL PROPERTIES BACK_COLOR, CELL_ORDINAL, FORE_COLOR, FONT_NAME, FONT_SIZE, FONT_FLAGS, FORMAT_STRING, VALUE, FORMATTED_VALUE, UPDATEABLE, ACTION_TYPE
Still in process of revising code for this engine, though some suggestions for you:
It looks like you just grab cube metadata (dims, measures etc.) and pass it to generator. This does not sound like a way to generate MDX. MDX statement should look like
select
{
// measures, calculated members
} on 0,
{
// dimension data - sets
} on 1 // probably more axis
from **Cube**
All other parameters are optional

Remove specific symbol from string

I have different string that starts and ends with { } like so {somestring}. I want to remove the delimiters from the string so that it shows somestring only. I can't do anything that counts the letters because I don't always know the length of the string.
Maybe this will help. Here is the code, somewhere here I want to delete the delimiters.
private static MvcHtmlString RenderDropDownList(FieldModel model)
{
ISerializer serializer = new SerializeJSon();
var value = "";
var tb1 = new TagBuilder("select");
tb1.MergeAttribute("id", model.QuestionId);
tb1.MergeAttribute("name", model.QuestionId);
tb1.MergeAttributes(GetHtmlAttributes(model.HtmlAttributes));
tb1.AddCssClass("form-field");
var sb = new StringBuilder();
MatchCollection matches = RegexHelper.GetBetweenDelimiter(model.FieldValues, "{", "}");
foreach (Match match in matches)
{
var o = match; //Solution var o = match.toString();
var tb2 = new TagBuilder("option");
//Solution string newString = o.trim(new [] { "{","}"});
tb2.SetInnerText(o.ToString()); //Solution tb2.SetInnerText(newString);
sb.Append(tb2.ToString(TagRenderMode.Normal) + "\n");
}
tb1.InnerHtml = sb.ToString();
return new MvcHtmlString(tb1.ToString(TagRenderMode.Normal));
}
string newString = originalString.Trim(new[] {'{', '}'});
Can you use Replace
string somestring = somestring.Replace("{","").Replace("}","");
Alternatively, you can use StartsWith and EndsWith which will only remove from the beginning and the end of the string, for example:
string foo = "{something}";
if (foo.StartsWith("{"))
{
foo = foo.Remove(0, 1);
}
if (foo.EndsWith("}"))
{
foo = foo.Remove(foo.Length-1, 1);
}
You could use replace e.g.
string someString = "{somestring}";
string someOtherString = someString.Replace("{","").Replace("}","");

Dynamic Objects in WCF not possible?

When building a response in WCF (json), im pretty sure it's not possible to use completely dynamic objects, but just wanted to double check here first.
An ideal response would look something like:
"userTypes" :
{
"BartSimpson" :
{
"url" : "foo",
"desc" : "bar"
},
"LisaSimpson" :
{
"url" : "foo",
"desc" : "bar"
}
}
In 'compiled' code, the above could be performed by the following architecture (slightly pseudocode):
public class Character{
string url {get;set;}
string desc{get;set;}
}
public class UserTypes{
public Character BartSimpson{get;set;}
public Character LisaSimpson{get;set;}
}
But my main goal is that BartSimpson and LisaSimpson are not 'compiled' so I could have any number of Character classes, with any name / identifer in the response.
Add the following using at the top of your service implementation class (make sure that you also add the proper references in your project):
using Newtonsoft.Json;
using System.Dynamic;
using System.IO;
using System.Text;
You may try this simple method which outputs the dynamic result:
public string GetData()
{
dynamic d = new ExpandoObject();
dynamic bartSimpson = new ExpandoObject();
dynamic lisaSimpson = new ExpandoObject();
bartSimpson.url = "foo";
bartSimpson.desc = "bar";
lisaSimpson.url = "foo";
lisaSimpson.desc = "bar";
d.userTypes = new ExpandoObject();
d.userTypes.BartSimpson = bartSimpson;
d.userTypes.LisaSimpson = lisaSimpson;
var s = JsonSerializer.Create();
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
s.Serialize(sw, d);
}
return sb.ToString();
}
To go one more step further (you'll just have to pass Bart and Lisa in the comaSeparatedNames value), you could do:
public string GetData(string comaSeparatedNames)
{
string[] names = comaSeparatedNames.Split(',');
dynamic d = new ExpandoObject();
dynamic dNames = new ExpandoObject();
foreach (var name in names)
{
dynamic properties = new ExpandoObject();
properties.url = "foo";
properties.desc = "bar";
((IDictionary<string, object>)dNames).Add(name, properties);
}
((IDictionary<string, object>)d).Add("userTypes", dNames);
var s = JsonSerializer.Create();
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
s.Serialize(sw, d);
}
// deserializing sample
//dynamic dummy = new ExpandoObject();
//var instance = s.Deserialize(new StringReader(sb.ToString()),
// dummy.GetType());
//var foo = instance.userTypes.BartSimpson.url;
return sb.ToString();
}
Note: I've also provided the lines (commented) for deserialization.

How to Create a campaign in MailChimp using ASP.Net

I need to create and send immediately campaigns in MailChimp.com. I used C# wrapper Percepective MCAPI.dll for this purpose.
from the MailChimp API, Its clear that we cannot lists but can create campaigns. I tried code but the campaignID is retured null; no exception thrown atleast. I did set the campaigntype to Auto.
here is my code snippet:
try
{
string apiKey = "api-us2"; // API KEY is valid
string emailAddress = "ravinderpal.singh#abc.net";
listsForEmailInput lstForEmailInput = new listsForEmailInput(apiKey, emailAddress);
listsForEmail cmd = new listsForEmail(lstForEmailInput);
listsForEmailOutput lstEmailOutPut = cmd.Execute();
List lstResults = lstEmailOutPut.result;
string listID = lstResults[0]; // Got Precraeted List ID( Valid Confirmed )
Console.WriteLine("\n" + listID);
// compaign Create
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listID;
campaignCreateOpt.subject = " New Campaign from dev_Anil";
campaignCreateOpt.from_email = "anil.k#abc.net";
campaignCreateOpt.from_name = "anil";
Dictionary content = new Dictionary();
content.Add("html", "Helloaasdsa");
content.Add("text", "Hi all !! this is dev_anil");
content.Add("url", "");
content.Add("archive", "");
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "any"; // Could not set Condition -- need help for this
// Need to set a Dictionary typeOptions because null is not supported
Dictionary typeOptions = new Dictionary();
campaignCreateParms campaignCreateParms = new campaignCreateParms(apiKey, EnumValues.campaign_type.auto, campaignCreateOpt, content, csOptions, typeOptions);
campaignCreateInput campaignCreateInput = new campaignCreateInput(campaignCreateParms);
campaignCreate campaignCreate = new campaignCreate(campaignCreateInput);
campaignCreateOutput ccOutput = campaignCreate.Execute(campaignCreateInput);
string abc = ccOutput.result; // This comes out to null
}
catch(Exception ee)
{
Console.WriteLine("\n\n Exception :" + ee.Message); // no exception
}
can anybody show me the right direction and what is wrong with the code.
any help would be much appreciated.
thanks.
I solved this problem and here is code as solution. here listID is precreated List ID in your account in Mailchimp.
private void CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 100;
string campaignID =string.Empty;
// compaign Create Options
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listID;
campaignCreateOpt.subject = "subject";
campaignCreateOpt.from_email = "abc#xyz.com";
campaignCreateOpt.from_name = "abc";
campaignCreateOpt.template_id = TemplateID;
// Content
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("html_ArticleTitle1", "ArticleTitle1");
content.Add("html_ArticleTitle2","ArticleTitle2");
content.Add("html_ArticleTitle3", "ArticleTitle3");
content.Add("html_Article1", "Article1");
content.Add("html_Article2", "Article2");
// Conditions
List<campaignSegmentCondition> csCondition = new List<campaignSegmentCondition>();
campaignSegmentCondition csC = new campaignSegmentCondition();
csC.field = "interests-" + 123; // where 123 is the Grouping Id from listInterestGroupings()
csC.op = "all";
csC.value = "";
csCondition.Add(csC);
// Options
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "all";
// Type Options
Dictionary<string, string> typeOptions = new Dictionary<string, string>();
typeOptions.Add("offset-units", "days");
typeOptions.Add("offset-time", "0");
typeOptions.Add("offset-dir", "after");
// Create Campaigns
campaignCreate campaignCreate = new campaignCreate(new campaignCreateInput(apiKey, EnumValues.campaign_type.plaintext, campaignCreateOpt, content, csOptions, typeOptions));
campaignCreateOutput ccOutput = campaignCreate.Execute();
List<Api_Error> error = ccOutput.api_ErrorMessages; // Catching API Errors
if (error.Count <= 0)
{
campaignID = ccOutput.result;
}
else
{
foreach (Api_Error ae in error)
{
Console.WriteLine("\n ERROR Creating Campaign : ERRORCODE\t:" + ae.code + "\t ERROR\t:" + ae.error);
}
}
}
I removed the url and archive from the content. Then the campaign was created just fine:
// campaign Create
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listId;
campaignCreateOpt.subject = " New Campaign from Someemone";
campaignCreateOpt.from_email = "someone#home.com";
campaignCreateOpt.from_name = "someone";
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("html", "Lots of cool stuff here.");
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "any"; // Could not set Condition -- need help for this
// Need to set a Dictionary typeOptions because null is not supported
Dictionary<string,string> typeOptions = new Dictionary<string, string>();
campaignCreateParms campaignCreateParms = new campaignCreateParms(apiKey, EnumValues.campaign_type.trans, campaignCreateOpt, content, csOptions, typeOptions);
campaignCreateInput campaignCreateInput = new campaignCreateInput(campaignCreateParms);
campaignCreate campaignCreate = new campaignCreate(campaignCreateInput);
campaignCreateOutput ccOutput = campaignCreate.Execute(campaignCreateInput);
string newCampaignId = ccOutput.result; // Not null anymore

Categories

Resources