RestSharp - Problems with Nested JSON data - c#

I've tried other answers with people who had the same issue, but I can't get it to work. Plus I'm new to this. Any help is appreciated.
When I run this, my phone data is null.
Here's the JSON data I get back from my service.
{"GetDirectoriesResult":"[{\"id\":1,\"department\":\"Admitting\",\"subdepartment\":\"\",\"phone\":\"555-444-4013\",\"comments\":\"Press 1\"},{\"id\":2,\"department\":\"Ambulatory Surgery Center\",\"subdepartment\":\"\",\"phone\":\"555-444-4013\",\"comments\":\"\"}]"}
My Code
public class PhoneList
{
// public string GetDirectoriesResult { get; set; }
public List<Phone> Phones { get; set; } //- can't get this working
}
public class Phone
{
public int id { get; set; }
public string department { get; set; }
public string subdepartment { get; set; }
public string phone { get; set; }
public string comments { get; set; }
}
public IRestResponse<PhoneList> Execute<PhoneList>(RestRequest request) where PhoneList : new()
{
PhoneList ro = new PhoneList();
var client = new RestClient();
client.BaseUrl = BaseUrl;
// var request = new RestRequest();
request.RequestFormat = DataFormat.Json;
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(ro);
IRestResponse<PhoneList> response = client.Execute<PhoneList>(request);
if (response.ErrorException != null)
{
const string message = "Error retrieving response. Check inner details for more info.";
var Exception = new ApplicationException(message, response.ErrorException);
throw Exception;
}
return response;
}

Related

Why API doesn't response correctly for my request?

I am testing request for API from Baselinker. I have created simple app in c#, which takes input as JSON file with parameters, then converts it to API request model, send it to API and receive response.
But I have problem with one request, https://api.baselinker.com/index.php?method=getOrders. When I try to get orders from my test account by this request I got response "Order source does not exist.", idk why - I have checked every variable in my class which represents this request but didn't find anything wrong. When I do the same on testing API request site (https://api.baselinker.com/index.php?tester) it works correct.
Here is my source code:
Class representing getOrder request:
public class GetOrders : IRequest<GetOrders.Response> {
[JsonPropertyName("order_id")]
public int? OrderId { get; set; }
[JsonPropertyName("date_confirmed_from")]
public int? DateConfirmedFrom { get; set; }
[JsonPropertyName("date_from")]
public int? DateFrom { get; set; }
[JsonPropertyName("id_from")]
public int? IdFrom { get; set; }
[JsonPropertyName("get_unconfirmed_orders")]
public bool? GetUnconfirmedOrders { get; set; }
[JsonPropertyName("include_custom_extra_fields")]
public bool? IncludeCustomExtraFields { get; set; }
[JsonPropertyName("status_id")]
public int? StatusId { get; set; }
[JsonPropertyName("filter_email")]
public string? FilterEmail { get; set; }
[JsonPropertyName("filter_order_source")]
public string? FilterOrderSource { get; set; }
[JsonPropertyName("filter_order_source_id")]
public int? FilterOrderSourceId { get; set; }
public class Product {
```Product class properties...```
}
public class Order {
```Order class properties...```
}
public class Response : Output {
[JsonPropertyName("orders")]
public List<Order> Orders { get; set; }
}
}
Class sending requests:
public class BaselinkerRequestManager {
private string _token;
private const string _url = "https://api.baselinker.com/connector.php";
public BaselinkerRequestManager(string token) { _token = token; }
private string GetRequestMethodName(object userRequest) {
return JsonNamingPolicy.CamelCase.ConvertName(userRequest.GetType().Name);
}
private RestRequest CreateRequest(string method, object parameters) {
var request = new RestRequest();
request.Method = Method.Post;
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("X-BLToken", _token);
request.AddParameter("method", method);
if ( parameters != null ) {
request.AddParameter("parameters", JsonSerializer.Serialize(parameters));
}
return request;
}
private async Task<RestResponse> ExecuteRequestAsync(RestClient client, RestRequest request) {
return await client.ExecuteAsync(request);
}
//TResponse - generic which represents Response Class in each Request
public async Task<TResponse> SendRequestAsync<TResponse>(IRequest<TResponse> userRequest) {
var client = new RestClient(_url);
var method = GetRequestMethodName(userRequest);
var request = CreateRequest(method, userRequest);
var response = await ExecuteRequestAsync(client, request);
return JsonSerializer.Deserialize<TResponse>(response.Content);
}
}
Here is call:
var requestManager = new BaselinkerRequestManager("token_to_connect");
//this request doesn't need parameters so i dont have to initialize it
var r_getOrders = await requestManager.SendRequestAsync(new Requests.Orders.GetOrders());

