Working with dynamic data with Azure DocumentDB and MVC5 - c#

I am working with Azure DocumentDB using dynamic data types, i.e., I do not predefine any classes for the data I'm working with. I'm querying my DocumentDb database/collection using calls of the form:
client.CreateDocumentQuery<dynamic>(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), query).ToArray();
The objects that get returned seem to be of type Micrsoft.Azure.Documents.QueryResult.
When the query is included as part of an MVC action, when the results are passed back to the client they become empty objects.
I was expecting to get 'dynamic' data back which would serialize just fine as part of the JsonResponse.
What do I need to do to convert each Micrsoft.Azure.Documents.QueryResult to dynamic?

According to your description, I tried to build my MVC Web Application and I could encounter the same issue as you mentioned.
I was expecting to get 'dynamic' data back which would serialize just fine as part of the JsonResponse.
You could leverage the following code:
var results=client.CreateDocumentQuery<dynamic>(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), query).ToArray();
return Content(JsonConvert.SerializeObject(results), "application/json");
Result

Related

Json object in post not recognized as object in web api

I have an angular client and want to execute a get request to my web api backend to get a list of items from the underlying Dapper Db Wrapper. Dapper allows me to pass in parameters as an anonymous object which would in csharp look like this:
connection.GetList<T>(new {myParam1:"a", myParam2: true});
What I want to achieve is, to create this parameter object in my angular frontend and pass it in a post request to the server which would then pass it on to the GetList function. The problem here is that the web api does not deserialize it as an (anonymous) object, but rather and IEnumerable of JTokens?
My web api signature is this:
public async Task<IHttpActionResult> MyFunction([FromBody]dynamic whereCond)
I have also tried to pass the object as string wrapped in an outer object like so (angular client):
this.migController.MigrationGetMigrationReports({whereCond: JSON.stringify({NotMigrated: true, MissingTargetFiles: 0})})
and then on the server I manually deserialize it as JObject:
string obj = whereCond.whereCond;
dynamic pObj = JObject.Parse(obj);
But this results in the exact same result: pObj is an IEnumerable and therefore I get an error message from the GetList call:
An enumerable sequence of parameters (arrays, lists, etc) is not allowed in this context
can anybody help?
The answer to my question turned out rather simple:
dynamic pObj = JObject.Parse(obj).ToObject<ExpandoObject>();
I had to cast it as ExpandoObject not just dynamic.
#Tsahi: this is not a design problem. My intention was to provide the server with parameters (filter) which is a quite common task for a client to reduce the dataset to be transferred. We could debate a standard way how to provide these parameters, however. In my special case the most practical way is the anonymous object.

How to pass key values pairs to HttpGet in ASP.NET Core WebApi?

I am creating a WebApi and I need to take a key value pairs for my GET endpoint. I found some examples of using dictionary in POST method bus this seems not to work with GET
So far I tried this:
[HttpGet]
public IActionResult Get([FromQuery] Dictionary<string, string> myVar)
{
}
I am using swagger to test the API and if I pass {"key":"value"} I am getting my dictionary with a single pair and value is the entire object I pass in. ({[myVar, {"key":"value"}]})
What is the correct way to pass multiple key value pairs to the WebApi for GET method?
EDIT: The underlying issue was that I was using swagger (swashbuckle) to test my endpoint. And at the moment of this question it doesn't support dynamic query parameters Issue on github. It should support it once OpenApi v3 support is added to swashbucle Issue on github.
You should be able to call the endpoint using the following structure and have the values automatically bound via Web API's built-in binder.
https://example.com/api/values?1=john&2=jane
1 and 2=keys for respective entries in dictionaries.
john and jane=values

Azure Data Factory .NET Integration: Some Properties Are Null

tl;dr: The .NET integration is returning partial objects, with some properties read as null. How can I get the full object with all properties?
I'm currently using C#.NET to read and modify Data Factory objects, using Microsoft.Azure.Management.DataFactories.
I can apparently successfully get most of my object data with a call like this:
var datasets = client.Datasets.List(resourceGroupName, dataFactoryName).Datasets;
While this gives me all of my Dataset objects, in all of the datasets, certain properties are simply left out. Here are some screenshots showing this:
This is what the Dataset is defined as, shown in Azure:
This is what I'm given by programmatically retrieving the Dataset object as JSON:
Similarly, here's the object as-is in memory at a breakpoint in my application:
As you can see, it's missing virtually all of the "Properties", with values being replaced with null.
How can I get the full, unadulterated object in my C# application?
Listing datasets will give you a "summary" of each dataset; as you observed, this means that certain details are not returned (e.g. typeProperties and structure).
After using the List method to get all datasets in the data factory, you can use the Microsoft.Azure.Management.DataFactories.DatasetsOperationExtensions.Get() method to get the full definition of each. Of course, you could simply call Get() if you already know the name of the dataset you are looking for.

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>();

how to get all the types of one index by using Nest(Elasticsearch) in C#

if use original api /_mapping, I can get all he information of all types for each index.
but when I use Nest, I can not see the way to do the same thing like /_mapping does. Nest has getMapping, but you must give a mapped type(object).
and I still not find any way to pass the /_mapping web api through Nest.
How to get the list of types of each indexes in Nest?
I found way to do this with Nest.
Nest actually provider a ElasticSearchClient within the object itself. the field call Raw actually provide all the API from ElasticSearchClient. and all the APIs mapped to the ElasticSearch REST web api, and give the JSON result directly.
to answer this question. the following code can be used:
var nestClient = new ElasticClient(new ConnectionSettings(new Uri("http://localhost:9200")));
var Response = nestClient.Raw.IndicesGetMapping();
var JSONResult=Response.Result;
JSONResult is String. Later on, this can be parsed by JObject.Parse(JSONResult); to get the JObject and processed further in C#.
This answer is only working for NEST 0.12, NEST 1.0 change the API completely

Categories

Resources