Rest Sharp Patch Request - c#

I'm very new still to Rest Sharp and Postman but I'm trying to make a "Update" to an existing user. Here is my code but I know its wrong. Does anyone have samples on how to perform a "replace" operation in Rest Sharp?
string url = _EndPoint + "?_action = patch & _queryId =for-userName & uid =" + obj.userName.ToString();
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
string username = "openidm-admin";
string password = "openidm-admin";
string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password));
string Update = BuildUpdate();
//if (Update != null)
//{
request.AddHeader("Authorization", "Basic " + svcCredentials);
request.AddHeader("content-type", "application/json");
//request.AddParameter("application/json", "[\n {\n \"operation\": \"replace\",\n \"field\": \"/userName\",\n \"value\": \"testuser4#aha.org\"\n },\n {\n \"operation\": \"replace\",\n \"field\": \"/mail\",\n \"value\": \"testuser4#aha.org\"\n }\n]", ParameterType.RequestBody);
request.AddBody({ "operation": "replace", "field": "/userName", "value": "testuser4#aha.org"}, { "operation": "replace", "field": "/mail", "value": "testuser4#aha.org"});
IRestResponse response = client.Execute(request);
Postman says it should be something like this:
[
{
"operation": "replace",
"field": "/userName",
"value": "testuser4#aha.org"
},
{
"operation": "replace",
"field": "/mail",
"value": "testuser4#aha.org"
}
]
I would prefer to write it that way but I have no idea how. The other code suggested I make a string. I can write it out via string but Id prefer to write it out in the body if I can or possible. Thanks in advance
Edit:
Here is my class:
public class IdentityDetails
{
//public const string type = "user";
//public const string realm = "dc=aha,dc=org";
public string userName { get; set; }
public string mail { get; set; }
public string givenName { get; set; }
public string sn { get; set; }
public string accountStatus { get; set; }
public string avectraId { get; set; }
public string AHApw { get; set; }
public string password { get; set; }
public string ahaBirthYear { get; set; }
public string city { get; set; }
public string ahaGender { get; set; }
public string ahaJobTitle { get; set; }
public string ahaLeadScore { get; set; }
public string stateProvince { get; set; }
public string orgId { get; set; }
public string[] ahaMemberGroup { get; set; }
public string[] ahaMemberType { get; set; }
public string regMethod { get; set; }
//public string[] ahaDrupalPermission { get; set; }
}
I think what I need to do though as well will be pass in the current field and value, and pass in the new value for the field. I'm just looking for a sample code though of someone else performing a update request using Restsharp. I could write it all out in a string but I'm hoping for a easier way then using a string and passing as a parameter.
Edit
I'm currently trying to do it by building a string to pass in as the parameter. I know there has to be a better way. Here is my current progress on building a string;
Postman String:
request.AddParameter("application/javascript", "[\n {\n \"operation\": \"replace\",\n \"field\": \"/userName\",\n \"value\": \"testuser4#aha.org\"\n },\n {\n \"operation\": \"replace\",\n \"field\": \"/mail\",\n \"value\": \"testuser4#aha.org\"\n }\n]", ParameterType.RequestBody);
My string builder function in progress:
private string BuildUpdate(string field, string newvalue, string oldvalue)
{
try
{
string Update = string.Empty;
string UpdateOperation = '"' + "operation" + '"' + ": " + '"' + "replace\"" + ",\n" + '"';
string Updatefield = "field" + '"' + ": \"";
string UpdateNewValue = "/" + newvalue + '"' + ",\n";
string
// "[\n {\n \"operation\": \"replace\",\n\"
// field\": \"
// /userName\",\n
// \"value\": \"testuser4#aha.org\"\n },\n {\n \"operation\": \"replace\",\n \"field\": \"/mail\",\n \"value\": \"testuser4#aha.org\"\n }\n]"
return Update;
}
catch(Exception ex)
{
return null;
}
}
Anyone have a better way to do this?

