Below is my JSON response from PHP Web API. I need this "tradeType" to be loaded in WPF ComboBox after checking "success"is true/false, If false display Error message shown in "message"
{
"success":"true",
"message":"Trade Type List",
"tradeType":[
{"id":1, "name":"Coaching Class"},
{"id":2,"name":"Food Supply"},
{"id":3,"name":"Marriage Bureau"}
]
}
I am new to WPF and Web API, what i have tried is
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://offline.localhost.in/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/utilities/trade_types").Result;
if (response.IsSuccessStatusCode)
{
var jsonString = response.Content.ReadAsStringAsync();
Root myDeserializedClass = JsonConvert.DeserializeObject<List<TradeType>>(jsonString);
cmbTrade.ItemsSource = users;
}
else
{
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}
var jsonString = response.Content.ReadAsStringAsync();
You are missing an await here so the call is fired but not awaited. Also have Task in var instead the string.
var jsonString = await response.Content.ReadAsStringAsync();
or use the non-async version.
public class TradeType
{
public int id { get; set; }
public string name { get; set; }
}
public class Root
{
public string success { get; set; }
public string message { get; set; }
public List<TradeType> tradeType { get; set; }
}
private void GetData()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://offline.localhost.in/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/utilities/trade_types").Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(result);
myDeserializedClass.tradeType.Insert(0, new TradeType { id = 0, name = "-Select-" });
cmbTrade.ItemsSource = myDeserializedClass.tradeType;
cmbTrade.DisplayMemberPath = "name";
cmbTrade.SelectedValuePath = "id";
cmbTrade.SelectedIndex = 0;
}
else
{
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}
}
Related
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);
I am working in Exception Logging, I have created API for that, API taking exception as parameter and few more thing.
[HttpPost]
[Route("/Log")]
public IEnumerable<string> Post([FromBody] WP2Exceptions wp2Exceptions)
{
ExceptionsModel exceptionsModel = new ExceptionsModel();
exceptionsModel = _exceptions.GetExceptionsByType(wp2Exceptions.exception.GetType().ToString());
ExceptionsLogModel exceptionLogModel = new ExceptionsLogModel();
exceptionLogModel.ExceptionID = exceptionsModel.ExceptionID;
exceptionLogModel.ModuleName = System.Reflection.Assembly.GetEntryAssembly().GetName().Name;
exceptionLogModel.ExceptionMessage = wp2Exceptions.exception.Message;
exceptionLogModel.ExceptionType = wp2Exceptions.exception.GetType().ToString();
exceptionLogModel.ExceptionSource = wp2Exceptions.exception.Source.ToString();
exceptionLogModel.ExceptionUrl = wp2Exceptions.exception.StackTrace;
_exceptionsLog.AddExceptionsLog(exceptionLogModel);
return new string[] { exceptionsModel.ExceptionType, exceptionsModel.Message };
}
public class WP2Exceptions
{
public string moduleName { get; set; }
public Exception exception { get; set; }
}
While i am passing exception in parameter i am getting "Bad Request" error
Test Code
public async void callAPI()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:50558/");
try
{
string s = null;
string sp = s.ToString();
}
catch (Exception ex)
{
var mydata = "{'exception':'" + JsonConvert.SerializeObject(ex) + "','moduleName':'WEBAPI'}";
var response = await client.PostAsync("Log", new StringContent(mydata, Encoding.UTF8, "application/json"));
if (response != null)
{
Console.WriteLine("Log ID - " + response.ToString());
}
}
}
Please correct me where i am doing wrong or is it possible can we pass exception object as a WEB API parameter?
I resolve the problem,
In remove below code.
var mydata = "{'exception':'" + JsonConvert.SerializeObject(ex) + "','moduleName':'WEBAPI'}";
Created new class and pass the data .
public class paramObject
{
public string modulename { get; set; }
public Exception exception { get; set; }
}
Inside callAPI method i implement following code.
pramObject po = new pramObject()
{
modulename="Webapi",
exception=ex,
};
var response = await client.PostAsync("Log", new StringContent(JsonConvert.SerializeObject(po), Encoding.UTF8, "application/json"));
{
"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);
I'm attempting to do a multipart upload to Google via web request, and I've followed Google's instructions on how to construct a valid multipart file upload request so I can send up metadata and the actual file data at the same time, but I keep getting a "Missing end boundary in multipart body." error when I try and upload a file and am out of ideas as to why. What am I doing wrong?
Also, I'm not using the Drive SDK as it did not suit my needs.
Here's my code:
public bool WriteFileData(Stream data, DSFile file, DSUser user)
{
var parent = new Parent();
var folders = GetUserFolders(user, false);
DSFolder parentFolder = folders.Where(f => f.FullPath == file.VirtualPath).FirstOrDefault();
parent.Id = parentFolder.DepositoryFolderId;
var addFileRequest = new AddFileRequest();
addFileRequest.Parents.Add(parent);
addFileRequest.Title = (file.FileName.ToLower().Contains(".ext") == false) ? file.FileName + ".ext" : file.FileName;
addFileRequest.ModifiedDate = ServiceUtil.ToISO8601(DateTime.Now);
addFileRequest.MimeType = "application/octet-stream";
addFileRequest.WritersCanShare = false;
addFileRequest.Description = file.Description;
addFileRequest.Labels = new FileLabels();
byte[] binData = new byte[data.Length];
data.Read(binData, 0, (int)data.Length);
string metadata = Microsoft.Http.HttpContentExtensions.CreateJsonDataContract<AddFileRequest>(addFileRequest).ReadAsString();
string binData64 = Convert.ToBase64String(binData);
string contentString = "--123ABC Content-Type: application/json; charset=UTF-8 " + metadata;
contentString += "--123ABC Content-Type: application/octet-stream " + binData64;
contentString += " --123ABC--";
HttpResponseMessage response;
try
{
HttpClient client = new HttpClient();
AddAuthHeader(client, credential.AccessToken);
client.DefaultHeaders.ContentType = "multipart/related; boundary=\"123ABC\"";
client.DefaultHeaders.ContentLength = HttpContent.Create(contentString).ReadAsByteArray().Length;
response = client.Post("https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart", HttpContent.Create(contentString));
string responseText = response.Content.ReadAsString();
return false;
}
catch (Exception ex)
{
return false;
}
}
EDIT: Here's my definition for AddFileRequest:
[DataContract]
public class AddFileRequest
{
[DataMember(Name="title")]
public string Title { get; set; }
[DataMember(Name = "labels")]
public FileLabels Labels { get; set; }
[DataMember(Name = "mimeType")]
public string MimeType { get; set; }
[DataMember(Name = "modifiedDate")]
public string ModifiedDate { get; set; }
[DataMember(Name = "parents")]
public List<Parent> Parents { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
[DataMember(Name="writersCanShare")]
public bool WritersCanShare { get; set; }
}
Found a solution. I decided to poke around the object browser and noticed that the System.Net.Http namespace has a "MultipartFormDataContent" class that did the trick. I didn't see it before because, for some reason, there are two different sets of nearly identical (but incompatible) HTTP namespaces: Microsoft.Http and System.Net.Http. Here's the updated code that works:
public bool WriteFileData(Stream data, DSFile file, DSUser user)
{
var parent = new Parent();
var folders = GetUserFolders(user, false);
DSFolder parentFolder = folders.Where(f => f.FullPath == file.VirtualPath).FirstOrDefault();
parent.Id = parentFolder.DepositoryFolderId;
var addFileRequest = new AddFileRequest();
addFileRequest.Parents.Add(parent);
addFileRequest.Title = (file.FileName.ToLower().Contains(".ext") == false) ? file.FileName + ".ext" : file.FileName;
addFileRequest.ModifiedDate = ServiceUtil.ToISO8601(DateTime.Now);
addFileRequest.MimeType = "application/octet-stream";
addFileRequest.WritersCanShare = false;
addFileRequest.Description = file.Description;
addFileRequest.Labels = new FileLabels();
string metadata = Microsoft.Http.HttpContentExtensions.CreateJsonDataContract<AddFileRequest>(addFileRequest).ReadAsString();
var content = new System.Net.Http.MultipartFormDataContent("ABC123");
content.Add(new System.Net.Http.StringContent(metadata, System.Text.Encoding.UTF8, "application/json"));
content.Add(new System.Net.Http.StreamContent(data));
try
{
var client = new System.Net.Http.HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", credential.AccessToken);
var response = client.PostAsync("https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart", content).Result;
string responseText = response.Content.ReadAsStringAsync().Result;
return false;
}
catch (Exception ex)
{
return false;
}
}
On the controller Put is as following:
[HttpPut]
[ActionName("putname")]
public JsonResult putname(string name)
{
var response = ...
return Json(response);
}
The issue is on the when consuming this API via following
using (httpClient = new HttpClient())
{
string name = "abc";
string jsonString = JsonConvert.SerializeObject(name);
var requestUrl = new Uri("http:...../controller/putname/");
using (HttpContent httpContent = new StringContent(jsonString))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = httpClient.PutAsync(requestUrl, httpContent).Result;
}
This code doesn't pass the parameter name to controller. I even tried changeing uri to /putname/" + name.
Here is what works for me:
var jsonString = "{\"appid\":1,\"platformid\":1,\"rating\":3}";
var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
var message = await _client.PutAsync(MakeUri("App/Rate"), httpContent);
Assert.AreEqual(HttpStatusCode.NoContent, message.StatusCode);
and my action method:
public void PutRate(AppRating model)
{
if (model == null)
throw new HttpResponseException(HttpStatusCode.BadRequest);
if (ModelState.IsValid)
{
// ..
}
}
and the model
public class AppRating
{
public int AppId { get; set; }
public int PlatformId { get; set; }
public decimal Rating { get; set; }
}
-Stan
For me it worked correctly:
string requestUrl = endpointUri + "/Files/";
var jsonString = JsonConvert.SerializeObject(new { name = "newFile.txt", type = "File" });
HttpContent httpContent = new StringContent(jsonString);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue ("application/json");
HttpClient hc = new HttpClient();
//add the header with the access token
hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
//make the put request
HttpResponseMessage hrm = (await hc.PostAsync(requestUrl, httpContent));
if (hrm.IsSuccessStatusCode)
{
//stuff
}