0

I want to connect to Google+ API, get access_token and then do some other stuffs with it. I made a Windows Form with the respective button. But I can't get back to the program window after getting the token. Must also say that I'm noobie in asynchronous programming.

I used that article to get know how to authenticate - http://www.daimto.com/googleplusapi-search-csharp/. So my code is:

using System;
using System.Net;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Plus.v1;
using Google.Apis.Services;

(...)

static string client_id = "XXXX.apps.googleusercontent.com";
static string client_secret = "yyyy";
ClientSecrets secrets = new ClientSecrets { ClientId = client_id, ClientSecret = client_secret };
string[] scopes = new string[] { PlusService.Scope.PlusLogin, PlusService.Scope.UserinfoEmail, PlusService.Scope.UserinfoProfile };

private void button1_Click(object sender, EventArgs e)
{
    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, scopes, Environment.UserName, CancellationToken.None).Result;
    var service = new PlusService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "disserApp",
    });
}

After clicking the button, all goes well - browser opened, Google authorisation page loaded. I typed my credentials in, gave the permissions etc. Finally, the blank page with the text like "Access token has been got. You may close that window." I closed the browser window, and went back to my program. But it was frozen! The button1 still displayed as ckickining etc. Looks like the program waits for a signal of asynchronous operation finish. What am I doing wrong? Thank you.

serhiy1994
  • 59
  • 8
  • 1
    At the very least you should be using `private async void button1_Click` and `UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, scopes, Environment.UserName, CancellationToken.None);` – Camilo Terevinto Dec 22 '18 at 01:24
  • @CamiloTerevinto thanks, i'll try it tomorrow. – serhiy1994 Dec 22 '18 at 02:11
  • @CamiloTerevinto yes, it works, thank you very much. To be honest, I was little confused because that function was written as non-async in the docs I provided. – serhiy1994 Dec 22 '18 at 15:10
  • No worries. You can check more about that here: https://stackoverflow.com/questions/19415646/should-i-avoid-async-void-event-handlers – Camilo Terevinto Dec 22 '18 at 15:12

0 Answers0