I think I found the answer to my problem. I'm not sure if I have this in the right order but I got the string formatted correctly. I hope this helps someone else as well.
Here is my base function for performing my REST update request using Restsharp:
public string UpdateRequest(string uid, string field, string newvalue, string oldvalue)
{
try
{
string url = _EndPoint + "?_action = patch & _queryId =for-userName & uid =" + uid;
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
string username = "openidm-admin";
string password = "openidm-admin";
string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password));
string Update = BuildUpdate(field, newvalue, oldvalue);
if (Update != null)
{
request.AddHeader("Authorization", "Basic " + svcCredentials);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", Update, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
return response.Content.ToString();
}
else
{
//Error
return "Error";
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
I'm calling my BuildUpdate function to return my Json string that I will use to pass in as my parameter. Here is my function to build the update string. I broke it up into two parts and converted each part into a json string format. Then I combine them into a single string:
private string BuildUpdate(string field, string newvalue, string oldvalue)
{
try
{
//Parameter String
string Update = string.Empty;
//New Value
var dict1 = new Dictionary<string, string>();
dict1.Add("operation", "replace");
dict1.Add("field", field);
dict1.Add("value", newvalue);
string json1 = Regex.Unescape(JsonConvert.SerializeObject(dict1, Newtonsoft.Json.Formatting.Indented));
//Current Value
var dict2 = new Dictionary<string, string>();
dict2.Add("operation", "replace");
dict2.Add("field", field);
dict2.Add("value", oldvalue);
string json2 = Regex.Unescape(JsonConvert.SerializeObject(dict2, Newtonsoft.Json.Formatting.Indented));
Update = json1 + ",\n " + json2;
return Update;
}
catch(Exception ex)
{
return null;
}
}
Here is my output string I will pass in as my parameter:
"{\r\n \"operation\": \"replace\",\r\n \"field\": \"userName\",\r\n \"value\": \"testuser999#aha.org\"\r\n},\n {\r\n \"operation\": \"replace\",\r\n \"field\": \"userName\",\r\n \"value\": \"testuser4#aha.org\"\r\n}"
Update:
I just wanted to share my working code sample with everyone.
Function 1:
public string UpdateRequest(string uid, string field, string value)
{
try
{
string url = _EndPoint + "?_action=patch&_queryId=for-userName&uid=" + uid;
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
string username = "openidm-admin";
string password = "openidm-admin";
string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password));
string Update = BuildUpdate(field, value);
if (Update != null)
{
request.AddHeader("Authorization", "Basic " + svcCredentials);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", Update, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
return response.Content.ToString();
}
else
{
//Error
return "Error";
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
Here is the string building function to build your Json string for the request:
private string BuildUpdate(string field, string value)
{
try
{
//Parameter String
string json = string.Empty;
//Value
var dict = new Dictionary<string, string>();
dict.Add("operation", "replace");
dict.Add("field", field);
dict.Add("value", value);
json = "[\n" + Regex.Unescape(JsonConvert.SerializeObject(dict, Newtonsoft.Json.Formatting.Indented)) + "\n]";
return json;
}
catch(Exception ex)
{
return null;
}
}
I'm not sure why I have to add "[\n" or "\n]" but I assume its wrapping it for some reason. Anyway, I hope this helps someone.

Related

RestSharp doesn't get data or content of response

I have a route in my web service that receives POST request with Json body and returns simple array in Json format. I'm using PostMan for testing route and it works perfectly. but when I'm using RestSharp it doesn't get any content (or data in deserialization case).
Here is my C# code :
public static async Task<string> UpdateProfile(Profile user, string serviceUrl)
{
string bodyraw = JsonConvert.SerializeObject(user)
var client = new RestClient(serviceUrl);
var request = new RestRequest();
request.Method = Method.POST;
request.Parameters.Clear();
request.AddParameter("application/json", bodyraw, ParameterType.RequestBody);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = await client.ExecuteTaskAsync<Profile>(request);
return response.Data.Address;
}
And here is the Profile Class:
public class Profile
{
public string Name { get; set; }
public string Family { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Address { get; set; }
public string Postal_code { get; set; }
public string Education { get; set; }
public string Gender { get; set; }
public string Age { get; set; }
public string Default_contact { get; set; }
public override string ToString()
{
return string.Concat(Name," " ,Family, " ", Address);
}
}
And this is PostMan OutPut:
{
"Name": "Holma",
"Family": "Kool",
"Email": "dr#gmail.com",
"Mobile": "09063094744",
"Address": "some city- basic av. sq 60",
"Postal_code": "10246666",
"Education": "1",
"Gender": "male",
"Age": "35"
}
And the PHP code that I used is:
function silverum_update_user_profile($request ){
$parameters = $request->get_json_params();// this is a WordPress method and works just fine
$name=sanitize_text_field($parameters['name']);
$family=sanitize_text_field($parameters['family']);
$email=sanitize_text_field($parameters['email']);
$mobile=sanitize_text_field($parameters['mobile']);
$address=sanitize_text_field($parameters['address']);
$postal_code=sanitize_text_field($parameters['postal_code']);
$education=sanitize_text_field($parameters['education']);
$gender=sanitize_text_field($parameters['gender']);
$age=sanitize_text_field($parameters['age']);
$extdp = [
"Name"=>$name,
"Family"=>$family,
"Email"=>$email,
"Mobile"=>$mobile,
"Address"=>$address,
"Postal_code"=>$postal_code,
"Education"=>$education,
"Gender"=>$gender,
"Age"=>$age
];
return $extdp;
}
When PHP method returns "Parameter" its OK and both PostMan and RestSharp can see output content but when method Returns new Array only PostMan is able to recive returnd object. I spent a couple of hour on the issue but didn't get anywhere. help please.
Try using the AddJsonBody() method within the RestRequest object as opposed to adding the parameter manually.
public static async Task<string> UpdateProfile(Profile user, string serviceUrl)
{
var client = new RestClient(serviceUrl);
var request = new RestRequest();
request.Method = Method.POST;
request.AddJsonBody(user);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = await client.ExecuteAsync<Profile>(request);
return response.Data.Address;
}

Creating Restsharp call to add parameters in an array

I need to send the following parameters to an AP using Restsharp in my C# console app
I have looked on here and on other sites, but not found anything that I can get to work.
This is what the raw code looks like
{
"LicenceNumber":"511237P",
"CardNumber":"DB07067",
"ExternalID":"ID56758",
"Comments":"data uploaded via automated weekly process",
"Rules":"EU",
"Activities": [
{
"StartTime":"2019-04-14 09:00:00",
"Duration":"480",
"ActivityType":"Rest"
}
]
}
What I need to do is use the Restsharp request.AddAddParameter to add the StartTime, Duration and ActivityType to the Activities but I am not sure how to proceed.
What I have so far is the following:
static void PostRecord(string url)
{
url = url + "/" + MembershipNumber;
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + Token);
request.AddParameter("LicenceNumber", LicenceNumber);
request.AddParameter("CardNumber", CardNumber);
request.AddParameter("ExternalID", ExternalID);
request.AddParameter("Comments", Comments);
request.AddParameter("Rules", Rules);
request.AddParameter("Activities", "Activities");
}
Any help would be much appreciated
****** UPDATE **********
I have amended my code after some more investigation it runs but says that the Activities details must be supplied so its not recognising the values in the array
url = url + "/" + MembershipNumber;
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
var Activities= new Dictionary<string, object>();
Activities.Add("StartTime", "2019-04-14 09:00:00");
Activities.Add("Duration", "480");
Activities.Add("ActivityType", "Rest");
JsonObject o = new JsonObject();
foreach (var kvp in Activities)
{
o.Add(kvp);
}
JsonArray array = new JsonArray();
array.Add(o);
request.AddHeader("Authorization", "Bearer " + Token);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("LicenceNumber", LicenceNumber);
request.AddParameter("CardNumber", CardNumber);
request.AddParameter("ExternalID", ExternalID);
request.AddParameter("Comments", Comments);
request.AddParameter("Rules", Rules);
request.AddParameter("Activities", array.ToString());
IRestResponse response = client.Execute(request);
Create a object and then assign your values to it accordingly:
public class Activity
{
public string StartTime { get; set; }
public string Duration { get; set; }
public string ActivityType { get; set; }
}
public class RootObject
{
public string LicenceNumber { get; set; }
public string CardNumber { get; set; }
public List<Activity> Activities { get; set; }
}
You can use Auto Properties you can generate them from a website such as this
Then you can create an instance of that class and assign all the values you need like so:
url = url + "/" + MembershipNumber;
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + Token);
// This how you assign your values for the RootObject class
RootObject MyObject = RootObject();
MyObject.LicenceNumber = LicenceNumber;
MyObject.CardNumber = CardNumber;
// then for the activities class you can do the following
MyObject.Activities = new List<Activity>();
MyObject.Activities.Add(new Activity(){StartTime = "2019-04-14 09:00:00", Duration = "480",ActivityType = "Rest"});
string jsonString = JsonConvert.SerializeObject(MyObject);
request.AddParameter("application/json", jsonString, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

Get the ok massage from http posrequest

{
"token_type": "bearer",
"access_token": "ew0KICAiYWxnIjogIkhTMjU2IiwNCiAgInR5cCI6ICJKV1QiDQp9.ew0KICAidG9rZW5EYXRhIjogInpjeXNxSWcvbnBJTjBZWG5BSlpLa0JJQTRERnVMK2JCcTFrT0VhbWxCbXRieHJITFdhbVZBVnluSzl2U0dQRVpZdW1TZ1dQRERwemU3UEphSWhPTjJIeGgvWURHL09qalFyQXZFSHlRRkRucUFUM05NK3ZhY2RKMnBaTlFrYVpHNEU4MjhkVFZpMnduTml2N1g3OHR4VmkxcS84bnBmN25NcWc1UkZlZ1VockhPUUU1WXJuMlVsRmJTV200dDNsTHoyWTJpa2ZMOURJOTVBTHIvV25rdjdhWkljNlJ1Rld5OThid05ZOHpCMXc9IiwNCiAgImNsaWVudElEIjogImNhNjQ3ZDc3OTZjNTQ4MjA5Y2RkYTllZDAwNGMzOGFhNTI0ODE3MTcwODAyODAwNDYyOCIsDQogICJyZXBseVVybCI6ICJodHRwOi8vbG9jYWxob3N0IiwNCiAgIm5iZiI6IDE1MTMwNTkxMTcsDQogICJleHAiOiAxNTEzMDYwOTE3LA0KICAiaWF0IjogMTUxMzA1OTExNw0KfQ.ixRDlLYfrJ-OQs6LzkLhf07skR9z1i-3w1u7rtRppgE",
"expires_in": 1800.0,
"refresh_token": "zcysqIg/npIN0YXnAJZKkBIA4DFuL+bBq1kOEamlBmtbxrHLWamVAVynK9vSGPEZgS5OAD7gpY2OoBSeaHH48aQ/ER3WZOnOijWQrxEFNKU="
}
This is what i have json response. i want to display acces_token from this.so i want code line.
this is the code I try to get this json.
public async Task NewMethodAsync()
{
try
{
HttpClient objClient = new HttpClient();
Uri requestUri = new Uri("https://approvalbotbeta.azurewebsites.net/api/token");
Dictionary<string, string> pairs = new Dictionary<string, string>();
var client_ID = "ca647d7796c548209cdda9ed004c38aa5248171708028004628";
var client_secret = "QXBwcm92YWxCb3RfVE9H7auiwc6RhE6ldS6WGsqWh2NhNjQ3ZDc3OTZjNTQ4MjA5Y2RkYTllZDAwNGMzOGFhNTI0ODE3MTcwODAyODAwNDYyOA==";
pairs.Add("grant_type", "client_credentials");
pairs.Add("reply_url", "http://localhost");
FormUrlEncodedContent httpContent = new FormUrlEncodedContent(pairs);
var encordedString = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(client_ID + ":" + client_secret));
// httpContent.Headers.Add("Authorization", "Basic " + encordedString);
//httpContent.Headers.Add("Authorization", "Basic " + encordedString);
// httpContent.Headers.Add["Authorization"] = "Basic" + encordedString;
objClient.DefaultRequestHeaders.Add("Authorization", "Basic " + encordedString);
HttpResponseMessage respon = await objClient.PostAsync("https://approvalbotbeta.azurewebsites.net/api/token", httpContent);
if (respon.IsSuccessStatusCode)
{
Console.WriteLine(respon.Content.ReadAsStringAsync().Result);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You need to install Newtonsoft.Json library and use this code:
dynamic json = JsonConvert.DeserializeObject(result);
string token = json.refresh_token;
Just create response class
public class Response
{
public string token_type { get; set; }
public string access_token { get; set; }
public double expires_in { get; set; }
public string refresh_token { get; set; }
}
Then use Newstonsoft Json - https://www.nuget.org/packages/newtonsoft.json/
var response = JsonConvert.DeserializeObject<Response>(result);
Console.WriteLine(response.access_token);

JSON String to DataTable Object in C#

So basically I SEARCHED everywhere, and I'm not finding anything that works in my situation.
I'm working with an API for Overwatch (a game) and I want to turn a String I download from the web, and check if it has a JSON string.
Let me show you the code:
< !--language: c# -->
HttpClient dc = new HttpClient();
string tag = e.Message.Text.ToString().Substring(7).Replace("#", "-");
string apiurl = (#"http://api.lootbox.eu/" + "pc/" + "global/" + tag + "/profile");
HttpResponseMessage datares = await dc.GetAsync(apiurl);
string finaldata = await datares.Content.ReadAsStringAsync();
#region PC
if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "pc/" + "us/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "pc/" + "kr/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "pc/" + "eu/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "pc/" + "cn/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
#endregion
#region XBOX LIVE
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "us/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "eu/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "kr/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "cn/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "xbl/" + "global/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
#endregion
#region PSN
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "us/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "global/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "cn/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "eu/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
else if (finaldata.Contains(":404"))
{
apiurl = (#"http://api.lootbox.eu/" + "psn/" + "kr/" + tag + "/profile");
datares = await dc.GetAsync(apiurl);
finaldata = await datares.Content.ReadAsStringAsync();
}
#endregion
DataTable obj = JsonConvert.DeserializeObject(finaldata);
So an example output, in this case, wouldv'e been:
{"data":{"username":"Rezoh","level":305,"games":{"quick":{"wins":"378"},"competitive":{"wins":"82","lost":85,"played":"167"}},"playtime":{"quick":"88 hours","competitive":"36 hours"},"avatar":"https://blzgdapipro-a.akamaihd.net/game/unlocks/0x0250000000000D70.png","competitive":{"rank":"3392","rank_img":"https://blzgdapipro-a.akamaihd.net/game/rank-icons/season-2/rank-5.png"},"levelFrame":"https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/0x025000000000092D_Border.png","star":"https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/0x025000000000092D_Rank.png"}}
Now I need to convert that to a table of some sort or something.
I got the JSON.Net but most people said to setup a class BEFORE you convert,
Problem was that: I had 2 "wins": and 3 "competitive": as you can see in the JSON string.
So making a class wasn't possible to my belief in this case. I tried making a new DataTable as shown in the last line of code but it tells me "Cannot implicitly convert type object to System.Data.DataTable" when using JsonConvert.DeserializeObject(finaldata); I even tried doing .ToString(); and also the dates variable, and .ToString() in that too.
I need a proper way to show these stats so, for example, I can show:
"Stats for user " + obj.Name + ":"
"Wins: " + obj.Wins
"Losses: " + obj.Losses
"Rank: " + obj.Rank
And no solutions online help me in my situation.
EDIT:
This solution doesn't work either for me:
convert json String to datatable?
or this
Nested Json String to DataTable
Nor does this:
var token = JToken.Parse(finaldata);
if (token.Type == JTokenType.Object)
token = new JArray(token);
var a = token.ToObject<DataTable>();
You can use a class as they said. I used http://json2csharp.com/ but VS can do it too.
You can try it here: https://dotnetfiddle.net/iaIvOn
using System;
using Newtonsoft.Json;
public class Program
{
public void Main()
{
var json = #"{""data"":{""username"":""Rezoh"",""level"":305,""games"":{""quick"":{""wins"":""378""},""competitive"":{""wins"":""82"",""lost"":85,""played"":""167""}},""playtime"":{""quick"":""88 hours"",""competitive"":""36 hours""},""avatar"":""https://blzgdapipro-a.akamaihd.net/game/unlocks/0x0250000000000D70.png"",""competitive"":{""rank"":""3392"",""rank_img"":""https://blzgdapipro-a.akamaihd.net/game/rank-icons/season-2/rank-5.png""},""levelFrame"":""https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/0x025000000000092D_Border.png"",""star"":""https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/0x025000000000092D_Rank.png""}}";
// read the doc: http://www.newtonsoft.com/json
var rootObject = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine("Stats for user " + rootObject.Data.Username + ":");
Console.WriteLine("Wins: " + rootObject.Data.Games.Competitive.Wins);
Console.WriteLine("Losses: " + rootObject.Data.Games.Competitive.Lost);
Console.WriteLine("Rank: " + rootObject.Data.Competitive.Rank);
}
public class Quick
{
// Free case support!
public string Wins { get; set; }
}
public class Competitive
{
public string Wins { get; set; } // you may want to check this string here ;)
public int Lost { get; set; }
public string Played { get; set; }
}
public class Games
{
public Quick Quick { get; set; }
public Competitive Competitive { get; set; }
}
public class Playtime
{
public string Quick { get; set; }
public string Competitive { get; set; }
}
public class Competitive2
{
public string Rank { get; set; }
// attribute ftw! http://www.newtonsoft.com/json/help/html/SerializationAttributes.htm
[JsonProperty(PropertyName = "rank_img")]
public string RankImg { get; set; }
}
public class Data
{
public string Username { get; set; }
public int Level { get; set; }
public Games Games { get; set; }
public Playtime Playtime { get; set; }
public string Avatar { get; set; }
public Competitive2 Competitive { get; set; }
public string LevelFrame { get; set; }
public string Star { get; set; }
}
public class RootObject
{
public Data Data { get; set; }
}
}
output
Stats for user Rezoh:
Wins: 82
Losses: 85
Rank: 3392
If Quick and Competitive are Game, maybe:
public abstract class Game
{
public string Wins { get; set; } // you may want to check this string here ;)
public int Lost { get; set; }
public string Played { get; set; }
}
public class Quick : Game // note that Quick game has Lost and PLayed now!
{
}
public class Competitive : Game
{
}
Or even (as #EpicSam proposed in comment):
public class Game
{
public string Wins { get; set; } // you may want to check this string here ;)
public int Lost { get; set; }
public string Played { get; set; }
}
public class Games
{
public Game Quick { get; set; }
public Game Competitive { get; set; }
}

How to use "like" feature in facebook c# sdk 5.4.1?

in facebook developers site it seems pretty easy.just make a HTTP POST to POST_ID/likes(i got the post i.d).
in c# sdk v.5.4.1 there is a POST method but i can't figure out how to use it and make the right call.
Look at the face book API documentation..here http://developers.facebook.com/
var fb = new FacebookClient("my token");
dynamic parameters = new ExpandoObject();
parameters.message = "the publish msg";
dynamic result = fb.Post("/me/feed", parameters);
var id = result.id;
var res = fb.Post("/" + id + "/likes");
I was having the same issue so I tried few things & this worked for me
var token = "[your access token]";
var fb = new Facebook.FacebookClient(token);
var postId = "173213306032925_745288855492031"; //replace this with your big id which comprises of [userid]_[postid]
Console.WriteLine(fb.Post(id+"/likes", null).ToString()); // should print 'True'
Console.WriteLine(fb.Get("173213306032925_745288855492031/likes").ToString()); //should give you details
public void FacebookLike(AppConnect appconnect )
{
try
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string fb_exchange = appconnect.UserToken;
string url =
string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&grant_type=fb_exchange_token&fb_exchange_token={3}&redirect_uri=https://www.facebook.com/connect/login_success.html&scope={1}&client_secret={2}",
appconnect.AppID, appconnect.ExtendedPermissions, appconnect.AppSecret, fb_exchange);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
dynamic parameters = new ExpandoObject(); parameters.idobject = "";
client.Post("/" + appconnect.AppID.ToString() + "_" + appconnect.PostID.ToString() + "/Likes", parameters);
// MessageBox.Show("....... Done ..........");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message +"\n"+ex.InnerException);
}
}
class AppConnect
{
//tring appId, string Appsecret, string userToken, string userID, string PostID
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string AppID { get; set; } = "991341734653453831";
public string AppSecret { get; set; } = "99dfbf29234ergec4a";
public string UserID { get; set; } = null;
public string UserToken { get; set; } = null;
public string PostID { get; set; } = null;
public string ExtendedPermissions { get; set; } = "user_posts, publish_actions, publish_pages,manage_pages,user_likes";
}

Categories

Resources