jquery create list<dictionary<string,string>> object - c#

I have a object defined in my C# code behind as
public List<Dictionary<string, string>> attributesList
{
get;
set;
}
now I need to fill this object from Jquery
That is, in my Jquery file I m getting certain values that I need to fill in this object.
I am stuck on how to create a JSON object from the following code
selectedAttributes.each(function (key, value) {
var attributeName = value.attributes.title.value;
var attributeValue = $('#' + attributeName + ' option:selected').text();
});
that can be supplied to the attributesList
I need to put (attributeName, attributeValue) pair in the attributelist object
I know I am not clear enough in asking this question, but if any information is required please comment and I'll reply almost instantly.

A Dictionary would be just an object in JS. You're able to address the items within the dictionary by it's name.
dic['name'] = 'value'; // valid
dic.name = 'value'; // also valid
var attrName = 'name';
dic[attrName] ='value'; // also valid
That should be enough info to let you accomplish your task.

Related

Ranorex validate-How to check if RepoItemInfo object is equal to string data in C# code?

I just want to check if my RepoItemInfo object (which is username Joe McAdam btw) is equal to string data.
I just tracked this element in Chrome, stored it in my repository and it is a span with #innertext="JoeMcAdam"
Then I made code module for mapping these objects in C# code:
public RepoItemInfo LeftNameRepoItem {get {return _pageHome.Home.ImeLijevoInfo; }}
And I have prepared data Name in my context file for this LeftName to check if they are equal:
void ITestModule.Run()
{
var dto = new LoginDto () {
Name = "Joe McAdam",
WaitTimeLimit = 20000,
};
LoginDtoContext.template = dto;
}
I just need a proper code example for checking if they are eqal. What should I do? Do I have to make some adapter for this RepoItemInfo to convert it in string, text or something else?
I hope I provided enough details about my problem.
Thanks in advance!

C# Create Deedle DataFrame from JSON response

I'm having a bit of trouble loading a JSON response from this request into a Deedle DataFrame:https://sampleserver6.arcgisonline.com/arcgis/rest/services/Earthquakes_Since1970/FeatureServer/0/query?where=OBJECTID%3C10&returnGeometry=false&f=json
In the JSON, what I'm interested are the features. More specifically, for each feature there are attributes - I want essentially just a collection of those attributes to load into a DataFrame. In this particular case, there is only one attribute "name" so my expectation is that the resulting DataFrame would have a column "name" with the values shown.
I've tried using json2csharp and creating my own class, but the result either doesn't have the column header/values or the values are missing. I'm not really sure what I'm doing wrong or if I'm even approaching this the right way. My understanding from the Deedle documentation is that it should be possible to create a DataFrame from a collection of objects: https://bluemountaincapital.github.io/Deedle/csharpframe.html#Creating-and-loading-data-frames. Certainly, using the Enumerable example listed on the page works as expected.
Here is the pertinent section of my code:
string url = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Earthquakes_Since1970/FeatureServer/0/query?";
WebClient wc = new WebClient();
wc.QueryString.Add("where", "OBJECTID<10");
wc.QueryString.Add("returnGeometry", "false");
wc.QueryString.Add("f", "json");
var data = wc.UploadValues(url, "POST", wc.QueryString);
var responseString = UnicodeEncoding.UTF8.GetString(data);
JObject o = JObject.Parse(responseString);
dynamic x = JsonConvert.DeserializeObject(responseString);
var testObjList = new List<dynamic>();
foreach (dynamic element in x.features)
{
testObjList.Add(new myClass { name = element.attributes.name});
Console.WriteLine($"{element.attributes.name}");
}
var dfObjects = Frame.FromRecords(testObjList);
dfObjects.Print();
var df = Frame.FromRecords(test);
df.Print(); // No headers or values shown
where myClass is just this:
public class myClass{
public string name { get; set; }
}
Any help/pointers would be much appreciated!
The Frame.FromRecords operation relies on static type information to figure out what properties the class has. In your case, you define the list of objects as List<dynamic> - this is compiled as Object and so Deedle does not see any members.
To fix this, all you need to do is to define the type as a list of myClass objects:
var testObjList = new List<myClass>();
A more compact approach using an anonymous type would work too:
var testObjList =
((IEnumerable<dynamic>)x.features).Select(element =>
new { name = element.attributes.name });
var dfObjects = Frame.FromRecords(testObjList);

Is it possible to add fields with invalid characters to a .net AnonymousType?

I'm trying to send a JSON message to facebook that they call a game.achievement but I wanted to create the object using an AnonymousType before Posting. The problem is one of the fields is "game:points" (with the colon). As you can see I've used the # prefix for the object field but it doesn't work for the game:points field. It gets underlined in red and won't compile.
var paramsJson = new
{
privacy = new { value = "ALL_FRIENDS" },
#object = new
{
app_id = "my app id",
type = "game.achievement",
title = "Test",
#"game:points" = 100,
description = "Test",
image = "img.png"
}
};
I've tried many varieties of #, double quotes etc. Is it possible or do I need to just use a StringBuilder for this?
Why don't you just use a dictionary?
var postData = new Dictionary<string, object>
{
{"game:points", 100}
}
Presumably you're going to have to serialize your object to Post it regardless of how it's constructed. Serializing this to JSON would result in the same structure. Alternatively, just do as other's have suggested and create a class for your payload. You can then use Newtonsoft to indicate alternative names for serialization.
public class GameAchievement
{
[JsonProperty("game:points")]
public int Points {get; set;}
}

JSON Deserialize Error: The given key was not present in the dictionary

