call to API works async, but I need it run sync - c#

I've been trying for a day to make this work synchronously, not async.
Here is the code that works:
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = false;
handler.Credentials = new NetworkCredential(username, password);
HttpClient clientPageFirst = new HttpClient(handler);
HttpResponseMessage responsePageFirst = await clientPageFirst.GetAsync(fullURL);
HttpContent contentPageFirst = responsePageFirst.Content;
string resultPageFirst = await contentPageFirst.ReadAsStringAsync();
Console.WriteLine(resultPageFirst);
It's for a C# console app, and there is another call there to another platform's API which works synchronously, but it uses tokens in the header to validate, not a network credential like this one (calling a local on premise CRM URL).
Can someone please help me change the
HttpResponseMessage responsePageFirst = await clientPageFirst.GetAsync(fullURL);
line so it is synchronous?
T.I.A.

Try this
HttpResponseMessage responsePageFirst = clientPageFirst.GetAsync("fullURL").Result;

Related

UWP http client delay in getting response

I found this peculiar behaviour of UWP HttpClient.
For a simple get call of WCF service is taking time almost more than 100 seconds(happens for first few calls). I observed that the same service is way too faster in iOS and rest client.
Attaching the code, Please let me know, if i doing wrong.
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.UseCookies = true;
var client = new HttpClient(clientHandler);
client.Timeout = TimeSpan.FromSeconds(100);
client.DefaultRequestHeaders.Add("Accept", "application/json");
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get,
requestUri);
var response = await client.SendAsync(httpRequestMessage);
//Between these lines there is a delay, it doesnt fire time out
also. I tried with HttpCompletionOption. No luck
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
}
Any help will be really appreciated.
Thanks and Regards,
Rummy

Calling Asp.Net Web API endpoint from Azure function

I am trying to develop following scenario using Azure functions.
I have developed Asp.Net Web API which handles the Database related operation. Now, I want to implement a scheduler like functionality which will run once a day and will clean up junk data from database. I've created an endpoint for that in my Web API but I want to execute it on regular basis so I think to implement scheduler using Azure function's TimerTrigger function, is there any way to call my web api's endpoint in TimerTrigger function.
How to handle my api's authentication in Azure function?
Thanks
Update:
Based on mikhail's answer, finally I got the token using following code:
var client = new HttpClient();
client.BaseAddress = new Uri(apirooturl);
var grant_type = "password";
var username = "username";
var password = "password";
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", grant_type),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password)
});
var token = client.PostAsync("token", formContent).Result.Content.ReadAsAsync<AuthenticationToken>().Result;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.token_type, token.access_token);
var response = await client.GetAsync(apiendpoint);
var content = await response.Content.ReadAsStringAsync();
Azure Function is running in a normal Web App, so you can do pretty much anything there. Assuming you are on C#, the function body might looks something like
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
var response = await client.GetAsync(url);
var content = await response.Content.ReadAsStringAsync();
You may be better off putting the entire database cleanup logic in the function and making it timer triggered, that way you keep your API out of it altogether.

Asynchronous API call, System.Threading.Tasks.TaskCanceledException: A task was canceled

I'm working on an application I inherited that makes asynchronous calls to an API. The application sends about 60 asynchronous requests to the API, and then retrieves them as they are ready. The API returns the results in the form of a zip archive object. It was using the following (abbreviated) code to retrieve results from the API, but this kept throwing intermittent System.Threading.Tasks.TaskCanceledException errors
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
Stream responseStream = response.Content.ReadAsStreamAsync().Result;
responseStream.Seek(0, 0);
za = new ZipArchive(responseStream, ZipArchiveMode.Read);
So I attempted to fix this by using await, and implemented the following methods, but I'm still getting the same errors. I can check the status of my API requests through a website, so I know they're not being canceled by the API. The requests that fail, fail in less than 5 minutes, so I know it's also not because the timeout value is too low on the HTTPClient. This is my first crack at asynchronous programming so if anyone can help with this, it would be greatly appreciated. Thanks.
public async Task<ZipArchive> GetExport(SourceTable sourceTable)
{
ZipArchive zipArchive = null;
switch (GetResultStatus(sourceTable))
{
case null:
break;
case "Completed":
{
zipArchive = await RetrieveResult(sourceTable);
}
break;
}
return zipArchive;
}
private async Task<ZipArchive> RetrieveResult(SourceTable sourceTable)
{
Export export = sourceTable.exports[0];
ZipArchive za = await RetrieveResultAsync(export);
return za;
}
private async Task<ZipArchive> RetrieveResultAsync(Export export)
{
ZipArchive za = null;
var credentials = new NetworkCredential(userName, password);
HttpClientHandler handler = new HttpClientHandler { Credentials = credentials };
HttpClient client = new HttpClient(handler);
client.Timeout.Add(new TimeSpan(0, 5, 0)); //5 minutes
HttpResponseMessage response = await client.GetAsync(restURL + "file/" + export.FileId);
response.EnsureSuccessStatusCode();
Stream responseStream = await response.Content.ReadAsStreamAsync();
responseStream.Seek(0, 0);
za = new ZipArchive(responseStream, ZipArchiveMode.Read);
return za;
}
UPDATE: After adding some more logging to this code I found out that it was indeed a timeout issue, and that I wasn't setting the timeout value correctly. When setting the value like below, it resolved the issues (of course with setting a higher timeout value than the default)
var credentials = new NetworkCredential(userName, password);
HttpClientHandler handler = new HttpClientHandler { Credentials = credentials };
HttpClient client = new HttpClient(handler);
client.Timeout = TimeSpan.FromMinutes(httpClientTimeout);

