Pass username and password into json url - c#

The URL Is:
http://reportguru.webdenza.com/vdetect-pro-2/api.php?q={\"svc\":\"auth\",\"params\":{\"username\":\"username\",\"password\":\"passowrd\"}}
The username and password should come from textboxes.Asp.net(c#) code is needed.
After passing the credentials the following json will come.
{ "items":
{ "642163":
{ "id": 642163,
"nm": "AK-21699-11-Lancer-Mohammed Al Noman" },
{ "642169":
{ "id": 642169,
"nm": "AK-21699-11-Lancer-Mohammed Al Noman" } ,
{ "642063":
{ "id": 642063,
"nm": "AK-21699-11-Lancer-Mohammed Al Noman" }
},
"sid": "fdf47003cc1eca9133822ba0025c6aea",
"count": 12,
"p_type": "hst"
}
fdf47003cc1eca9133822ba0025c6aea
All the items should come.I have 642163 like id 100.How get all these values in asp.net(c#).

Use System.Web.Script.Serialization.JavaScriptSerializer and it's Deserialize method to get a strong typed access to the JSON response.
If you don't mind adding new references, you could also have a look at Json.NET

Related

Get Value From JSON File stored in Azure Storage Using C#

I have JSON file in Azure Storage which I am reading using C#. In that JSON file there is anode called SQLViewDifinition and that node I have SQL which I need to fetch.
I have read the file into a string and converted that string in JObject. I have the JSON now but is finding it difficult to read that particular node. Tried with JToken and Jproperty. But could not crack it.
JSON file looks like this:
{
"jsonSchemaSemanticVersion": "1.4.0",
"imports": [
{
"corpusPath": "cdm:/foundations.cdm.json"
},
{
"corpusPath": "localCdm:/foundations.cdm.json"
}
],
"definitions": [
{
"entityName": "METCredManCollectionGroupEntity",
"exhibitsTraits": [
{
"traitReference": "is.CDM.entityVersion",
"arguments": [
{
"name": "versionNumber",
"value": "1.0.0"
}
]
},
{
"traitReference": "has.sqlViewDefinition",
"arguments": [
{
"name": "sqlViewDefinition",
"value": "CREATE VIEW [DBO].[METCREDMANCOLLECTIONGROUPENTITY] AS SELECT T1.COLLECTIONGROUPID AS COLLECTIONGROUPID, T1.DESCRIPTION AS DESCRIPTION, T1.RECID AS CREDMANCOLLECTIONGROUPTABLERECID, T1.DATAAREAID AS CREDMANCOLLECTIONGROUPTABLEDATAAREAID, T1.RECVERSION AS RECVERSION, T1.PARTITION AS PARTITION, T1.RECID AS RECID FROM CREDMANCOLLECTIONGROUPTABLE T1"
}
]
},
{
"traitReference": "has.backingElements",
"arguments": [
{
"name": "backingElements",
"value": "CredManCollectionGroupTable"
}
]
}
],
"hasAttributes": [
{
"name": "CollectionGroupId",
"dataType": "CredManCollectionGroupId",
"isNullable": true,
"displayName": "Collection group",
"maximumLength": 10
},
{
"name": "Description",
"dataType": "Description",
"isNullable": true,
"displayName": "Description",
"maximumLength": 60
},
{
"name": "CredmanCollectionGroupTableRecId",
"dataType": "other",
"isNullable": true,
"displayName": "Record-ID"
},
{
"name": "CredmanCollectionGroupTableDataAreaId",
"dataType": "other",
"isNullable": true,
"displayName": "Company"
}
],
"displayName": "MET Collection groups (Shared)"
},
{
"explanation": "Collection group",
"dataTypeName": "CredManCollectionGroupId",
"extendsDataType": "SysGroup"
},
{
"explanation": "Group",
"dataTypeName": "SysGroup",
"extendsDataType": "string"
},
{
"explanation": "Description",
"dataTypeName": "Description",
"extendsDataType": "string"
}
]
}
I need to find sqlViewDefinition from this file.
So far I can read the JSON in a JSON object. But could not find a way to get the view definition.
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Nancy.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class FindFiles
{
// Main Method with int return type
static int Main(String[] args)
{
Console.WriteLine("Buid SQL");
// for successful execution of code
return X("FILE_NAME");
}
public static int X(string fileName)
{
//connection string
string storageAccount_connectionString = "CONNECTION_STRING";
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccount_connectionString);
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("CONTAINER");
//The specified container does not exist
try
{
//root directory
CloudBlobDirectory dira = container.GetDirectoryReference(string.Empty);
//true for all sub directories else false
var rootDirFolders = dira.ListBlobsSegmentedAsync(true, BlobListingDetails.Metadata, null, null, null, null).Result;
foreach (var blob in rootDirFolders.Results)
{
if (blob.Uri.OriginalString.Contains(fileName, StringComparison.OrdinalIgnoreCase) && blob.Uri.OriginalString.Contains(".cdm.json", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Blob: " + blob.Uri.OriginalString);
if (blob.GetType() == typeof(CloudBlockBlob))
{
CloudBlockBlob b = (CloudBlockBlob)blob;
string jsonText = b.DownloadTextAsync().Result;
Dictionary<string, object> json_Dictionary = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(jsonText.ToString());
JObject json = JObject.Parse(jsonText);
}
}
}
}
catch (Exception e)
{
// Block of code to handle errors
Console.WriteLine("Error", e);
}
return 1;
}
}
As you are using .NET 6 and because the structure is always the same, the easiest way to deserialize is to mimic the structure of the JSON in C# classes. You can then easily deserialize the JSON into objects and access the properties of the objects instead of "brachiating" through dynamic data.
In order to get the classes, you can use Visual Studio's Paste Special function (Edit -> Paste special -> Paste JSON as classes). This generates the classes for you (you can adjust the classes if you don't need parts of them or change the casing of the property names; also you can use attributes to customize the serialization).
Afterwards, it is easy to parse the JSON into an object, e.g. (I've put your sample JSON into the jsonContent variable):
var obj = System.Text.Json.JsonSerializer.Deserialize<Rootobject>(jsonContent);
Because it still is a complex structure, getting to the SQL needs a bit of code:
Console.WriteLine(obj
.definitions[0]
.exhibitsTraits
.Where(x => x.traitReference == "has.sqlViewDefinition")
.First().arguments.Where(x => x.name == "sqlViewDefinition")
.First().value);
Finally, the above code writes the following output:
CREATE VIEW [DBO].[METCREDMANCOLLECTIONGROUPENTITY] AS SELECT T1.COLLECTIONGROUPID AS COLLECTIONGROUPID, T1.DESCRIPTION AS DESCRIPTION, T1.RECID AS CREDMANCOLLECTIONGROUPTABLERECID, T1.DATAAREAID AS CREDMANCOLLECTIONGROUPTABLEDATAAREAID, T1.RECVERSION AS RECVERSION, T1.PARTITION AS PARTITION, T1.RECID AS RECID FROM CREDMANCOLLECTIONGROUPTABLE T1
You can use this documentation to get familiar with JSON handling in .NET 6.

Fetch Value from Json without DeserializeObject C#

Following Json is return from API call.
{
"version": "dddf2222",
"data": {
"account": {
"username": "34343",
},
},
"error": 0
}
I want to fetch value of username without DeserializeObject.
dynamic stuff = JsonConvert.DeserializeObject(myJson);
Console.WriteLine(stuff.data.account.username);
using using Newtonsoft.Json.Linq
dynamic stuff = JObject.Parse(myJson);
Console.WriteLine(stuff.data.account.username);

Format JSON with Google protobuf

With this code:
var button = Value.ForStruct(new Struct{
Fields={
["type"] = Value.ForString("postback"),
["title"] = Value.ForString("Call Representative"),
["payload"] = Value.ForString("+15105551234"),
}
});
var inPayload = Value.ForStruct(new Struct{
Fields ={
["buttons"] = Value.ForList(button),
["text"] = Value.ForString("try the postback"),
["template_type"] = Value.ForString("button"),
}
});
var attachment = Value.ForStruct(new Struct{
Fields ={
["payload"] = inPayload,
["type"] = Value.ForString("template"),
}
});
var msg = Value.ForStruct(new Struct{
Fields ={
["attachment"] = attachment,
});
Payload = new Struct{
Fields ={
["facebook"] = msg
}
I was able to create the following json:
"payload": {
"facebook": {"attachment": {
"payload": {
"buttons": [ {
"type": "postback",
"title": "Call Representative",
"payload": "+15105551234"
}],
"text": "try the postback",
"template_type": "button"
},
"type": "template"
}}
Now I need to create the following other format but I dont find how to do it:
"payload": {
"message": "Yes I did it"
"platform": "kommunicate",
"attachment": {
"payload": {
"buttons": [ {
"type": "postback",
"title": "Call Representative",
"payload": "+15105551234"
}],
"text": "try the postback",
"template_type": "button"
},
"type": "template"
}
I really dont find how to eliminate the first "facebook": { element and leave only:
{
"message": "Yes I did it",
"platform": "kommunicate",
"attachment":
And include message and platform at the same level. Here is the complete json I will like to generate:
"payload": {
"platform": "kommunicate",
"message": "Yes I did it",
"attachment": {
"payload": {
"buttons": [ {
"type": "postback",
"title": "Call Representative",
"payload": "+15105551234"
}],
"text": "try the postbackggggggg",
"template_type": "button"
},
"type": "template"
}
If you want to take an object and convert it to json I would recommend taking a look at Newtonsoft Json.Net library. They have plenty of examples that might help you. There is also protobuf.net library for serializing to protobuf instead of json.
Both libraries are used in similar ways, you create a class with appropriate properties and set the values you want. You will need multiple classes for nested types as in your example. Protobuf requires you to annotate the properties with attributes, while this is optional for json.net. You then send the object to the serialization library and get a string or binary data representing your object. This kind of object is often called a Data Transfer Object (DTO), since the only purpose it has is to aid in serialization or/and transfering the data to another system.

How to know the interactions happened with the feed in stream?

My query goes like this: If I have a feedItem (an image posted on facebook), how can I verify that I have liked it or not? Can I verify all the interactions which I have done to the feedItem or the interactions other people have done to it (like, dislike, pin, share)? Is there any way in getstream.io to retrieve these interactions?
Thanks in advance...
Graph API provides all functions you need. Here are some examples:
Read shares[it's a field of an object]: https://developers.facebook.com/docs/graph-api/reference/v3.1/post#read
Read Shared posts: https://developers.facebook.com/docs/graph-api/reference/v3.1/object/sharedposts
read likes:
https://developers.facebook.com/docs/graph-api/reference/v3.1/object/likes#read
/likes returns only the profile for the current user if read with a
user access token:
Album, Photo, Post, Video
all returns are JSON, which you can directly Deserialize Anonymous Type without using stream, for example, likes:
{
"likes": {
"data": [
{
"name": "Bill the Cat",
"id": "155111347875779",
"created_time": "2017-06-18T18:21:04+0000"
},
{
"name": "Calvin and Hobbes",
"id": "257573197608192",
"created_time": "2017-06-18T18:21:02+0000"
},
{
"name": "Berkeley Breathed's Bloom County",
"id": "108793262484769",
"created_time": "2017-06-18T18:20:58+0000"
}
],
"paging": {
"cursors": {
"before": "Nzc0Njg0MTQ3OAZDZD",
"after": "NTcxODc1ODk2NgZDZD"
},
"next": "https://graph.facebook.com/vX.X/me/likes?access_token=user-access-token&pretty=0&summary=true&limit=25&after=NTcxODc1ODk2NgZDZD"
},
"summary": {
"total_count": 136
}
},
"id": "user-id"
}

Retrieving "images" from a JSON string retrived from Instagram API

Using C# and Visual Studio 2010 (Windows Form Project), InstaSharp and Newtonsoft.Json libraries.
I want to get the image url from the JSON string returned to me by the Endpoint Instagram API when I request for a particular hashtag.
I can so far retrive the JSON string.
I am trying to use Newtonsoft.Json to deserialize the object using the examples, but I probably dont understand the JSON string representation of the object properly.
Below is a simplified sample response I get from the api call tags/tag-name/media/recent from their documentation. source here
{
"data": [{
"type": "image",
"filter": "Earlybird",
"tags": ["snow"],
"comments": {
}
"caption": {
},
"likes": {
},
"created_time": "1296703536",
"images": {
"low_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_7.jpg",
"width": 612,
"height": 612
}
},
"id": "22699663",
"location": null
},
...
]
}
I want to get specifically the standard_resolution in the images part.
This is the revelevant code that I currently have.
//Create the Client Configuration object using Instasharp
var config = new InstaSharp.Endpoints.Tags.Unauthenticated(config);
//Get the recent pictures of a particular hashtag (tagName)
var pictures = config.Recent(tagName);
//Deserialize the object to get the "images" part
var pictureResultObject = JsonConvert.DeserializeObject<dynamic>(pictureResult.Json);
consoleTextBox.Text = pictureResult.Json;
var imageUrl = pictureResultObject.Data.Images;
Console.WriteLine(imageUrl);
I get the error: Additional information: Cannot perform runtime binding on a null reference
so imageUrl is indeed null when I debug, hence indicating I am not accessing it the right way.
Anyone can explain to me how to access different parts of this JSON String using Newtonsoft.Json?
Using Newtonsoft.Json
dynamic dyn = JsonConvert.DeserializeObject(json);
foreach (var data in dyn.data)
{
Console.WriteLine("{0} - {1}",
data.filter,
data.images.standard_resolution.url);
}
I wrote a plugin for .net which takes care of deserializing the json string and returning a data table. it is still in development but see if it helps. Instagram.NET on Github

Categories