I'm trying to output JSON to a drop down list in a web form. I've managed to get this far:
WebClient client = new WebClient();
string getString = client.DownloadString("http://myfeed.com/app_feed.php");
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>(getString);
string name = item["title"];
return name;
This brings back the feed ok but it runs into an error on the line:
string name = item["title"];
Bringing back this error:
Additional information: The given key was not present in the dictionary.
This is a sample of my feed:
{"apps":[{"title":"title1","description":"description1"},
{"title":"title2","description":"description2"},
{"title":"title3","description":"description3"}
So I thought that I was referencing the first title and I was planning to loop through them:
string name = item["title"];
But obviously not!
I have looked on Stackoverflow but I can't find an answer that I can apply to my own code.
title is inside another key apps and its an array so you should iterate it, I show you just select first one using index 0
string name = item["apps"][0]["title"];
you can access all by foreach
foreach (var ap in item["apps"])
{
Console.WriteLine(ap["title"]);
}
First, your JSON is invalid. Second: you need to loop over your items, as it is an array. If you want to access the first one, you could do: item["apps"][0]["title"]
Looping through all items:
var str = #"{""apps"":[{""title"":""title1"",""description"":""description1""},
{""title"":""title2"",""description"":""description2""},
{""title"":""title3"",""description"":""description3""}]}";
var serializer = new JavaScriptSerializer();
dynamic obj = serializer.Deserialize<object>(str);
foreach (var item in obj["apps"])
{
Console.WriteLine("item title: " + item["title"]);
}

Which approach to templating in C# should I take?

What I have
I have templates that are stored in a database, and JSON data that gets converted into a dictionary in C#.
Example: 
Template: "Hi {FirstName}"
Data: "{FirstName: 'Jack'}"
This works easily with one level of data by using a regular expression to pull out anything within {} in the template.
What I want
I would like to be able to go deeper in the JSON than the first layer.
Example:
Template: "Hi {Name: {First}}"
Data: "{Name: {First: 'Jack', Last: 'Smith'}}"
What approach should I be taking? (and some guidance on where to start with your pick)
A regular expression
Not use JSON in the template (in favor of xslt or something similar)
Something else
I'd also like to be able to loop through data in the template, but I have no idea at all where to start with that one!
Thanks heaps
You are in luck! SmartFormat does exactly as you describe. It is a lightweight, open-source string formatting utility.
It supports named placeholders:
var template = " {Name:{Last}, {First}} ";
var data = new { Name = new { First="Dwight", Last="Schrute" } };
var result = Smart.Format(template, data);
// Outputs: " Schrute, Dwight " SURPRISE!
It also supports list formatting:
var template = " {People:{}|, |, and} ";
var data = new { People = new[]{ "Dwight", "Michael", "Jim", "Pam" } };
var result = Smart.Format(template, data);
// Outputs: " Dwight, Michael, Jim, and Pam "
You can check out the unit tests for Named Placeholders and List Formatter to see plenty more examples!
It even has several forms of error-handling (ignore errors, output errors, throw errors).
Note: the named placeholder feature uses reflection and/or dictionary lookups, so you can deserialize the JSON into C# objects or nested Dictionaries, and it will work great!
Here is how I would do it:
Change your template to this format Hi {Name.First}
Now create a JavaScriptSerializer to convert JSON in Dictionary<string, object>
JavaScriptSerializer jss = new JavaScriptSerializer();
dynamic d = jss.Deserialize(data, typeof(object));
Now the variable d has the values of your JSON in a dictionary.
Having that you can run your template against a regex to replace {X.Y.Z.N} with the keys of the dictionary, recursively.
Full Example:
public void Test()
{
// Your template is simpler
string template = "Hi {Name.First}";
// some JSON
string data = #"{""Name"":{""First"":""Jack"",""Last"":""Smith""}}";
JavaScriptSerializer jss = new JavaScriptSerializer();
// now `d` contains all the values you need, in a dictionary
dynamic d = jss.Deserialize(data, typeof(object));
// running your template against a regex to
// extract the tokens that need to be replaced
var result = Regex.Replace(template, #"{?{([^}]+)}?}", (m) =>
{
// Skip escape values (ex: {{escaped value}} )
if (m.Value.StartsWith("{{"))
return m.Value;
// split the token by `.` to run against the dictionary
var pieces = m.Groups[1].Value.Split('.');
dynamic value = d;
// go after all the pieces, recursively going inside
// ex: "Name.First"
// Step 1 (value = value["Name"])
// value = new Dictionary<string, object>
// {
// { "First": "Jack" }, { "Last": "Smith" }
// };
// Step 2 (value = value["First"])
// value = "Jack"
foreach (var piece in pieces)
{
value = value[piece]; // go inside each time
}
return value;
});
}
I didn't handle exceptions (e.g. the value couldn't be found), you can handle this case and return the matched value if it wasn't found. m.Value for the raw value or m.Groups[1].Value for the string between {}.
Have you thought of using Javascript as your scripting language? I had great success with Jint, although the startup cost is high. Another option is Jurassic, which I haven't used myself.
If you happen to have a Web Application, using Razor maybe an idea, see here.
Using Regex or any sort of string parsing can certainly work for trivial things, but can get painful when you want logic or even just basic hierarchies. If you deserialize your JSON into nested Dictionaries, you can build a parser relatively easily:
// Untested and error prone, just to illustrate the concept
var parts = "parentObj.childObj.property".split('.');
Dictionary<object,object> current = yourDeserializedObject;
foreach(var key in parts.Take(parts.Length-1)){
current = current[key];
}
var value = current[parts.Last()];
Just whatever you do, don't do XSLT. Really, if XSLT is the answer then the question must have been really desperate :)
Why not us nvelocity or something?

Categories