0

I am working on a service which should be able to insert calendar Events into user calendars from various Google Apps domains using a service account. Everything works fine, however I came across a small issue while initialising the service using Google API. The initialisation as described in Google APIs looks something like this:

        string[] scopes = new string[] { CalendarService.Scope.Calendar };
        var certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
        try
        { 
            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL) 
                {
                    User = user,
                    Scopes = scopes
                }.FromCertificate(certificate));

            CalendarService service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
            });
            return service;
        }

        catch (Exception ex)
        {
            return null;
        }

The problem I am having is that I would like to be able to check if the CalendarService is connected before I actually try to insert any Event. However the provided code snippet does not run any underlying network communication - it just initialise the service. The whole authentication process happens while executing events e.g.: var eventResult = newEventRequest.Execute();

Is there any nice way how to check if the service is actually connected before creating any events (check for HttpRequestException, TokenResponseException, etc.)? The only solution I can think of would be to insert a simple event and then delete it right after or not use the Google API at all.

Thank you in advance.

80833
  • 35
  • 5

1 Answers1

0

Try refreshing token beforehand like this:

if(credential.RequestAccessTokenAsync(CancellationToken.None).Result)
{
    AuthenticationKey = credential.Token.AccessToken;
}

This will try to refresh the Access Token essentially providing you the way to check service connectivity.

Furhan S.
  • 1,494
  • 2
  • 13
  • 22
  • There is no need to store the actual token as its already stored in the credentials instance and will be passed into the CalendarService itself no? Therefore I tried just this: `try { var auth = credential.RequestAccessTokenAsync(CancellationToken.None).Result; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return null; }` which works fine, however all the exceptions are nested in an AggregateException :/ – 80833 Jun 30 '15 at 08:37
  • Might help people with the same issue. http://stackoverflow.com/questions/21483599/using-googleapisclient-serviceaccountcredential-calling-requestaccesstokenasync. – 80833 Jun 30 '15 at 10:15