Dynamic object anonymous type Azure DynamicTableEntity - c#

So I'm doing a exercise with wpf and getting data from azure table but I am using the DynamicTableEnity to query the cloudtableclient. A big issue comes in trying to covert the results that come back to a object that can be displayed in the Datagrid of WPF.
This requires a list of object, which I don't know what object comes back BUT I have all the data in the properites of the DynamicTableEnity. So my first hack at this was as follow.
List<dynamic> dynamicList = new List<dynamic>();
foreach (var entry in tableStorageEntry)
{
var dictionaryObject = AzureConversionHelper.Converstion(entry);
var json = new JavaScriptSerializer().Serialize(dictionaryObject);
dynamic foo = JObject.Parse(json);
dynamicList.Add(foo);
}
public static object Converstion(DynamicTableEntity entity)
{
var dictionary = new Dictionary<string, object>();
dictionary.Add("PartitionKey", entity.PartitionKey);
dictionary.Add("RowKey", entity.RowKey);
dictionary.Add("TimeStamp", entity.Timestamp.ToString());
foreach (var prop in entity.Properties)
{
dictionary.Add(prop.Key, prop.Value.PropertyAsObject);
}
return dictionary;
}
I had no idea what I am doing and it was kind of a struggle since I haven't worked much with anonymous objects. My hack was to convert the properties into a dictionary of strings convert them into a json string and then parse them back into a dynamic object. . . . . that sounds really bad even in my head but after a couple hours of slap around articles of anonymous types I came up with that idea.
This granted how horrible it is works, so its a start for me but it becomes a real issue when I am pull down large set of data, and it makes task almost painful since I'm almost doing a triple read through the data. Can anyone point me to a better method or maybe some pointer on how to better approach this issue.

Related

List does not get saved when I use Application.Current.SavePropertiesAsync in Xamarin forms

I am currently trying to save a list in Xamarin forms. I use this code snippet:
var list = new List<myClass> ();
Application.Current.Properties["myList"] = list;
await Application.Current.SavePropertiesAsync();
When I then close the app and use this code...
if (Application.Current.Properties.ContainsKey("myList"))
{
}
...I cannot reach this if statement.
I read something about people having issues saving a list with this solution but they solved it by converting it to a string. I am a bit unsure on how to do this. If I do this...
Application.Current.Properties["myList"] = list.ToString();
...the app crashes.
I saw that there is a plugin called "Settings" that I might need to use instead in case there isn't a solution to this problem but I would prefer to work with my current code if possible.
The Properties dictionary can only serialize primitive types for
storage. Attempting to store other types (such as List can
fail silently).
It means that you can't save List because it's not a primitive type of object. You can serialize it to JSON string for example then it will work. Code example:
var jsonValueToSave = JsonConvert.SerializeObject(myList);
Application.Current.Properties["myList"] = jsonValueToSave;
await Application.Current.SavePropertiesAsync();
Don't forget to deserialize JSON to List<string> when loading the value back.
Note that yourList.ToString() will not work in this case. More info here.
P.S.: Get familiar with the official documentation & check this post on another related thread.

Convert JSON to List of OrderedDictionaries, then Add() back to new List

I'm attempting to read the contents of a JSON file using Newtonsoft JSON which is a list of dictionaries, iterate through them, and create a new list of dictionaries after rooting out the one I don't want which will eventually be written back to the JSON file.
No matter what I try, I can't seem to be able to add the JSON entries within its list back to a new List. Here's the error:
Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:
The best overloaded method match for 'System.Collections.Generic.List<System.Collections.Specialized.OrderedDictionary>.Add(System.Collections.Specialized.OrderedDictionary)'
has some invalid arguments
Here's the JSON string I've deserialized:
[
{
"name":"test",
"custom":false,
"file":"strawberry-perl-5.10.1.2portable.zip",
"url":"http://strawberryperl/....",
"ver":"5.10.1",
"csum":"f86ae4b14daf0b1162d2c4c90a9d22e4c2452a98"
}
]
And here's my code:
dynamic customPerlList = JsonParse("perls_custom");
List<dynamic> updatedList = new List<dynamic>();
foreach (var perlStruct in customPerlList)
{
if (perlStruct.name != perlVersionToRemove)
{
Console.WriteLine("match");
updatedList.Add((OrderedDictionary)perlStruct);
}
}
I've just started developing in C#, so my attempts using examples found while searching either aren't sinking in, or I'm missing something else. Can someone please point out the err in my ways, and what the proper approach is to do what I'm attempting?
The most likely problem is that typeless JSON objects typically are matched with IDictionary<string, object> interfaces in .NET libraries; OrderedDictionary does not have that interface. And really, JSON objects are not considered ordered.
Perhaps you can switch to using a regularDictionary<string, object>, or writing a specific class to serialize to/from.
If you wanted to use Dictionary<string, object>, then you should consider deserializing as follows:
var list = JsonConvert.ToObject<List<Dictionary<string, object>>>(s);

How to retrieve nested json objects in C#?

