Something wrong with passing parameter to FB Api() method - c#

I've the following code that fetches my friends list with some specific fields to be returned.
public ActionResult Test()
{
fbApp = new FacebookApp();
authorizer = new CanvasAuthorizer(fbApp);
authorizer.Perms = requiredAppPermissions;
if (fbApp.Session != null)
{
dynamic friendsFields = new ExpandoObject();
friendsFields.fields = "id,name,location,bio,gender,religion,activities";
JsonObject data = fbApp.Get("/me/friends", friendsFields);
ViewData["friends"] = data["data"] as JsonArray;
return View();
}
}
I'm asking for id,name,location,bio,gender,religion,activities fields, but the result doesn't submit all those fields. Only id,name,gender are returned which makes suspect something is wrong... if i try to get the same data using the browser and passing the fields the result returns all the requested fields:
URL: https://graph.facebook.com/me/friends?fields=id,name,bio,gender,picture,religion,activities&access_token=...
"data": [
{
"id": "data_data_data",
"name": "data_data_data",
"bio": "data_data_data",
"gender": "data_data_data",
"religion": "data_data_data",
"picture": "data_data_data",
"activities": {
"data": [
{
"name": "data_data_data",
"category": "data_data_data",
"id": "data_data_data",
"created_time": "data_data_data"
}
]
}
},
{
"id": "data_data_data",
"name": "data_data_data",
"bio": "data_data_data",
"gender": "data_data_data",
"picture": "data_data_data"
}
]
}
Anyone have any idea what might be wrong here? Can it be the API? I'm using the latest version 4.1.1
TIA!

You have to cast the result of the Get method or just access it dynamically. Here is the corrected code with the authorization fixed as well.
[CanvasAuthorize(Perms="user_friends")]
public ActionResult Test()
{
var fbApp = new FacebookApp();
dynamic friendsFields = new ExpandoObject();
friendsFields.fields = "id,name,location,bio,gender,religion,activities";
dynamic result = fbApp.Get("/me/friends", friendsFields);
var data = result.data as JsonArray;
ViewData["friends"] = data;
return View();
}

Related

Columns not returning correctly when using WIQL Queries from ADO

I am trying to get all Epics from ADO using the below code
string PAT = "sdsd";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", PAT))));
string query = "SELECT [System.Id], [System.WorkItemType], [System.Title], [System.State], [System.AreaPath], [System.IterationPath], [System.TeamProject], [System.WorkItemType] FROM workitems WHERE System.WorkItemType='Epic' ORDER BY [System.ChangedDate] DESC ";
var q = JsonConvert.SerializeObject(new WiqlQuery() { query = query });
using (HttpResponseMessage response =client.PostAsync("https://dev.azure.com/{Org}/_apis/wit/wiql?api-version=6.0",new StringContent(q,Encoding.UTF8,"application/json")).GetAwaiter().GetResult())
{
response.EnsureSuccessStatusCode();
string responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
string k = "";
}
}
Code executes without any trouble. But if I run the above query in ADO query editor, its returning all the columns in the Select statement.
But when I run the same in Code, I am not all getting any of those columns. Instead I am getting below JSON
{
"queryType": "flat",
"queryResultType": "workItem",
"asOf": "2021-07-02T08:30:15.84Z",
"columns": [
{
"referenceName": "System.Id",
"name": "ID",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.Id"
},
{
"referenceName": "System.WorkItemType",
"name": "Work Item Type",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.WorkItemType"
},
{
"referenceName": "System.Title",
"name": "Title",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.Title"
},
{
"referenceName": "System.State",
"name": "State",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.State"
},
{
"referenceName": "System.AreaPath",
"name": "Area Path",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.AreaPath"
},
{
"referenceName": "System.IterationPath",
"name": "Iteration Path",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.IterationPath"
},
{
"referenceName": "System.TeamProject",
"name": "Team Project",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.TeamProject"
},
{
"referenceName": "System.WorkItemType",
"name": "Work Item Type",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.WorkItemType"
}
],
"sortColumns": [
{
"field": {
"referenceName": "System.ChangedDate",
"name": "Changed Date",
"url": "https://dev.azure.com/{organization}/_apis/wit/fields/System.ChangedDate"
},
"descending": true
}
],
"workItems": [
{
"id": 61380,
"url": "https://dev.azure.com/{organization}/_apis/wit/workItems/613810"
},
{
"id": 61834
}
]
}
What could be the reason or how to get all the columns of data we have specified in Select statement
Yes, RUN WIQL returns only the list of ids. Then you can use Get Work Items Batch to get only needed fields:
POST https://dev.azure.com/fabrikam/_apis/wit/workitemsbatch?api-version=6.1-preview.1
BODY:
{
"ids": [
297,
299,
300
],
"fields": [
"System.Id",
"System.Title",
"System.WorkItemType",
"Microsoft.VSTS.Scheduling.RemainingWork"
]
}