Get application to wait until Variables are updated

I am working with OAuth at the moment. The problem with the current code is it doesn't wait until the user allows the application on the site and gets the proper key and secret. I was using a threading type wait but, sometimes it not long enough...some users are slower then others. I have attached a snippet of my code. What I would like to know is where to insert a while statement, or should I even use that ?
public OAuthToken GetRequestToken(Uri baseUri, string consumerKey, string consumerSecret)
{
var uri = new Uri(baseUri, "oauth/request_token");
uri = SignRequest(uri, consumerKey, consumerSecret);
var request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Get;
var response = request.GetResponse();
var queryString = new StreamReader(response.GetResponseStream()).ReadToEnd();
var parts = queryString.Split('&');
var token = parts[1].Substring(parts[1].IndexOf('=') + 1);
var secret = parts[0].Substring(parts[0].IndexOf('=') + 1);
return new OAuthToken(token, secret);
}
You should switch over to the newer System.Net.Http and System.Net.Http.WebRequest libraries that come with .NET now. These all use the new async programming stuff that is available with .NET 4.5.
You can call a request (returning you a task object that you can wait on) and automatically pause the thread for the response. The UI won't respond, as normal. That is probably the easiest thing to do if you don't understand how the new async and await keywords work. For more information on them, see http://msdn.microsoft.com/en-us/library/hh191443.aspx
Here is your code doing things with the new libraries:
using System.Net.Http;
public OAuthToken GetRequestToken(Uri baseUri, string consumerKey, string consumerSecret)
{
var uri = new Uri(baseUri, "oauth/request_token");
uri = SignRequest(uri, consumerKey, consumerSecret);
var message = new HttpRequestMessage(new HttpMethod("GET"), uri);
var handler = new WebRequestHandler();
var client = new HttpClient(handler);
// Use the http client to send the request to the server.
Task<HttpResponseMessage> responseTask = client.SendAsync(message);
// The responseTask object is like a wrapper for the other task thread.
// We can tell this task object that we want to pause our current thread
// and wait for the client.SendAsync call to finish.
responseTask.Wait();
// - Once that thread finishes, and the code continues on, we need to
// tell it to read out the response data from the backing objects.
// - The responseTask.Result property represents the object the async task
// was wrapping, we want to pull it out, then use it and get the content
// (body of the response) back.
// - Getting the response actually creates another async task (the
// .ReadAsStringAsync() call) but by accessing the .Result
// property, it is as if we called .ReadAsStringAsync().Wait(); Except that
// by using Result directly, we not only call Wait() but we get the resulting,
// wrapped object back. Hope that didn't confuse you much :)
var queryString = responseTask.Result.Content.ReadAsStringAsync().Result;
// And all your other normal code continues.
var parts = queryString.Split('&');
var token = parts[1].Substring(parts[1].IndexOf('=') + 1);
var secret = parts[0].Substring(parts[0].IndexOf('=') + 1);
return new OAuthToken(token, secret);
}
Why Not use a modal pop up and then call the authentication class on the submit button

WinRt C# HttpClient SendAsync does not return

I am creating a Metro App that makes a HTTP Post request to a webserver to obtain JSON data. Initially I use the same code to logon to the web server and the HTTP Post request returns fine. It is only later that I run into an issue where the code hangs when I call the SendAsync() method.
I used wireshark to view the network traffic and I did see the server returning a response. So I am not sure why the call is not completing. Anyone have any ideas?
Here is the code I am using:
var httpHandler = new HttpClientHandler();
httpHandler.CookieContainer = __CookieJar;
var httpClient = new HttpClient(httpHandler);
UserAgentDetails userAgent = UserAgentDetails.GetInstance();
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent.UserAgentString);
foreach (string key in __colHeaders)
httpClient.DefaultRequestHeaders.Add(key, __colHeaders[key]);
var content = new StringContent(postData);
if (contentType != null && contentType.Length > 0)
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
var requestMsg = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
requestMsg.Content = content;
requestMsg.Headers.TransferEncodingChunked = true;
var responseMsg = await httpClient.SendAsync(requestMsg);
// no return from method after logon

Categories

Resources