Reputation: 1088
I trying to get Request Token from Trello with RestSharp. I got token only in request thread, but dont able to save it in variable of my app. There some code:
private async void GetToken()
{
app.Client.Authenticator = OAuth1Authenticator.ForRequestToken(app.ConsumerKey, app.ConsumerSecret);
var request = new RestRequest("OAuthGetRequestToken", Method.POST);
app.Client.ExecuteAsync(request, HandleResponse);
}
private void HandleResponse(IRestResponse restResponse)
{
var Response = restResponse;
MessageBox.Show(Response.Content);
QueryString qs = new QueryString(Response.Content);
app.OAuthToken = qs["oauth_token"];
app.OAuthTokenSecret = qs["oauth_token_secret"];
app.Verifier = qs["verifier"];
MessageBox.Show(app.OAuthToken); //got token here, but after
MessageBox.Show(app.OAuthTokenSecret); //I don`t have anything in this variables
}
Have you any ideas?
Upvotes: 4
Views: 409
Reputation: 1088
Solution to this problem is to create class that enable me to create synchronous request. There is code of this class:
public static class RestClientExtensions
{
public static Task<IRestResponse> ExecuteTask(this IRestClient client, RestRequest request)
{
var TaskCompletionSource = new TaskCompletionSource<IRestResponse>();
client.ExecuteAsync(request, (response, asyncHandle) =>
{
if (response.ResponseStatus == ResponseStatus.Error)
TaskCompletionSource.SetException(response.ErrorException);
else
TaskCompletionSource.SetResult(response);
});
return TaskCompletionSource.Task;
}
}
And now my code looks like this:
private async void GetToken()
{
app.Client.Authenticator = OAuth1Authenticator.ForRequestToken(app.ConsumerKey, app.ConsumerSecret);
RestRequest request = new RestRequest("OAuthGetRequestToken", Method.POST);
IRestResponse restResponse = await app.Client.ExecuteTask(request);
HandleResponse(restResponse);
GetAccesToken();
}
private void HandleResponse(IRestResponse response)
{
var Response = response;
System.Diagnostics.Debug.WriteLine(Response.Content);
QueryString qs = new QueryString(Response.Content);
app.OAuthToken = qs["oauth_token"];
app.OAuthTokenSecret = qs["oauth_token_secret"];
System.Diagnostics.Debug.WriteLine(app.OAuthToken);
System.Diagnostics.Debug.WriteLine(app.OAuthTokenSecret);
}
And after the method HandleResponse(response); performed, I have the token and token secret in my app class. I still believe that there must be better solution for this problem, but it is the only one that I know.
Upvotes: 4