Stripe Transfer JSON
I'm trying to get all charge IDs associated with a transfer.
var json = new StreamReader(context.Request.InputStream).ReadToEnd();
var stripeEvent = StripeEventUtility.ParseEvent(json);
StripeTransfer stripeTransfer;
switch (stripeEvent.Type)
{
case "transfer.created":
stripeTransfer = Stripe.Mapper<StripeTransfer>.MapFromJson(stripeEvent.Data.Object.ToString());
var transferId = stripeTransfer.Id;
stripeTransfer = _stripeManager.GetTransfer(transferId);
foreach (var charge in stripeEvent.Data.Object["transactions"])
{
}
_stripeManager.ProcessTransfer(stripeTransfer);
break;
In visual studio's immediate window, stripeEvent.Data.Object["transactions"] shows the data I want so I know that the json is getting sucked in properly. Those transactions are a collection of charges, they match my .net StripeCharge object. I'm having trouble figuring out how to iterate through the transactions...all I really need is the ID for each. Would like to see "transactions" as a C# IEnumerable object.
(the json in question is linked at the top of this post) let me know if more info is needed.
I've found the specific item is under ["transactions"]["data"][0]["id"] but there may be more than one so, still working on how to get them out and cast them...think I'm close but it seems like there should be a more elegant way of doing it.
EDIT,
Thanks Andrew, so even though I have all of the charge data, it is incoming data. So what I'll be doing is using the event to just get the id and then make the call to get the charge object from my own end to prevent any event spoofs. So that means I don't have to worry about casting at this point. Here is my solution, feel free to advise if there is a better way to do it
for (int i = 0; i < Int32.Parse(stripeEvent.Data.Object["transactions"]["total_count"].ToString()); i++)
{
string chargeId = stripeEvent.Data.Object["transactions"]["data"][i]["id"].ToString();
// do stuff with it
}
just for completeness:
Data under transactions looks like an array so should be able to index into them..
If you need to access to any other fields in the future you could construct c# objects but given the webhook 3rd party dance you are already doing probably not worth it as you only need id.

Locate and update runtime created object

Haven't found a duplicate answer to this yet, so here goes..
I need to create 'objects' (could be key:value pair, but I need to databind) during runtime from data I receive from a serial port.
For example I'll receive "012320.50". I am breaking this into an object/key for "0123" with a value of "20.50". I also need to databind a control to this. I can't know how many, or the 'name' of these sources until the data is streamed in. So i need to create them dynamically.
That said, I was planning on using a list of objects...but I hope there is a better solution. And I haven't figured out how to bind to these yet...?
Mock-example:
class myObject{
int Name{get;set;}
double Value{get;set}
}
Dictionary<int, myObject> dict = new Dictionary<int, myObject>();
when serial data is received I parse then create the object:
dict.Add(name, new myObject(Name=name, Value = value});
Now for my questions:
When the value comes through again for a source, how can I reference that and assign a new value? I was thinking of iterating through the Dictionary and if(Name == name) kinda stuff to change the value, but I'm thinking that's terrible and inefficient. Hopefully someone has a better way?
How can I databind a control to the same object? Not sure here at all...just starting with WPF. I understand how to databind...but to a dynamic object, not so much.

Looping through JSON in a C# dictionary

I am trying to implement a PHP function I have already made in C# but I have no idea of the syntax used in C# used to Navigate Dictionaries! (Associative arrays in PHP). What I am doing essentially is making a foreach loop to print each instance of a property in the associative array. I'm not sure if my question is completely clear so to make it easier, What would be the C# equivalent of this?
foreach ( $data->response->docs as $info )
{
echo "{$info->EventId},";
echo "{$info->VenueName},";
}
I just need a nudge in the right direction syntax wise.
Thanks
EDIT-
oops, when I posted this question I was tired. my problem is how to navigate a dictionary serialized from JSON. in my example I was parsing two properties from this sample data :-
{"responseHeader":{"status":0,"QTime":2},"response":{"facet_counts":{},"numFound":110,"docs":[{"VenueSEOLink":"/Aberdeen-Music-Hall-tickets-Aberdeen/venue/443660","VenueId":"10512085.....
etc etc....
So I am trying to figure out how to go down multiple levels through the dict. (C# equivalent of ->)
In C#, you can use a System.Collections.Dictionary or a generic System.Collections.Generic.Dictionary<TKey, TObject>. I recommend the generic dictionary because it is strongly-typed and you don't have to cast the contents every time you retrieve an object.
Assuming your EventId is an int, you can access it like this:
Dictionary<int, string> info = new Dictionary<int, string>();
int eventId = 42;
info[eventId] = "Some value";
var value = info[eventId];
// value = "Some value" as string
If you are using string keys just change the dictionary definition and key type from int to string.
To iterate on a dictionary (or any collection or other object that implements IEnumerable), you use essentially the same syntax as in PHP:
foreach (var item in info) {
// Do something with item
}
More info Systems.Collections.Generic.IDictionary is here.

Categories

Resources