Read Data From MongoDB When Document Structure Is Different - c#

We are currently working on a .NET Core application and we are using MongoDB for it. I am using .NET Driver to access the data. All the data we are saving in a collection has different types of data structure.
For example, it has first document which has Name, Phone and a Payload which has embedded document in which we are saving address:
{
"Name": "TestName",
"Phone": "23846787",
"Payload": {
"Address": "TestAddress",
"City": "TestCity"
},
"Active": true
}
Then in the same collection we have another document which has Name, Phone and a Payload which is completely different from first one:
{
"Name": "TestName2",
"Phone": "54568765",
"Payload": {
"Weight": "70",
"Age": "45",
"Gender": "Female"
}
}
Now when we use .NET driver to get both of these records, we get an error because it cannot cast the embedded document into an object (as it doesnt know about the object). We need to tell it, which type of object is the embedded document. But we dont want to do it because we have several types of payload we want to save. I tried using discriminator "_t" but it didn't help.
Can someone please suggest how we can read the data when we have different elements in the document and also has embedded documents?

You can define a convention indicating that the client must ignore the elements that it is unable to map:
var conventionPack = new ConventionPack
{
new IgnoreExtraElementsConvention(true)
};
ConventionRegistry.Register("conventions", conventionPack, _ => true);
var client = new MongoClient(options)...

Related

Parsing JSON Using Newtonsoft.Json Without Knowing the Structure

