c# Background Task only runs 1 time? - c#

Hi so i wane do a background task with my code but the code only runs 1 time when i startup my application. i have put a break point already in my infinity loop but that doesn't get triggerd. So i was wondering what can be the issue. my task is doing a test if my data is coming in my google calendar. Its a check. I hope somebody can help me out.
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
string DbConnectionString = _configuration.GetValue<string>("Site:ConnectionString");
using (IDbConnection conn = OpenConnection(DbConnectionString))
{
List<GoogleAccess> googleCredentials = conn.Query<Domain.GoogleAccess>("Select g.Id, g.CalendarId, g.RefreshToken, convert(nvarchar(36), g.CompanyUserId) as CompanyUserId from [dbo].[googleAccess] g", null, commandType: CommandType.Text).ToList();
// list with all users
foreach (var credential in googleCredentials.Where(e => e.RefreshToken is not null).ToList())
{
var accessToken = RefreshToken(credential.RefreshToken);
// search all events Where that contain CompanyUserTreatmentId From that user
var allReservations = await TurnUp.Admin.Infrastructure.RestAPI.Reservation.GetAll(new Models.RestAPI.Reservation.PostModel.GetAllReservationPostModel() { });
var covertedList = new List<EventModel>();
foreach (var reservation in allReservations.result.items.Where(e => e.isCancelled == false).ToList())
{
covertedList.Add(new EventModel
{
Id = reservation.id.ToString(),
Description = reservation.description,
Start = new EventDateTime { DateTime = DateTime.Parse(reservation.startTime.ToString()).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"), TimeZone = "Europe/Zurich" },
End = new EventDateTime { DateTime = DateTime.Parse(reservation.endTime.ToString()).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"), TimeZone = "Europe/Zurich" },
Summary = reservation.description
});
}
//Retrieving all Google Events from google api
var allGoogleEvents = new List<EventModel>();
RestClient restClient = new RestClient(new Uri("https://www.googleapis.com/calendar/v3/calendars/primary/events"));
RestRequest restRequest = new RestRequest();
//Send parameters with the request
restRequest.AddQueryParameter("key", $"{ApiKeys}");
restRequest.AddParameter("maxResults", 2500);
restRequest.AddParameter("OrderBy", "startTime");
restRequest.AddParameter("showDeleted", "false");
restRequest.AddParameter("timeMin", DateTime.UtcNow.AddMonths(-1).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"));
restRequest.AddParameter("timeMax", DateTime.UtcNow.AddMonths(6).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"));
restRequest.AddHeader("Authorization", "Bearer " + accessToken);
restRequest.AddHeader("Accept", "application/json");
try
{
//Get request to server
var response = restClient.Get(restRequest);
//check if response is ok
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//change response to an class that can be used
JObject calendarEvents = JObject.Parse(response.Content);
var test = calendarEvents["nextSyncToken"].ToString();
allGoogleEvents = calendarEvents["items"].ToObject<List<EventModel>>();
}
}
catch (Exception ex)
{
throw new Exception("Coulden't connect to google agenda.");
}
//list with reservations that arn't in google
var newList = covertedList.Except(allGoogleEvents).Concat(allGoogleEvents.Except(covertedList));
//var newList = googleEventList.Except(covertedList).Concat(covertedList.Except(googleEventList));
foreach (var ev in newList)
{
var restClientForAddingEvents = new RestClient();
var restRequestForAddingEvents = new RestRequest();
restClientForAddingEvents.BaseUrl = new System.Uri($"https://www.googleapis.com/calendar/v3/calendars/{credential.CalendarId}/events");
EventModel newEvent = new EventModel();
newEvent.Start.DateTime = DateTime.Parse(ev.Start.DateTime).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK");
newEvent.End.DateTime = DateTime.Parse(ev.End.DateTime).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK");
newEvent.Description = ev.Description;
newEvent.Id = Guid.NewGuid().ToString().Replace("-", "");
var model = JsonConvert.SerializeObject(newEvent, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
//Send parameters with the request
restRequest.AddQueryParameter("key", $"{ApiKeys}");
restRequest.AddHeader("Authorization", "Bearer " + accessToken);
restRequest.AddHeader("Accept", "application/json");
restRequest.AddHeader("Content-Type", "application/json; charset=utf-8");
restRequest.AddParameter("application/json", model, ParameterType.RequestBody);
//RestClient restClient = new RestClient(new Uri($"https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events/" + ev.Id.ToString().Replace("-", "")));
//RestRequest restRequest = new RestRequest();
////Send parameters with the request
//restRequest.AddQueryParameter("key", $"{ApiKeys}");
//restRequest.AddHeader("Authorization", "Bearer " + accestoken);
//restRequest.AddHeader("Accept", "application/json");
try
{
//Post request to server
var restResponse = restClient.Post(restRequest);
//check if response is ok
if (restResponse.StatusCode == System.Net.HttpStatusCode.OK)
{
}
}
catch (Exception ex)
{
throw new Exception("Coulden't Create an event in google agenda.");
}
}
}
}
await Task.Delay(5000, stoppingToken);
}
}

Related

c# retrieve google agenda when an updat happens

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

Sending Multiple Files in a single Request to API

I am fairly new to API's. I am writing a "simple" API that will convert .docx files to .pdf files and return the pdf's back to the client for saving. I have the code working for a single file but I wanted to code the API to handle multiple files in a single request. Now the API is not receiving the request. I can provide the working code with a single file if requested.
I am sure I am missing something simple. Please see below and see if anyone see's something that I could be doing better or why the API is not receiving the POST request.
Client:
List<string> documents = new List<string>();
private async void btnConvert_Click(object sender, EventArgs e)
{
using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
{
client.BaseAddress = new Uri(BaseApiUrl);
//client.DefaultRequestHeaders.Add("Accept", "application/json");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, BaseApiUrl + ApiUrl);
foreach (string s in docPaths)
{
byte[] bte;
bte = File.ReadAllBytes(docPath);
string data = JsonConvert.SerializeObject(Convert.ToBase64String(bte));
documents.Add(data);
}
using (var formData = new MultipartFormDataContent())
{
foreach (string s in documents)
{
//add content to form data
formData.Add(new StringContent(s, Encoding.UTF8, "application/json"));
}
// List of Http Reponse Messages
var conversions = documents.Select(doc => client.PostAsync(BaseApiUrl + ApiUrl, formData)).ToList();
//Wait for all the requests to finish
await Task.WhenAll(conversions);
//Get the responses
var responses = conversions.Select
(
task => task.Result
);
foreach (var r in responses)
{
// Extract the message body
var s = await r.Content.ReadAsStringAsync();
SimpleResponse res = JsonConvert.DeserializeObject<SimpleResponse>(s);
if (res.Success)
{
byte[] pdf = Convert.FromBase64String(res.Result.ToString());
// Save the PDF here
}
else
{
// Log issue
}
}
}
}
API: This is not getting the request so this function is not complete. I need to figure out why it not being hit.
[HttpPost]
public async Task<List<SimpleResponse>> Post([FromBody]string request)
{
var response = new List<SimpleResponse>();
Converter convert = new Converter();
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var requestContents in provider.Contents)
{
try
{
//var result = convert.CovertDocToPDF(requestContents, WebConfigurationManager.AppSettings["tempDocPath"], WebConfigurationManager.AppSettings["tempPdfPath"]);
//response.Add(new SimpleResponse() { Result = result, Success = true });
}
catch (Exception ex)
{
response.Add(new SimpleResponse() { Success = false, Exception = ex, Errors = new List<string>() { string.Format("{0}, {1}", ex.Message, ex.InnerException?.Message ?? "") } });
}
}
return response;
}
SimpleResponse Model:
public class SimpleResponse
{
public object Result { get; set; }
public bool Success { get; set; }
public Exception Exception { get; set; }
public List<string> Errors { get; set; }
}
UPDATE
Did suggestions made by #jdweng and I am getting a null response on the API POST
Client:
public async void btnConvert_Click(object sender, EventArgs e)
{
using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
{
client.BaseAddress = new Uri(BaseApiUrl);
client.DefaultRequestHeaders.Add("Accept", "application/json");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//application/json
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, BaseApiUrl + ApiUrl);
List<string> requests = new List<string>();
byte[] bte;
// New Code per the suggestion
foreach (string s in docPaths)
{
bte = File.ReadAllBytes(s);
requests.Add(Convert.ToBase64String(bte));
}
// End new code
string data = JsonConvert.SerializeObject(requests);
request.Content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response1 = client.PostAsync(BaseApiUrl + ApiUrl, request.Content).Result;
Task<string> json = response1.Content.ReadAsStringAsync();
SimpleResponse response = JsonConvert.DeserializeObject<SimpleResponse>(json.Result);
//result = JsonConvert.DeserializeObject(result).ToString();
if (response.Success)
{
bte = Convert.FromBase64String(response.Result.ToString());
if (File.Exists(tempPdfPath))
{
File.Delete(tempPdfPath);
}
System.IO.File.WriteAllBytes(tempPdfPath, bte);
}
else
{
}
}
}
Server:
[HttpPost]
public async Task<List<SimpleResponse>> Post([FromBody]string request)
{
// The request in NULL....
List<SimpleResponse> responses = new List<SimpleResponse>();
List<string> resp = JsonConvert.DeserializeObject(request) as List<string>;
try
{
Converter convert = new Converter();
foreach (string s in resp)
{
var result = convert.CovertDocToPDF(request, WebConfigurationManager.AppSettings["tempDocPath"], WebConfigurationManager.AppSettings["tempPdfPath"]);
responses.Add(new SimpleResponse()
{
Result = result,
Success = true
});
}
}
catch (Exception ex)
{
responses.Add(new SimpleResponse()
{
Result = null,
Success = true,
Exception = ex,
Errors = new List<string>() { string.Format("{0}, {1}", ex.Message, ex.InnerException?.Message ?? "") }
});
}
return responses;
}
I have finally solved the issues and can now successfully send multiple .docx files to the API and get the .pdf files back from the API. Now I want to figure out how to send each files on it's own thread instead of all together.
Client:
public async void btnConvert_Click(object sender, EventArgs e)
{
using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
{
client.BaseAddress = new Uri(BaseApiUrl);
client.DefaultRequestHeaders.Add("Accept", "application/json");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, BaseApiUrl + ApiUrl);
List<string> requests = new List<string>();
byte[] bte;
foreach (string s in docPaths)
{
bte = File.ReadAllBytes(s);
requests.Add(Convert.ToBase64String(bte));
}
var data = JsonConvert.SerializeObject(requests);
request.Content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response1 = await client.PostAsync(BaseApiUrl + ApiUrl, request.Content);
Task<string> json = response1.Content.ReadAsStringAsync();
var response = JsonConvert.DeserializeObject<List<SimpleResponse>>(json.Result);
foreach (SimpleResponse sr in response)
{
if (sr.Success)
{
bte = Convert.FromBase64String(sr.Result.ToString());
string rs = RandomString(16, true);
string pdfFileName = tempPdfPath + rs + ".pdf";
if (File.Exists(pdfFileName))
{
File.Delete(pdfFileName);
}
System.IO.File.WriteAllBytes(pdfFileName, bte);
}
else
{
}
}
}
}
API:
[HttpPost]
public async Task<List<SimpleResponse>> Post([FromBody] List<string> request)
{
List<SimpleResponse> responses = new List<SimpleResponse>();
try
{
Converter convert = new Converter();
foreach (string s in request)
{
var result = convert.CovertDocToPDF(s, WebConfigurationManager.AppSettings["tempDocPath"], WebConfigurationManager.AppSettings["tempPdfPath"]);
responses.Add(new SimpleResponse()
{
Result = result,
Success = true
});
}
}
catch (Exception ex)
{
responses.Add(new SimpleResponse()
{
Result = null,
Success = true,
Exception = ex,
Errors = new List<string>() { string.Format("{0}, {1}", ex.Message, ex.InnerException?.Message ?? "") }
});
}
return responses;
}