Parse nested json and return the values as string[]

Can you help me parse the values in 'realEstateProperties' attribute (ex. serial number and economyType.value). Here is a part of the json file:
{
"Entity1": {
"id": "5f514d20744a1fb",
"realEstateProperties": [
{
"serialNumber": "11",
"cadastralSections": [
{
"id": "5f514dc11a1e3",
"economyType": {
"value": "landRegisterPage.type",
}
}
],
"landRegisterPage": {
"id": "3456",
"landRegisterBook": {
"abbreviation": null
},
"note": "LRP",
"tags": null
},
"propertyTextBlock": null
}
],
"customFields": [],
Here is what I currently have:
public static string[] GetJsonValues(string jsonProperty)
{
testCaseName = "Entity1";
FixtureIncident.Root incObject = new FixtureIncident.Root();
incObject = LoadJSONFile();
JObject incJson = JObject.FromObject(incObject);
var attributes = incJson[testCaseName].ToList<JToken>();
var property = attributes.Find(i => i.ToObject<JProperty>().Name == jsonProperty) as JArray; //returns property=null
string[] Properties = property.ToObject<string[]>();
return Properties;
}
property returns null and I am not sure how to correct it.
I need to save all the realEstateProperties values in a string[].
I found some similar topics but I couldn't adjust my code so I make it works. Thanks in advance for your help.

Unity Facebook SDK, retrieve data from 'apprequests' from API

I am fetching /me/apprequests from Facebook API. It works and I get the data in JSON format.
Thing is that everything is nested, like a dictionary inside a dictionary.
What i tried:
Dictionary<string, object> dict = Facebook.MiniJSON.Json.Deserialize(result.RawResult) as Dictionary<string, object>;
object data;
string request_code = "";
if (dict.TryGetValue("data", out data))
{
var rc = (((Dictionary<string, object>)data)["id"]);
request_code = (string)rc;
}
Debug.Log("request_code=" + request_code);
I think I need to loop the dictionary to get all id's.
I can confirm that if (dict.TryGetValue("data", out data)) does work correctly and get the dictionary of data arrays, but fails here (((Dictionary<string, object>)data)["id"]); with casting error.
Json looks like:
{
"data": [{
"application": {
"category": "Games",
"link": "https:\/\/www.facebook.com\/games\/?app_id=2523532533",
"name": "game name",
"id": "23432423423"
},
"created_time": "2019-02-27T16:01:15+0000",
"from": {
"name": "David boom",
"id": "387923432423089962"
},
"message": "You are invited",
"to": {
"name": "Dusty Spice",
"id": "10234324421033685"
},
"id": "413880842521239_10156578101000000"
},
{
"application": {
"category": "Games",
"link": "https:\/\/www.facebook.com\/games\/?app_id=2523532533",
"name": "game name",
"id": "23432423423"
},
"created_time": "2019-02-27T14:12:41+0000",
"from": {
"name": "David boom2",
"id": "387923432423089962"
},
"message": "You are invited",
"to": {
"name": "Dusty Spice",
"id": "10234324421033685"
},
"id": "316676422209302_10156578101000000"
}],
"paging": {
"cursors": {
"before": "NDEzODgwODQyNTIxMjM5Ojc1OTQzODY4NAZDZD",
"after": "MzE2Njc2NDIyMjA5MzAyOjc1OTQzODY4NAZDZD"
}
}
}
Managed to make it work if it will help someone:
string request_code = "";
if (dict.TryGetValue("data", out data))
{
int dataLength = ((List<object>)data).Count;
for (int i = 0; i < dataLength; i++)
{
var rc = ((List<object>)data)[i];
var rc2 = (((Dictionary<string, object>)rc)["id"]);
request_code = (string)rc2;
Debug.Log("request_code=" + request_code);
}
}

get Specific Id from json file

this is my json file
{
{
"#odata.context": "https://api.onedrive.com/v1.0/$metadata#drives('me')/items('root')/children/$entity",
"createdBy": {
"application": {
"displayName": "Nopbackup",
"id": "4c190e01"
},
"user": {
"displayName": "pallav jha",
"id": "611c19eb038d5aa1"
}
},
"createdDateTime": "2016-05-12T07:25:36.463Z",
"cTag": "adDo2MTFDMTlFQjAzOEQ1QUExITEyNC42MzU5ODYzODk5MTI3MDAwMDA",
"eTag": "aNjExQzE5RUIwMzhENUFBMSExMjQuMw",
"id": "611C19EB038D5AA1!124",
"lastModifiedBy": {
"application": {
"displayName": "Nopbackup",
"id": "4c190e01"
},
"user": {
"displayName": "pallav jha",
"id": "611c19eb038d5aa1"
}
},
"lastModifiedDateTime": "2016-05-12T08:36:31.27Z",
"name": "Nopbackup",
"parentReference": {
"driveId": "611c19eb038d5aa1",
"id": "611C19EB038D5AA1!105",
"path": "/drive/root:"
},
"size": 0,
"webUrl": "https://onedrive.live.com/redir?resid=611C19EB038D5AA1!124",
"fileSystemInfo": {
"createdDateTime": "2016-05-12T07:25:36.463Z",
"lastModifiedDateTime": "2016-05-12T08:36:31.27Z"
},
"folder": {
"childCount": 0
}
}
}
i want to get this "id": "4c190e01" from json
dynamic value = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
string id = Convert.ToString(value.id[0]);
this is my code but i am not getting 4c190e01 id
rewrite your code as following...
dynamic valuePoco = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
string id = Convert.ToString(valuePoco.createdBy.application.id);
You can use the path to the desired property. If you want to select the element with 4c190e01 as id, you can use
string id = value.createdBy.application.id;
or
string id = value.lastModifiedBy.application.id;
depending on your needs.
As it was pointed out, you'd need to fix your JSON first and remove the first { and the last }
First thing first, Your json is invalid.
You've to remove one { from top and } from the bottom and then use the following code:
dynamic jsonObj = JsonConvert.DeserializeObject(result);
string id = jsonObj.createdBy.application.id.ToString();

c# .net - read JSON

I am trying to read an environment variable from a JSON object that looks like this:
{
"staging_env_json": {},
"running_env_json": {},
"system_env_json": {
"EN_VAR_NAME": {
"mysql": [
{
"name": "name-here",
"label": "label-here",
"tags": [
"mysql",
"relational"
],
"plan": "",
"credentials": {
"hostname": "host",
"port": "port",
"name": "name-here",
"username": "username",
"password": "password",
}
}
]
}
}
}
Using C# how would I access the username and password? I have tried this....
envVariable = Environment.GetEnvironmentVariable("EN_VAR_NAME");
var obj = JObject.Parse(envVariable);
var hostname = (string)obj["mysql"]["credentials"]["username"];
But this isn't getting me where.. can anyone please point me in the right direction?
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(envVariable);
var userName = ((dynamic)obj).system_env_json.EN_VAR_NAME.mysql[0].credentials.username
You can parse it as dynamic:
dynamic result = JsonConvert.DeserializeObject<dynamic>(input);
Console.WriteLine(result.system_env_json.EN_VAR_NAME.mysql[0].credentials.username);

Categories

Resources