how to convert list obj to client.PostAsJsonAsync

how to convert list obj to client.PostAsJsonAsync
Class model
public class CheckStatusModel
{
public int OBJID { get; set; }
public string SUPID { get; set; }
public string STATUSPTC { get; set; }
public int DATEACTIVESUP { get; set; }
}
public class CheckStatus
{
public CheckStatusModel Data { get; set; }
public string StatusCode { get; set; }
}
Sending request to find web api REST service resource using
HttpClient**
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync("api/RPDeployment/BIL_CFP_BOX_CHECK_STATUSPTC", checkStatusParam);
if(response.IsSuccessStatusCode)
{
var EmpResponse = response.Content.ReadAsStringAsync().Result;
ListStatusPTC = JsonConvert.DeserializeObject<List<CheckStatus>>(EmpResponse);// not convert ????
}
}
EmpResponse
{
"data": [**
{
"OBJID": 1012540462,
"SUPID": 1041252952,
"STATUSPTC": 1,
"DATEACTIVESUP": 0
}
**],
"StatusCode": 200
}
help me please ??
Oh I see. You're trying to deserialize an object (denoted by { and }) into a list (in JSON, denoted by [ and ]).
You need to change your CheckStatus class as follows:
public class CheckStatus
{
public List<CheckStatusModel> Data { get; set; } // data is an array so this needs to be some kind of collection
public string StatusCode { get; set; }
}
And deserialize like so:
ListStatusPTC = JsonConvert.DeserializeObject<CheckStatus>(EmpResponse); // the JSON contains an object, so this needs to deserialize to an object. you can't deserialize to a list.

Xamarin upload image to a REST web server (Bad Request)

I know that this question has already been posted more than one time but I’m still hanged with the problem of sending one image from a Xamarin client to a REST web server. I receive a BadRequest error on the client side but I don’t know if it comes from the server or from the client.
Here is the Xamarin code (client side) :
public class WsDest
{
public string D_ID { get; set; }
public string D_NOM { get; set; }
public string D_CAT1 { get; set; }
public string D_CAT2 { get; set; }
public string D_ANNEE { get; set; }
public Byte[] D_PHOTO1 { get; set; }
}
static async Task<string> Do_UpdateVehiculeInfos(WsDest Dest)
{
string cRet = "";
string cIP = Application.Current.Properties["IPSERVEUR"].ToString().Trim();
using (HttpClient client = new HttpClient())
{
try
{
var oJson = JsonConvert.SerializeObject(Dest);
var cJson = new StringContent(oJson, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("Application/json"));
client.Timeout = TimeSpan.FromMilliseconds(8000);
client.MaxResponseContentBufferSize = 3000000;
client.BaseAddress = new Uri(cIP + "/MyWebService.svc/");
using (HttpResponseMessage r = await client.PostAsync("UpdateVehicule", cJson))
{
if (r.IsSuccessStatusCode)
{
await Application.Current.MainPage.DisplayAlert("", "Mise à jour effectuée !", "+OK+");
await Application.Current.MainPage.Navigation.PopAsync(); //Remove the page currently on top (= retourne à la page d'avant)
}
else
{
await Application.Current.MainPage.DisplayAlert("", r.ReasonPhrase.ToString(), "-OK-");
}
}
}
catch (Exception e)
{
await Application.Current.MainPage.DisplayAlert("", e.Message, "/OK/");
}
}
return cRet;
}
On the server side :
[DataContract]
public class WsDest
{
[DataMember]
public string D_ID { get; set; }
[DataMember]
public string D_NOM { get; set; }
[DataMember]
public string D_CAT1 { get; set; }
[DataMember]
public string D_CAT2 { get; set; }
[DataMember]
public string D_ANNEE { get; set; }
[DataMember]
public Byte[] D_PHOTO1 { get; set; }
}
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "UpdateVehicule")]
bool UpdateVehicule(WsDest DestUpdate) ;
public bool UpdateVehicule(WsDest DestRecep)
{
// my code to process data and image
}
The BadRequest message desapears when I set Dest.D_PHOTO1 to null on client side.
Does anybody have an idea on this subject?
Can you show us how the JSON looks like with the byte having a value?<<
Before the Json.SerializeObject(Dest), DEST.D_PHOTOS1 is {byte[6855981]}.
[137,80,70,....]
After the serialization, it's something more 'exotic' :
Before and after serialization
Eric

