C#: Map API results to Class Properties - c#

I'm trying to build a program in which I consume an API through a client that a company has made available for its software.
Here's a link to it.
Though it does make it easier for one to establish a connection and make a call through its embedded methods, I'm having a difficult time manipulating the data once I receive it.
[Note: I know it's sort of meaningless to provide y'all with the background of the client and how I'm making the call, but I would think it'd be hard for one to get a glimpse of what's going on if I'm not even providing how the connection is happening behind the client or how the database looks.]
Previously, I tried manipulating the data directly after making the call like this (link below), but I realized this is too difficult for me since I'm still a noob at C#, and it's been hard to mess with the results (object) as a dynamic[] value.
Link
Therefore, I believe it'd be best if I pursue the route of getting the data as an object, serialize it, turn it to (json), and map it to properties. I believe once I do this it should be easier to manipulate the data because I'd have an easier time turning the data into single values, lists, etc. However, I'm having a difficult time connecting the dots at this point of the code.
This is what I have so far..
I'm only interested in the EntryID, NameFirst, and NameLast of the results, but further along the way I do see myself utilizing the info from the other fields of this table and others. If someone could help me make the connection from the results to these properties, I would very much appreciate it. This would be a huge step in the application I'm trying to build using this API data.
Thanks in advance!
Class of Properties Link
JsonData Processor Link
JSON Results from Call Link
using System;
using [Custom]Api;
using Newtonsoft.Json;
namespace testing2
{
public class Program
{
public static void Main(string[] args)
{
[CustomApi]Client connection = new [CustomApi]Client("BaseURL",
"Username", "Password");
var value =
connection.Select("Entry",Criteria.Equals("NameLast","Rincon Recio"));
string results = JsonConvert.SerializeObject(value);
///not sure if making results as string is the right call to begin
this
//[Syntax where I tell results to match properties of Class 1]
//[Create list of EntryID, NameFirst, NameLast]
//[Display list in listbox]
Console.WriteLine(results);
Console.ReadLine();
}
}
}

No, JsonConvert.SerializeObject(value) shouldn't make a difference.
Try Deserialising values to array of Class1.
Like so
var realResult = JsonConvert.DeserializeObject<Class1[]>(values);
Source

Related

Whats the Good Practice of Possible Linq Result Data Storage to be used Globally within Solution

How do i do this the proper way legit code. like if it do a linq query within using and the result is i want it to use on another different bracket of using another call of linq query
if i store it i could declare a pre define var neither can i use a class constructor method.
what is the proper way to do this that i may able to use it on maybe different modules or different function / method without again doing the same call over in every method.
Hope i made it clear what i want.
var globalstorage;
using (Si360DbContext _si360DbContext = new Si360DbContext())
{
var selectedItems = _si360DbContext.SaleDumpDetails
.Where(sd => sd.SaleID == saleid)
.Select(i => i.SaleItemID).ToList();
//Store data..
globalstorage = selectedItems;
}
// able to reuse it else where having the same data stored on it.
globalstorage
It depends... as always...
If you're working on a web project, some mechanism that allows you to cache would be approprate. A MemoryCache for example could be a good and fast solution. However... If the amount of data grows, or you run multiple instances of the same website for example, you may need a distributed cache system like Redis.
For different types of apps, console or maybe Windows desktop you could just create a public static variable and you're good to go. So again, it totally depends on the needs of your solution.

What is the best way to serialize, return and consume complex C# object from an MVC3 app?

Here's my situation: I have an MVC3 app that has some very complex C# objects, and those get rendered to a views in this application. However, I have a new requirement: a console application (that I am also writing) will run under a scheduler, and it needs to pull these objects from this MVC3 app, and then do something else with these complex objects.
Since I have control over both apps, I can share a library of the complex objects between them. All of these objects are marked [Serializable]. However, I cannot figure out an easy way to serialize these objects and send them from the MVC3 app to the Console app.
I tried simple JavaScriptSerializer and using the HttpClient to read the string, then deserialize it on the console-app end of things, but unfortunately it doesn't deserialize the data correctly. Everything is null. I can inspect the string on a breakpoint when it arrives at the console app, and all the data is there, in the string, but it just doesn't get de-serialized correctly.
Is there an easier way to do this? I don't care what the serialization method is. The data doesn't have to be passed as JSON and no other application but mine is going to consume these objects. But so far I can't figure out the easiest way to produce/consume these objects.
I know I can go down the whole "create a web service contract" and use data annotations route, but I was hoping there was an easier, less time-consuming way of doing it.
Using Json.NET:
Server-Side
string serializedObject = JsonConvert.SerializeObject(yourComplexObject);
// Send the string to the client...
Client-Side
In the client, you don't even have to know the deserialized object's type, you can take advantage of anonymous objects and dynamic:
string serializedObject = // ... Fetch from server
dynamic complexObject = JsonConvert.DeserializeObject(serializedObject);
// ...
string id = complexObject.UserId;
P.S.: Please note that the object's methods or state is not going to get serialized, only the public properties are.
Can your action just return your object? If so, your client code would look something like (using HttpClient)
var result = client.GetAsync(url).Result;
var myObj = await result.Content.ReadAsAsync<T>();