How to mimic this using RESTSHARP C# restclient instead of using httpclient?

I am using httpclient to invoke a endpoint , this is working fine for me. But i need to invoke the endpoint using the restsharp restclient object. How can i do that? Here is the code that works for me using the http client postasync.
//Input Parameters and request headers
string userID = "testuser";
string memberId = "001";
string baseURL = "https://www.test.com";
string urlParameters ="TestServices/GetAll/{0}/{1}/{2}/{3}/{4}/{5}";
string contentType = "application/json";
string role = "USER";
string Caller = "PREVIEW";
string ticks = DateTime.Now.Ticks.ToString();
string systemId = "613e70b3-e3ec-4205-bcd6-094d6a9f7a41";
string encryptedToken = “XXXXXXXXXXXXXXXXXXXX”
string sessionID = "8303d34a-5c8a-4984-9bf9-4ba39be21352";
//data to be send as stringcontent
string postData = "{\"TheContentAreas\":[{\"ControlTypeID\":\"230c5669-aa0d-41bc-9069-559b5e7d0ece\",\"PlaceholderID\":\"a16a471e-9416-43fc-8ceb-fddb97509e0c\"}]}";
string response = string.Empty;
//call the end point
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseURL);
client.DefaultRequestHeaders.Add("Authorization", "XXXXXXXXXXXXXXXXXXXXXXX");
client.DefaultRequestHeaders.Add("Session", sessionID);
client.DefaultRequestHeaders.Add("EncryptedKey", encryptedToken);
try
{
HttpResponseMessage resp = client
.PostAsync(string.Format(urlParameters, role, systemId, Caller, ticks, userID, memberId),
new StringContent(postData, System.Text.Encoding.UTF8, "application/json")).Result;
if (resp.IsSuccessStatusCode)
{
response = resp.Content.ReadAsStringAsync().Result;
}
}
I spent some time working on it, here is my solution.
I created a generic service invoker class and called it from my main class.
//Main class calling the service invoker
try
{
var _restMethodInvoker = new RestEndPointInvoker();
var headers = new Dictionary<string, string>
{
{ "Authorization", "xxx" },
{ "Session", "xxx" } ,
{ "EncryptedKey", "xxx"}
};
var inputParameters = new Dictionary<string, string>
{
{ "Role", "MEMBER" },
{ "SystemID", "xxx" } ,
{ "Caller", "PREVIEW" } ,
{ "Ticks", "1234" } ,
{ "UserID", "TestUser" } ,
{ "MemberId", "TestMEmber" }
var request1 = new RestClientRequest
{
_apiMethod = "TestServices/GetAll/{Role}/{SystemID}/{Caller}/{Ticks}/{UserID}/{MemberId}",
_environmentType = "xx",
_inputParameters = inputParameters,
_requestHeaders = headers
};
var result1 = _restMethodInvoker.GetAsync<List<ReturnType>>(request1);
var result = result1.Result;
}
catch (Exception ex)
{
throw ex;
}
Rest Invoker class using restsharp
namespace RestServiceInvoker
{
public class RestEndPointInvoker : IRestEndPointInvoker
{
public RestEndPointInvoker()
{
_httpClient = new RestClient();
}
private void BuildRestClient(RestClientRequest request)
{
//Set the headers
foreach (var header in request._requestHeaders)
{
_httpClient.AddDefaultHeader(header.Key, header.Value);
}
}
public async Task<IRestResponse<T>> GetAsync<T>(RestClientRequest request) where T: new()
{
//Build the client object
BuildRestClient(request);
//Build request object
var restRequest = BuildRestReqestObject(request);
//var response11 = _httpClient.Execute<T>(restRequest);
var taskSource = new TaskCompletionSource<IRestResponse<T>>();
//Execute the request
_httpClient.ExecuteAsync<T>(restRequest, response =>
{
if (response.ErrorException != null)
taskSource.TrySetException(response.ErrorException);
else
taskSource.TrySetResult(response);
});
return await taskSource.Task;
}
private RestRequest BuildRestReqestObject(RestClientRequest requestObj)
{
var request = new RestRequest {Resource = requestObj._apiMethod};
if (requestObj._inputParameters == null || requestObj._inputParameters.Count <= 0) return request;
foreach (var inputParam in requestObj._inputParameters)
{
request.AddParameter(inputParam.Key, inputParam.Value, ParameterType.UrlSegment);
}
request.Method = Method.POST; //This could be parameterized from the client. For now we are only supporting get calls
//This would be sent as input parameter. Just was lazy to hardcode it here
string jsonToSend = #"xxxxxxxxxxx";
request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
return request;
}
}
}

Twitter API invalid or expired token

I'm trying to use the below code but for some reason I'm getting an invalid or expired token it seemed to work once but never again.
Any ideas? (consumerKey and consumerSecret are constants generated in the class.)
public ActionResult Index()
{
string twitterAccount = System.Configuration.ConfigurationManager.AppSettings["twitterAccount"];
JsonDeserializer jsonDeserializer = new JsonDeserializer();
var model = new TwitterVM.LandingModel();
var qs = GetToken();
string oauthToken = qs["oauth_token"];
string oauthTokenSecret = qs["oauth_token_secret"];
RestClient client = new RestClient("https://api.twitter.com/1.1")
{
Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, oauthToken, oauthTokenSecret)
};
RestRequest request = new RestRequest("statuses/user_timeline", Method.GET);
request.Parameters.Add(new Parameter()
{
Name = "screen_name",
Value = twitterAccount,
Type = ParameterType.GetOrPost
});
request.Parameters.Add(new Parameter()
{
Name = "count",
Value = 10,
Type = ParameterType.GetOrPost
});
request.Parameters.Add(new Parameter()
{
Name = "include_rts",
Value = true,
Type = ParameterType.GetOrPost
});
request.Parameters.Add(new Parameter()
{
Name = "include_entities",
Value = true,
Type = ParameterType.GetOrPost
});
IRestResponse response = client.Execute(request);
model.Tweets =
jsonDeserializer.Deserialize<List<TwitterVM.Tweet>>(response);
return View(model);
}
private NameValueCollection GetToken()
{
RestClient client = new RestClient("https://api.twitter.com") { Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret) };
//Do the auth shit...
RestRequest request = new RestRequest("oauth/request_token", Method.POST);
IRestResponse response = client.Execute(request);
return HttpUtility.ParseQueryString(response.Content);
}
Using Twitter's OAuth2 API (https://api.twitter.com/oauth2/token)
See https://dev.twitter.com/oauth/application-only for details....
var client = await CreateHttpClient("....", "....");
//don't dispose this client and use for subsequent API calls
var screenName = "....";
var count = 10;
var include_rts = true;
var url = $"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={screenName}&include_rts={include_rts}&count={count}";
var json = await client.GetStringAsync(url);
public static async Task<HttpClient> CreateHttpClient(string consumerKey, string consumerSecret)
{
var bearerToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(consumerKey + ":" + consumerSecret));
string url = "https://api.twitter.com/oauth2/token";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Basic " + bearerToken);
var resp = await client.PostAsync(url, new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded")).ConfigureAwait(false);
resp.EnsureSuccessStatusCode();
var result = await resp.Content.ReadAsStringAsync().ConfigureAwait(false);
var jObj = new JavaScriptSerializer().Deserialize<Dictionary<string,string>>(result);
if (jObj["token_type"] != "bearer") throw new Exception("Invalid Response From Twitter/OAuth");
client.DefaultRequestHeaders.Remove("Authorization");
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + jObj["access_token"]);
return client;
}

How to POST request using RestSharp

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.

Categories

Resources