Facebook Graph API is not returning the property user_birthday

I'm using Facebook Graph API to return user information for my app. So far I only needed to get the email as an extended property and I never had any problem with it. However, now I have to get the user birthday, but it is not working as expected. I am getting a null value.
Here is part of the class I use to return the information
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OAuth2;
namespace Contoso.Web.Mvc.Controls.Authentication.IdentityProviders
{
public class FacebookIdentityProvider : IdentityProvider
{
public override ActionResult Authenticate(Func<LoginParameters, ActionResult> CallbackFunction)
{
var authorization = fbClient.ProcessUserAuthorization();
var urlHelper = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
if (authorization == null && String.IsNullOrWhiteSpace(Parameters.AccessToken))
{
//Kick off authorization request
fbClient.RequestUserAuthorization(scope: new string[] { "email", "user_birthday"});
}
else
{
if(authorization != null)
Parameters.AccessToken = authorization.AccessToken;
var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(Parameters.AccessToken));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var graph = FacebookGraph.Deserialize(responseStream);
var user = GetUser(graph);
var requiresExtraInformation = false;
DoFormAuthenticationAndCreateUserIfNeeded(user, out requiresExtraInformation);
if (requiresExtraInformation)
{
return RedirectToExtraInformationPage(user);
}
return CallbackFunction(Parameters);
}
}
}
return new RedirectResult(urlHelper.Action("Index"));
}
}
[DataContract]
public class FacebookGraph
{
private static DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(FacebookGraph));
[DataMember(Name = "id")]
public long Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "first_name")]
public string FirstName { get; set; }
[DataMember(Name = "last_name")]
public string LastName { get; set; }
[DataMember(Name = "email")]
public string Email { get; set; }
[DataMember(Name = "gender")]
public string Gender { get; set; }
[DataMember(Name = "user_birthday")]
public string UserBirthday { get; set; }
public static FacebookGraph Deserialize(string json)
{
if (string.IsNullOrEmpty(json))
{
throw new ArgumentNullException("jsonStream");
}
return Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(json)));
}
public static FacebookGraph Deserialize(Stream jsonStream)
{
if (jsonStream == null)
{
throw new ArgumentNullException("jsonStream");
}
return (FacebookGraph)jsonSerializer.ReadObject(jsonStream);
}
}
}
When I deserialize the response I get from facebook I get all the information I need except for the user birthday (it appears as null). I checked and my facebook profile does have the user birthday.
Ok, I finally found the problem and it was a little bit silly, but I'm leaving it here in case someone else stumbles upon this.
The problem was that even though I was requesting the correct scope "user_birthday", the property in the graph object is just called "birthday", so instead of having this
[DataMember(Name = "user_birthday")]
public string UserBirthday { get; set; }
I should have this
[DataMember(Name = "birthday")]
public string UserBirthday { get; set; }
And that's it. It's working now!

