question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Authenticating / Refreshing Google API access token and avoiding a “file in use” exception?

See original GitHub issue

I have been encouraged to ask my question that I raised on StackOverflow here.

In short, I have been having occasional issues when trying to sync with a Google Calendar.

The basic functionality is:

  • Authenticate
  • Delete existing calendar events
  • Add new calendar events

The delete / add tasks are done using batching.

As mentioned, sometimes I get an exception like:

2020-11-30 18:47:03.6762|ERROR|GoogleAuthandSync.Program|AddEventsToCalendarXML|System.IO.IOException: The process cannot access the file ‘C:\Users\USERNAME\AppData\Roaming\XXXXX.Application\Google.Apis.Auth.OAuth2.Responses.TokenResponse-user’ because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

This is how I authenticate:

Private Function DoAuthentication(ByRef rStrToken As String, ByRef rParameters As OAuth2Parameters) As Boolean
    Dim credential As UserCredential
    Dim Secrets = New ClientSecrets() With {
        .ClientId = m_strClientID,
        .ClientSecret = m_strClientSecret
    }

    m_Scopes.Add(CalendarService.Scope.Calendar)

    Try
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, m_Scopes,
                                                                 "user", CancellationToken.None,
                                                                 New FileDataStore("XXXXX.Application")).Result()

        If credential.Token.IsExpired(Google.Apis.Util.SystemClock.Default) Then
            credential.RefreshTokenAsync(CancellationToken.None)
        End If


        ' Create the calendar service using an initializer instance
        Dim initializer As New BaseClientService.Initializer() With {
            .HttpClientInitializer = credential,
            .ApplicationName = "xxx"
        }
        m_Service = New CalendarService(initializer)

        rStrToken = credential.Token.AccessToken.ToString()
        rParameters.AccessToken = credential.Token.AccessToken
        rParameters.RefreshToken = credential.Token.RefreshToken
    Catch ex As Exception
        ' We encountered some kind of problem, perhaps they have not yet authenticated?
        ' Can we isolate that as the exception?
        m_logger.Error(ex, "DoAuthentication")

        Return False
    End Try

    Return True
End Function

I was wondering if this line is wrong:

credential.RefreshTokenAsync(CancellationToken.None)

Should it be proceeded with await? I wondered if it might still be refreshing the token file whilst we are continuing to try and use it. I can provide further code snippets as needed.

As mentioned, it usually works and this is a sporadic issue.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:24 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
amanda-tarafacommented, Dec 1, 2020

You don’t need to do any of that, there’s a Revoke method on the UserCredential. You can do something like the following (I’m writing directly on the comment so there might be some syntax errors).

Private Async Function DoRevokeAsync() As Task (Of Boolean)
    Dim credential As UserCredential
    Dim Secrets = New ClientSecrets() With {
        .ClientId = m_strClientID,
        .ClientSecret = m_strClientSecret
    }

    m_Scopes.Add(CalendarService.Scope.Calendar)

    Try
        credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, m_Scopes,
                                                                 "user", CancellationToken.None,
                                                                 New FileDataStore("XXXXX.Application"))

        Await credential.RevokeTokenAsync(CacenllationToken.None)

    Catch ex As Exception
        ' We encountered some kind of problem, perhaps they have not yet authenticated?
        ' Can we isolate that as the exception?
        m_logger.Error(ex, "DoAuthentication")

        Return False
    End Try

    Return True
End Function

This will both revoke the token with the Google Auth platform and delete it from the local file.

1reaction
amanda-tarafacommented, Dec 1, 2020

Yes, given that yours is a console application, it should be fine as it is now. Just calling Wait() and Result is redundant. You can just do:

Public Function Main() As Integer
        Return Run.Result
End Function
Read more comments on GitHub >

github_iconTop Results From Across the Web

Authenticating / Refreshing Google API access token and ...
Authenticating / Refreshing Google API access token and avoiding a "file in use" exception? Ask Question. Asked 2 years, 8 months ago.
Read more >
[Vb.Net]-Google Token refresh issue - appsloveworld.com
Authenticating / Refreshing Google API access token and avoiding a "file in use" exception? Fetching access token from refresh token in VB.net using...
Read more >
RESTful API with Python & FastAPI: Access and Refresh ...
RESTful API with Python & FastAPI: Access and Refresh Tokens ... which provides # access to the values within the .ini file in...
Read more >
Unified Data Model field list | Chronicle Security
It is an error to populate this field from within a parser. ... Key value labels. ... file, File, Information about the file...
Read more >
Citrix Fixes and Known Issues – XenApp & XenDesktop / ...
For example if you have an error code or error message, use that to perform a ... however subsequent attempts fail with error...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found