I am calling the following function to get access token for retrieving Twitter user profile using REST Api.
public async Task<string> GetAccessToken()
{
try
{
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.twitter.com/oauth2/token ");
var customerInfo = Convert.ToBase64String(new UTF8Encoding().GetBytes(OAuthConsumerKey + ":" + OAuthConsumerSecret));
request.Headers.Add("Authorization", "Basic " + customerInfo);
request.Content = new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded");
//program exits at this point
HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
string json = await response.Content.ReadAsStringAsync();
var serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>(json);
return item["access_token"];
}
catch (Exception ex)
{
MessageBox.Show("In Retrieving access token : " + ex.ToString());
}
}
The program exits/terminates without retrieving a response at the point HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
is called.
This is the parent function which calls GetAccessToken()
public async Task getUserProfile(string userName)
{
try
{
if (accessToken == null)
{
accessToken = await GetAccessToken().ConfigureAwait(false);
}
var request = new HttpRequestMessage(HttpMethod.Get, string.Format(" https://api.twitter.com/1.1/users/show.json?screen_name={0}", userName));
request.Headers.Add("Authorization", "Bearer " + accessToken);
var httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
var jsonString = await response.Content.ReadAsStringAsync();
var serializer = new JavaScriptSerializer();
dynamic jsonObj = serializer.Deserialize<object>(jsonString);
}
catch (Exception ex)
{
if (DEBUG)
{
MessageBox.Show("In Retrieving user profile from twitter : " + ex.ToString());
}
}
}
I am unable to catch an exception as to why the program exits at GetAccessToken() or getUserProfile(). But the code executes successfully and retrieves an HttpResponseMessage if getUserProfile() has Task<IEnumerable<string>>
as return type. Why does this problem occur? How can the exception be caught?
Your application exits permaturely because you are not waiting for getUserProfile()
to be completed. You can mark getTwitterInfo
as async similar to the others or tell it to wait for the task to finish
public async Task getTwitterInfo() {
var twitter = new Twitter("consumerKey","consumerSecret");
await twitter.getUserProfile(userName);
}
OR
public void getTwitterInfo() {
var twitter = new Twitter("consumerKey","consumerSecret");
var task = twitter.getUserProfile(userName);
var result = task.WaitAndUnwrapException();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With