Getting FB Page data from facebook using C#

In my Desktop application, I want to read the Wall posts,Messages, Like counts etc for a particular Facebook page (not for a facebook user)
I went through this post get user data(on stackoverflow). I want to achieve the same thing but for a FB page.
I am ready to create a facebook application to achieve this and have the user to give permission to pull the data.
Please advice on the above.
You need an access token to get page data from Facebook.
First get an access token using below URL with your facebook application's parameters:
https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={yourappid}&client_secret={yourappscret}
Then you can call the Facebook Graph API with returning token
General: https://graph.facebook.com/wikipedia?access_token={token}
Posts: https://graph.facebook.com/wikipedia/posts?access_token={token}
An example code would be;
class Program
{
static void Main(string[] args)
{
var client = new WebClient();
string oauthUrl = string.Format("https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={0}&client_secret={1}", "appid", "appsecret");
string accessToken = client.DownloadString(oauthUrl).Split('=')[1];
string pageInfo = client.DownloadString(string.Format("https://graph.facebook.com/wikipedia?access_token={0} ", accessToken));
string pagePosts = client.DownloadString(string.Format("https://graph.facebook.com/wikipedia/posts?access_token={0} ", accessToken));
}
}
After researching i have developed this code
class Posts
{
public string PostId { get; set; }
public string PostStory { get; set; }
public string PostMessage { get; set; }
public string PostPictureUri { get; set; }
public Image PostImage { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
}
private List<Posts> getFBPosts()
{
//Facebook.FacebookClient myfacebook = new Facebook.FacebookClient();
string AppId = "--------";
string AppSecret = "----------";
var client = new WebClient();
string oauthUrl = string.Format("https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={0}&client_secret={1}", AppId, AppSecret);
string accessToken = client.DownloadString(oauthUrl).Split('=')[1];
FacebookClient myfbclient = new FacebookClient(accessToken);
string versio= myfbclient.Version;
var parameters = new Dictionary<string, object>();
parameters["fields"] = "id,message,picture";
string myPage="fanPage"; // put your page name
dynamic result = myfbclient.Get(myPage +"/posts", parameters);
List<Posts> postsList = new List<Posts>();
int mycount=result.data.Count;
for (int i = 0; i < result.data.Count; i++)
{
Posts posts = new Posts();
posts.PostId = result.data[i].id;
posts.PostPictureUri = result.data[i].picture;
posts.PostMessage= result.data[i].message;
var request = WebRequest.Create(posts.PostPictureUri);
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
posts.PostImage = Bitmap.FromStream(stream);
}
postsList.Add(posts);
}
return postsList;
}
You can also use a Nuget package called Facebook to fetch data from Facebook graph. Also, Json.NET helps you map the data directly into objects:
public class FacebookPageInfo
{
public long Id { get; set; }
public string Name { get; set; }
}
public class FacebookPost
{
public string Message { get; set; }
// ReSharper disable once InconsistentNaming
public string Created_Time { get; set; }
public string Id { get; set; }
}
public class FacebookPagingInfo
{
public string Previous { get; set; }
public string Next { get; set; }
}
public class FacebookPostData
{
public List<FacebookPost> Data { get; set; }
public FacebookPagingInfo Paging { get; set; }
}
public class Friend
{
public string Id { get; set; }
public string Name { get; set; }
}
// get access token
string oauthUrl = $"https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={appId}&client_secret={appSecret}";
string accessToken = client.DownloadString(oauthUrl).Split('=')[1];
// get data and deserialize it
var fbClient = new FacebookClient(accessToken);
var fbData = fbClient.Get("/wikipedia/").ToString();
var info = JsonConvert.DeserializeObject<FacebookPageInfo>(fbData);
fbData = fbClient.Get("/wikipedia/posts").ToString();
var posts = JsonConvert.DeserializeObject<FacebookPostData>(fbData);

Categories