Url Encoding an array

This might seem dirty but it's for documentation purposes I swear!
I am accessing my services using GETs in my documentation so people can try things out without needing to get too complicated.
Appending x-http-method-override=POST to the URL forces the server to take a GET as a POST
This is all good except when I need to POST an array of objects. This would be simple in a standard POST but today I have a new bread of nightmare.
The expected POST looks like:
{"name":"String","slug":"String","start":"String","end":"String","id":"String","artists":[{"id":"String","name":"String","slug":"String"}],"locationId":"String"}
As you can see there is an array of artists up in here.
I have tried to do the following:
model/listing?start=10:10&end=12:30&artists[0].name=wayne&artists[0].id=artists-289&locationid=locations-641&x-http-method-override=POST
But to no avail.
How can I get an array of objects into a URL so that service stack will be happy with it?!
I appreciate this is not the done thing but it's making explaining my end points infinitely easier with clickable example URLs
You can use JSV to encode complex objects in the URL. This should work for your DTO:
model/listing?name=wayne&artists=[{id:artists-289,name:sample1},{id:artists-290,name:sample2}]&locationId=locations-641
You can programmatically create JSV from an arbitrary object using the ToJsv extension method in ServiceStack.Text.

c# static Data Dictionary lingering when source data changes - even across IIS users

I have an online store and the software is highly customized but not completely ours. We sell tours and some of them have reservations so I added a calendar to let them pick the date/time they want. Originally each cal_SelectionChanged() call was looking stuff up from the store database and that was, of course, horribly slow. I wanted to use a Data Dictionary to get the information once and use it whenever needed.
I have this class:
public partial class ConLib_Custom_BuyTourProductDialog : System.Web.UI.UserControl
and this declared inside that class.
static Dictionary<string, string> CustomFieldDict = new Dictionary<string, string>();
I also have a function to load all the bits from a database that I'll need on my page. My plan was to call this on Page_Load() and just access the info when needed.
protected void LoadCustomFieldDictionary()
{
string _sku = _Product.Sku.Trim().ToLower();
if (CustomFieldDict.ContainsKey("Sku"))
{
// is the dictionary entry for *this* sku?
if (CustomFieldDict["Sku"] == _sku)
{
return; // already have this one.
}
}
CustomFieldDict["Sku"] = _sku;
CustomFieldDict["EventId"] = TTAUtils.GetCustomFieldValue(_Product, "EventId");
CustomFieldDict["ResEventTypeId"] = TTAUtils.GetCustomFieldValue(_Product, "ResEventTypeId");
etc.
}
Then my boss loaded a page - ok, everything was fine - and changed one of the bits of data in the database to point to a different, wrong, ResEventTypeId. Reload the page and it has the new data. He changed it back to the original and it was "stuck" on the wrong information. I loaded a browser on my iPad and went there and it fed me the wrong info as well.
It seems that the server is caching that DataDictionary and even if we change the database all visitors, even in other sessions, get this cached wrong info.
Do you think this assessment is right?
What's the proper way to do this so that a visitor changing dates gets some kind of cached lookup speed and yet another browser gets a fresh set from the database?
How do I make it "forget" what it thinks it knows and accept the new info until I fix it? Reset IIS?
Thankfully this is on a dev server and not my live store!
Thanks for your help. I've learned a lot about C# and .NET but it's shade-tree-mechanic type stuff and I lack the formal training that is out there and would really help in situations like these. Any help is appreciated!
For anyone coming by at a later time:
What Jonesy said is very true - statics are scary. I found out from one site (link to a link from his link) that statics like this are sticky to the Application Pool level so any other browser would get the "wrong" information.
For my situation I decided to use ViewState to store the info since it was small and my current V.S. isn't very large already. Beware doing this for large amounts of data but in my case it was the best.

When do I need a datacontract in WCF and would it be better to use a simple type?

I am having some trouble designing my WCF service. Bassically I need the service to recieve an XML document. The xml maps to a class that was generated from xsd.exe. I was originally just had this:
public void AddDocument(string xmlString)
Then I would deserialize the xml into the generated class. I was told this is a bad idea because I am doing extra work since wcf will do the serialization for me if I just use the document class as a parameter like this:
public void AddDocument(MyGeneratedClass document)
I'm new to WCF but if I do it this way I thought I would have to create a datacontract for MyGeneratedClass. The generated class is 20,000+ lines so this would take forever.
Do I need a DataContract? Anyway I think I am missing something so I hope this makes sense and if anyone can point me in the right direction I would greatly appreciate it. Thanks!
I would use simple types if your method only requires one or two parameters, and will return only a single simple type value.
As a general rule:
If you need to pass in more than just a few (less than 5) simple types - use some kind of a Request object, otherwise your call gets unwieldy.
If you need to return more than one single simple type value, use a Response object to bundle up those values.
I would try to avoid sending and receiving XML and parse it - try to send back and forth real well structured (data) objects - much easier to deal with and type-safe and all !

Categories

Resources