I'm working on a project that involves automating API calls using a Swagger Definition. I download the swagger.json file. The structure of the JSON Object I need to parse is not consistent. When parsing paths, there are a list of objects, then within that they have the methods that can be used for that specific path. I can retrieve just the path using various string methods but my question was, is there a good way to parse json if the JSON is structured in such a way that it does not have a firm key? Here is an example of what I mean:
{"/user": {
"post": {
"tags": [
"user"
],
"summary": "Create user",
"description": "This can only be done by the logged in user.",
"operationId": "createUser",
"consumes": [
"application/json"
],
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "Created user object",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
}
If I wanted to just parse that path and retrieve the method object how could I go about that considering sometimes the object will be "post" or sometimes it will be "get", "put", etc depending on what is allowable for the path.
JObject jsonResp = swaggerDownload();
JObject paths = (JObject)jsonResp["paths"];
foreach (var i in paths)
{
string pathToString = i.ToString();
var shaveSomethings = pathToString.Substring(1, something.Length - 2);
var pathAndJson = shaveSomethings.Split(new[] { ',' }, 2);
string correctJsonStructure = "{\"" + pathAndJson[0] + "\":" + pathAndJson[1] + "}";
JObject bd = JObject.Parse(correctJsonStructure);
//dynamic pathsTest = JsonConvert.DeserializeObject<dynamic>(correctJsonStructure);
//JObject result = JsonConvert.DeserializeObject<JObject>(correctJsonStructure);
//Console.WriteLine(bd["/user"]);
}
The swagger.json file should have full definition of each entity that endpoints return. You can follow How to create Rest API client to get a working client.
I've dealt with an API where responses didn't always match the definition. I saved all responses to a store/log first and then would try to de-serialize JSON. In case of an exception I would go back to store/log and see what was different and update my code to accommodate for the change. After few iterations there were no new changes and the ordeal was over.
Hope that helps.

Can you send a dynamic template to a list, using only list id?

According to the SendGrid docs, it seems like I can send a template to a list by inputting the template ID and list ID into the singlesend call. However when I call this method with those JSON fields, I get an error.
JSON:
{"sender_id":779461,"filter":{"list_ids":["572d0ae8-c665-4265-8e90-28fda56d9409"],"send_to_all":"false"},"template_id":"d-2b8c55e6e0a6463ab096d2e146d77c2c"}
Error: {
"errors": [
{
"field": "",
"message": "json could not be unmarshalled"
}
]
}
I've been trying to get the correct JSON format for a while now, with no luck due to this non-descriptive error. I am also using the C# library for .NET and I cannot find any methods to set a list id to the message. The SendGrid support portal is broken so I cannot reach out to them.
try your json like this send_to_all is not of type string but boolean:
{
"sender_id": 779461,
"filter": {
"list_ids": [
"572d0ae8-c665-4265-8e90-28fda56d9409"
],
"send_to_all": false
},
"template_id": "REAL UUID"
}

Post image into list sharepoint with Microsoft Graph

I am working on MS Sharepoint with Microsoft Graph API. I call MS Graph API with .Net Core v2.1.
I want to do a POST request on a Sharepoint List where one of the column is an image column, but I can't find documentations about how to do that... Does anyone know more about how to do it please?
Update:
I saw this post and I changed my json :
{
"fields": {
"Title": "Test",
"Photo": {
"Url": "https://myurl/picture.jpg",
"Description":"This is my picture"
}
}
}
But I have this error message :
{
"error": {
"code": "-1, Microsoft.SharePoint.Client.InvalidClientQueryException",
"message": "A value without a type name was found and no expected type is available. When the model is specified, each value in the payload must have a type which can be either specified in the payload, explicitly by the caller or implicitly inferred from the parent value.",
"innerError": {
"request-id": "34773f4f-131f-4249-8a03-b8a820ba4a6b",
"date": "2019-05-16T13:26:17"
}
}
}
It seems that it expects the Photo's value to be a PrimitiveValue and not an object...
May be this should help you.
POST
https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items
Assuming all your images are already uploaded in your site assets folder. Added the below JSON for the image column with site asset image URL id
POST https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items
Content-Type: application/json
{
"fields": {
"Title": "Widget",
"Color": "Purple",
"Weight": 32,
"image": "/assets/image5.png"
}
}
reference: https://learn.microsoft.com/en-us/graph/api/listitem-create?view=graph-rest-1.0&tabs=javascript
Hope it helps

How to manage Facebook api response data in C# asp.net?

How to convert facebook api response in user readable HTML format?
I call graph api
https://graph.facebook.com/me/feed?access_token=<token>
below is my response data from API.
{
"data": [
{
"id": "100000626589435_240877109276507",
"from": {
"name": "Abhi Patel",
"id": "100000626589435"
},
"type": "status",
"created_time": "2011-08-02T10:36:17+0000",
"updated_time": "2011-08-02T10:36:17+0000"
},
{
"id": "100000626589435_240760105954874",
"from": {
"name": "Abhi Patel",
"id": "100000626589435"
},
"type": "status",
"created_time": "2011-08-02T03:02:21+0000",
"updated_time": "2011-08-02T03:02:21+0000"
},
{
"id": "100000626589435_223775454320006",
"from": {
"name": "Abhi Patel",
"id": "100000626589435"
},
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/274314_100000898272591_5481895_q.jpg",
"link": "http://www.facebook.com/?ref=nf_fr",
"icon": "http://static.ak.fbcdn.net/images/icons/?8:",
"type": "link",
"created_time": "2011-06-28T18:56:44+0000",
"updated_time": "2011-06-28T18:56:44+0000"
}
],
"paging": {
"previous": "<previous link>",
"next": "<next link>"
}
}
also want paging in facebook response data,
I want 20 records from facebook api response. How to manage this things..
Facebook returns raw JSON data. There are no style elements to it. It's up to you to present the data returned in the format you choose. Imagine if Facebook returned HTML and style elements. That wouldn't work very well for desktop applications or mobile devices. Instead, they just give you the raw data, and you design the HTML elements, or the WPF Views, or whatever to show the data you want to show.
By returning the raw data, you can also store it locally in a database for your own queries, or your own applications purposes.
Edited to add: You can parse out the objects by accessing the JSON elements directly, or you can deserialize the result to C# objects.
Console.WriteLine(response.data[0].from.name);
As for paging, you need to parse out the Paging elements. The Facebook C# SDK returns dynamic objects, so you can do something like
string next = response.paging.next;
string prev = response.paging.prev;
And then just make a request to each URL to fetch the data you want.
Use JSON.net and convert into the XML then it would be easy to manage for you.

YouTube API Comments Feed

I am attempting to get the Comments Feed from a video entry using the YouTube API for .NET. I am working on a program in WPF and C#, but can't seem for the life of me to figure out how to retrieve this feed.
I tried looking at the YouTube API Developer's Guide, but it seems to be missing some information about Comment Feeds (near the bottom of the page).
This has changed in version 3 of the YouTube API. There is a new endpoint called commentThreads/list which allows you to return a thread of comments for a resource.
If you want to return a list of comments on a video resource, set up a GET request with part=id,snippet and videoId=[VIDEO_ID]. I'll be using https://www.youtube.com/watch?v=HwNIDcwfRLY as an example:
HTTP GET https://www.googleapis.com/youtube/v3/commentThreads?part=id%2Csnippet&videoId=HwNIDcwfRLY&key={YOUR_API_KEY}
Let's use the first comment returned as an example:
{
"kind": "youtube#commentThread",
"etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/jhK_kJqnNF8_fiRI_o7w6ehubv8\"",
"id": "z120sfshyxzewt1nx23sevyr1vu1jd2pr04",
"snippet": {
"videoId": "HwNIDcwfRLY",
"topLevelComment": {
"kind": "youtube#comment",
"etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/h903NemnXx-8Hfe6lRIYCFERSe4\"",
"id": "z120sfshyxzewt1nx23sevyr1vu1jd2pr04",
"snippet": {
"authorDisplayName": "mach-a-chine seahawksgoonie",
"authorProfileImageUrl": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
"authorChannelUrl": "http://www.youtube.com/channel/UCBmJ0sw7plIZHLvhfz7oo_w",
"authorChannelId": {
"value": "UCBmJ0sw7plIZHLvhfz7oo_w"
},
"videoId": "HwNIDcwfRLY",
"textDisplay": "",
"authorGoogleplusProfileUrl": "https://plus.google.com/102274783439566633837",
"canRate": true,
"viewerRating": "none",
"likeCount": 0,
"publishedAt": "2016-02-05T03:42:35.158Z",
"updatedAt": "2016-02-05T03:42:35.158Z"
}
},
"canReply": true,
"totalReplyCount": 0,
"isPublic": true
}
}
Note that the comment isn't actually in this topLevelComment object. textDisplay returns the empty string, which is a known issue with the YouTube API. We need to make an additional request to commentThreads/list with id=[COMMENT_ID], where [COMMENT_ID] is topLevelComment.id:
HTTP GET https://www.googleapis.com/youtube/v3/commentThreads?part=id%2Csnippet&id=z120sfshyxzewt1nx23sevyr1vu1jd2pr04&key={YOUR_API_KEY}
The resulting response's snippet dictionary will have the user's comment as the value for the textDisplay key:
"snippet": {
"authorDisplayName": "mach-a-chine seahawksgoonie",
"authorProfileImageUrl": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
"authorChannelUrl": "http://www.youtube.com/channel/UCBmJ0sw7plIZHLvhfz7oo_w",
"authorChannelId": {
"value": "UCBmJ0sw7plIZHLvhfz7oo_w"
},
"videoId": "HwNIDcwfRLY",
"textDisplay": "my next ring tone! yeah boy!\ufeff",
"authorGoogleplusProfileUrl": "https://plus.google.com/102274783439566633837",
"canRate": true,
"viewerRating": "none",
"likeCount": 0,
"publishedAt": "2016-02-05T03:42:35.158Z",
"updatedAt": "2016-02-05T03:42:35.158Z"
}
}
The comment is: "my next ring tone! yeah boy!"
Note that you can also pass in a list of up to 50 comma-separated id or videoId strings of comment objects to retrieve per API call.
See the Retrieve comments for a video guide for additional information and sample code.
YouTubeRequest request = ... // Your request object
Video v = ... // Your video object
Feed<Comment> comments = request.GetComments(v);
comments.entries will contain all the comments for the video v as Comment objects, so you don't need to mess with the feed at all.

Categories

Resources