Currently working on a project with the cloud / azure and windows phone 7, I must make a call to service.
For me the convenience I use sharp rest but I am facing a problem;
I do not know when my appeal is complete.
public static bool CreateUser(User userToCreate)
{
if (CheckNetwork())
{
var client = new RestClient(Global.Url);
var request = new RestRequest("/user", Method.POST);
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
ser.WriteObject(ms, userToCreate);
string json = JsonHelper.ToJson(userToCreate);
request.AddHeader("Content-type", "application/json; charset=utf-8");
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
try
{
object resp = null;
client.ExecuteAsync(request, response =>
{
if (response.ResponseStatus == ResponseStatus.Completed)
{
RestResponse resource = response;
string content = resource.Content;
resp = Convert.ToBoolean(JsonHelper.FromJson<string>(content));
}
});
return (bool)resp;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return false;
}
}
MessageBox.Show("You are not connect to the network!");
return false;
}
In this example, the method return first "resp" before making his call to service.
How can I be sure I do not exit this method before resp not been filled?
EventWaitHandle Wait = new AutoResetEvent(false);
client.ExecuteAsync(request, response =>
{
if (response.ResponseStatus == ResponseStatus.Completed)
{
RestResponse resource = response;
string content = resource.Content;
resp = Convert.ToBoolean(JsonHelper.FromJson<string>(content));
Wait.Set();
}
});
Wait.WaitOne();
Related
how can i get a signal that my external agenda in my own app needs to be updated when there is a new event been made. at this moment my code looks like this but i can't retrieve a new event from google calendar. what do i do wrong.
public async Task<List<EventModel>> GetAllEventsAsync()
{
var refresToken = RetrieveRefreshTokenAndRevoke.RefreshToken();
if (refresToken == "ok")
{
var tokens = JObject.Parse(System.IO.File.ReadAllText(ConstantJsonFileLink.TOKEN));
RestClient restClient = new RestClient(new Uri("https://www.googleapis.com/calendar/v3/calendars/primary/events"));
RestRequest restRequest = new RestRequest(Method.GET);
restRequest.AddQueryParameter("key", $"{ApiKey}");
restRequest.AddHeader("Authorization", "Bearer " + tokens["access_token"]);
restRequest.AddHeader("Accept", "application/json");
try
{
var response = await restClient.ExecuteAsync(restRequest);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
JObject calendarEvents = JObject.Parse(response.Content);
var allEvents = calendarEvents["items"].ToObject<List<EventModel>>();
return allEvents;
}
}
catch (Exception ex)
{
throw new Exception("Coulden't connect to google agenda.");
}
}
return null;
}
There are two ways to find out if there were changes to any events in your google calendar.
The first and less robust solution woudl be polling. You could run an events.list every five minutes or so and check for changes.
The second option would be to listen for changes by setting up a watch and listing for push notifications the way this works is you set up a web end point on your system that listens for calls from Google calendar. In the event a change is made to any of your events Google will notify this endpoint on your server and you will then know that you need to make a new call to the api to get any updates.
public Watch WatchEventAsync()
{
var refresToken = RetrieveRefreshTokenAndRevoke.RefreshToken();
if (refresToken == "ok")
{
var tokens = JObject.Parse(System.IO.File.ReadAllText(ConstantJsonFileLink.TOKEN));
var restClient = new RestClient();
var restRequest = new RestRequest();
restClient.BaseUrl = new System.Uri("https://www.googleapis.com/calendar/v3/calendars/Primary/events/watch");
Watch watch = new Watch();
watch.Id = CalendarId;
watch.Token = refresToken;
watch.Type = "webhook";
watch.Params = new Watch.Param { Ttl = "604800" };
var model = JsonConvert.SerializeObject(watch, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
restRequest.AddQueryParameter("key", $"{ApiKeys}");
restRequest.AddHeader("Authorization", "Bearer " + tokens["access_token"]);
restRequest.AddHeader("Accept", "application/json");
restRequest.AddHeader("Content-Type", "application/json; charset=utf-8");
restRequest.AddParameter("application/json", model, ParameterType.RequestBody);
try
{
var restResponse = restClient.Post(restRequest);
if (restResponse.StatusCode == System.Net.HttpStatusCode.OK)
{
JObject watchEvents = JObject.Parse(restResponse.Content);
return watchEvents.ToObject<Watch>();
}
}
catch (Exception ex)
{
throw new Exception("Coulden't Create an event in google agenda.");
}
}
return null;
}
// I have this for the moment
I've been trying to use RestSharp Library in order to make requests, but when I've tried to make a POST request this error keeps emerging!!
Here is the code:
private readonly string contentType = "application/json";
try
{
var restClient = new RestClient(new Uri(InvoiceExpressURLS.URL_createClient));
string clientJsonRequest =
JsonConvert.SerializeObject(
JsonConvert.DeserializeObject("{\"client\":" + JsonConvert.SerializeObject(newClient) + "}")
);
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Content-Type", contentType);
request.AddJsonBody(clientJsonRequest);
var restResponse = await restClient.ExecuteTaskAsync<object>(request);
if (restResponse.IsSuccessful)
{
response.responseObject = restResponse.Data;
response.responseMessage = string.Format("The client \"{0}\" was successfuly created.", newClient.name);
}
else
{
response.responseStatus = restResponse.StatusCode;
response.responseMessage = restResponse.ErrorMessage;
}
}
catch (Exception e)
{
response.responseStatus = HttpStatusCode.InternalServerError;
response.responseMessage = e.Message;
response.responseObject = e;
}
I want to add a record to the json service in my application. How can I do this via Service Url. Here is my code.
CustomerModel customer = new CustomerModel();
customer.Name = entryCompanyName.Text;
customer.Title = entryCompanyTitle.Text;
customer.PhoneNumber = entryTelephone.Text;
customer.FaxNumber = entryFax.Text;
customer.Email = entryEmail.Text;
customer.CityId = 6444;
string json = JsonConvert.SerializeObject(customer);
string sContentType = "application/json";
string path = "service url";
HttpClient Client = new HttpClient();
var task = Client.PostAsync(path, new StringContent(json.ToString(), Encoding.UTF8, sContentType));
I'm trying M. Wiśnicki's solution, but I took this error
I did not get an error when I added System.net :( Where do i make mistakes?
This worked for me
public static async Task<string> PostEntityToApi<T>(string yourMethodUrl, T yourModel)
{
try
{
if (_httpClient == null)
{
_httpClient = new HttpClient { BaseAddress = new Uri(yourWebSiteUrl) };
}
var stringContentInput = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(new Uri(yourWebSiteUrl. + apiUrl), stringContentInput);
if (!response.IsSuccessStatusCode)
{
throw new Exception(response.StatusCode.ToString());
}
var stringAsync = await response.Content.ReadAsStringAsync();
LoggingManager.Error("Received error response: " + stringAsync);
return stringAsync;
}
catch (Exception exception)
{
return null;
}
}
You can use WebRequest, this sample working for me, i use it in my app.
This is System.Net.WebRequest class, here you find doc.
public async Task<string> PostSample(object data, string uri)
{
// Create an HTTP web request using the URL:
var request = (HttpWebRequest) WebRequest.Create(new Uri(uri));
request.ContentType = "application/json";
request.Method = "POST";
var itemToSend = JsonConvert.SerializeObject(data);
using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
{
streamWriter.Write(itemToSend);
streamWriter.Flush();
streamWriter.Dispose();
}
// Send the request to the server and wait for the response:
using (var response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (var stream = response.GetResponseStream())
{
var reader = new StreamReader(stream);
var message = JsonConvert.DeserializeObject<string>(reader.ReadToEnd());
return message;
}
}
}
How I can convert my traditional HttpWebRequest "POST" call with Async / Await pattern, Here with this I am attaching my current code, Any one please help me to convert this code using Async / Await pattern for windows phone 8.
public void GetEnvironmentVariables(Action<Credentials> getResultCallback, Action<Exception> getErrorCallback)
{
CredentialsCallback = getResultCallback;
ErrorCallback = getErrorCallback;
var uri = new Uri(BaseUri);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
var jsonObject = new JObject
{
new JProperty("apiKey",_api),
new JProperty("affiliateId",_affid),
};
var serializedResult = JsonConvert.SerializeObject(jsonObject);
byte[] requestBody = Encoding.UTF8.GetBytes(serializedResult);
request.BeginGetRequestStream(GetRequestStreamCallback, new object[] { request, requestBody });
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
var request = (HttpWebRequest)((object[])asynchronousResult.AsyncState)[0];
using (var postStream = request.EndGetRequestStream(asynchronousResult))
{
var byteArray = (byte[])((object[])asynchronousResult.AsyncState)[1];
// Write to the request stream.
postStream.Write(byteArray, 0, byteArray.Length);
}
request.BeginGetResponse(GetResponseCallback, request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
var request = (HttpWebRequest)asynchronousResult.AsyncState;
try
{
var response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
Credentails = JsonConvert.DeserializeObject<Credentials>(responseString);
if (Credentails != null && string.IsNullOrEmpty(Credentails.Err))
CredentialsCallback(Credentails);
else
{
if (Credentails != null)
ErrorCallback(new Exception(string.Format("Error Code : {0}", StorageCredentails.Err)));
}
}
}
catch (WebException we)
{
var reader = new StreamReader(we.Response.GetResponseStream());
string responseString = reader.ReadToEnd();
Debug.WriteLine(responseString);
ErrorCallback(we);
}
}
Since Windows Phone 8 doesn't seem to offer the TAP methods you need such as GetRequestStreamAsync the first thing to do is write a little wrapper to provide them for yourself:
public static class WebRequestAsyncExtensions
{
public static Task<Stream> GetRequestStreamAsync(this WebRequest request)
{
return Task.Factory.FromAsync<Stream>(
request.BeginGetRequestStream, request.EndGetRequestStream, null);
}
public static Task<WebResponse> GetResponseAsync(this WebRequest request)
{
return Task.Factory.FromAsync<WebResponse>(
request.BeginGetResponse, request.EndGetResponse, null);
}
}
Note the use of Task.Factory.FromAsync - this is the preferred way to get an await-friendly wrapper around an APM-based async API such as those offered by WebRequest. This is far more efficient than using Task.Factory.StartNew as suggested by someone else, because that would spin up a new thread, whereas this won't need to.
With this in place, you can now write your code in the same way you would on platforms where these TAP-style methods are available (e.g. Windows 8 store apps, desktop apps, etc.):
public async Task GetEnvironmentVariablesAsync(Action<Credentials> getResultCallback, Action<Exception> getErrorCallback)
{
CredentialsCallback = getResultCallback;
ErrorCallback = getErrorCallback;
var uri = new Uri(BaseUri);
var request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
var jsonObject = new JObject
{
new JProperty("apiKey",_api),
new JProperty("affiliateId",_affid),
};
var serializedResult = JsonConvert.SerializeObject(jsonObject);
byte[] requestBody = Encoding.UTF8.GetBytes(serializedResult);
// ASYNC: using awaitable wrapper to get request stream
using (var postStream = await request.GetRequestStreamAsync())
{
// Write to the request stream.
// ASYNC: writing to the POST stream can be slow
await postStream.WriteAsync(requestBody, 0, requestBody.Length);
}
try
{
// ASYNC: using awaitable wrapper to get response
var response = (HttpWebResponse) await request.GetResponseAsync();
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
// ASYNC: using StreamReader's async method to read to end, in case
// the stream i slarge.
string responseString = await reader.ReadToEndAsync();
Credentails = JsonConvert.DeserializeObject<Credentials>(responseString);
if (Credentails != null && string.IsNullOrEmpty(Credentails.Err))
CredentialsCallback(Credentails);
else
{
if (Credentails != null)
ErrorCallback(new Exception(string.Format("Error Code : {0}", StorageCredentails.Err)));
}
}
}
catch (WebException we)
{
var reader = new StreamReader(we.Response.GetResponseStream());
string responseString = reader.ReadToEnd();
Debug.WriteLine(responseString);
ErrorCallback(we);
}
}
Note the four lines with // ASYNC: comments - these show where I've made changes. I've collapsed your method down to one, because that's a) possible once you're using async and await and b) much easier than trying to pass things from one method to the next using state arguments.
Notice that the second and fourth of these actually makes async some things you were previously doing synchronously: writing data into the request stream, and reading data out of the response stream. For a small request this probably doesn't matter, but if large amounts of data are being transferred, a synchronous call to Write or ReadToEnd may block. Fortunately, although Windows Phone 8 appears to be missing the TAP methods on WebRequest, it does offer them on Stream and StreamReader so this works without needing to write any extension methods.
I'm new to the community, so here goes my first post. In this case, you can return anytype using a generic Task. This has worked well for me in the past.
Server Side
public class MyController : ApiController
{
public Task<string> PostAsync()
{
return Task.Factory.StartNew(() =>
{
return "populate me with any type and data, but change the type in the response signature.";
});
}
}
Client Side
public class HomeController : Controller
{
public Task<ViewResult> Index()
{
return Task.Factory.StartNew(() =>
{
var model = "use a provider, get some data, or something";
return View(model);
});
}
}
This should do the job:
public async void GetEnvironmentVariables(Action<Credentials> getResultCallback, Action<Exception> getErrorCallback) {
CredentialsCallback = getResultCallback;
ErrorCallback = getErrorCallback;
var uri = new Uri(BaseUri);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
var jsonObject = new JObject {
new JProperty("apiKey", _api),
new JProperty("affiliateId", _affid),
};
var serializedResult = JsonConvert.SerializeObject(jsonObject);
var requestBody = Encoding.UTF8.GetBytes(serializedResult);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBody, 0, requestBody.Length);
await GetResponse(request);
}
private async Task GetResponse(WebRequest request) {
Stream resStream = null;
try {
var response = await request.GetResponseAsync();
if (response == null) {
return;
}
resStream = response.GetResponseStream();
if (resStream == null) {
return;
}
var reader = new StreamReader(resStream);
var responseString = await reader.ReadToEndAsync();
Credentails = JsonConvert.DeserializeObject<Credentials>(responseString);
if (Credentails != null && string.IsNullOrEmpty(Credentails.Err)) {
CredentialsCallback(Credentails);
}
else {
if (Credentails != null) {
ErrorCallback(new Exception(string.Format("Error Code : {0}", StorageCredentails.Err)));
}
}
}
catch (WebException we) {
if (resStream != null) {
var reader = new StreamReader(resStream);
var responseString = reader.ReadToEnd();
Debug.WriteLine(responseString);
}
ErrorCallback(we);
}
}
I m trying to POST the request using RestSharp client as follows
I m passing the Auth Code to following function
public void ExchangeCodeForToken(string code)
{
if (string.IsNullOrEmpty(code))
{
OnAuthenticationFailed();
}
else
{
var request = new RestRequest(this.TokenEndPoint, Method.POST);
request.AddParameter("code", code);
request.AddParameter("client_id", this.ClientId);
request.AddParameter("client_secret", this.Secret);
request.AddParameter("redirect_uri", "urn:ietf:wg:oauth:2.0:oob");
request.AddParameter("grant_type", "authorization_code");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
client.ExecuteAsync<AuthResult>(request, GetAccessToken);
}
}
void GetAccessToken(IRestResponse<AuthResult> response)
{
if (response == null || response.StatusCode != HttpStatusCode.OK
|| response.Data == null
|| string.IsNullOrEmpty(response.Data.access_token))
{
OnAuthenticationFailed();
}
else
{
Debug.Assert(response.Data != null);
AuthResult = response.Data;
OnAuthenticated();
}
}
But i am getting response.StatusCode = Bad Request. Can anyone help me for how do i POST the request using Restsharp client.
My RestSharp POST method:
var client = new RestClient(ServiceUrl);
var request = new RestRequest("/resource/", Method.POST);
// Json to post.
string jsonToSend = JsonHelper.ToJson(json);
request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
try
{
client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
// OK
}
else
{
// NOK
}
});
}
catch (Exception error)
{
// Log
}
This way works fine for me:
var request = new RestSharp.RestRequest("RESOURCE", RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Json }
.AddBody(BODY);
var response = Client.Execute(request);
// Handle response errors
HandleResponseErrors(response);
if (Errors.Length == 0)
{ }
else
{ }
Hope this helps! (Although it is a bit late)
As of 2017 I post to a rest service and getting the results from it like that:
var loginModel = new LoginModel();
loginModel.DatabaseName = "TestDB";
loginModel.UserGroupCode = "G1";
loginModel.UserName = "test1";
loginModel.Password = "123";
var client = new RestClient(BaseUrl);
var request = new RestRequest("/Connect?", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(loginModel);
var response = client.Execute(request);
var obj = JObject.Parse(response.Content);
LoginResult result = new LoginResult
{
Status = obj["Status"].ToString(),
Authority = response.ResponseUri.Authority,
SessionID = obj["SessionID"].ToString()
};
it is better to use json after post your resuest like below
var clien = new RestClient("https://smple.com/");
var request = new RestRequest("index", Method.POST);
request.AddHeader("Sign", signinstance);
request.AddJsonBody(JsonConvert.SerializeObject(yourclass));
var response = client.Execute<YourReturnclassSample>(request);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
{
return Ok(response.Content);
}
I added this helper method to handle my POST requests that return an object I care about.
For REST purists, I know, POSTs should not return anything besides a status. However, I had a large collection of ids that was too big for a query string parameter.
Helper Method:
public TResponse Post<TResponse>(string relativeUri, object postBody) where TResponse : new()
{
//Note: Ideally the RestClient isn't created for each request.
var restClient = new RestClient("http://localhost:999");
var restRequest = new RestRequest(relativeUri, Method.POST)
{
RequestFormat = DataFormat.Json
};
restRequest.AddBody(postBody);
var result = restClient.Post<TResponse>(restRequest);
if (!result.IsSuccessful)
{
throw new HttpException($"Item not found: {result.ErrorMessage}");
}
return result.Data;
}
Usage:
public List<WhateverReturnType> GetFromApi()
{
var idsForLookup = new List<int> {1, 2, 3, 4, 5};
var relativeUri = "/api/idLookup";
var restResponse = Post<List<WhateverReturnType>>(relativeUri, idsForLookup);
return restResponse;
}
It's better to specify the Json data body.
var client = new RestClient("URL");
var request = new RestRequest("Resources",Method.POST);
request.RequestFormat = RestSharp.DataFormat.Json;
request.AddBody(new classname
{
id = value1;
Name = "";
});
var response = client.Execute(request);
Check statusCode from response.
Always ensure that status code should be OK.