Issue with translating a delegate function from c# to vb.net for use with Google OAuth 2

Posted by Jeremy on Stack Overflow See other posts from Stack Overflow or by Jeremy
Published on 2012-03-20T04:38:58Z Indexed on 2012/03/20 5:29 UTC
Read the original article Hit count: 306

I've been trying to translate a Google OAuth 2 example from C# to Vb.net for a co-worker's project. I'm having on end of issues translating the following methods:

    private OAuth2Authenticator<WebServerClient> CreateAuthenticator()
        {
            // Register the authenticator.
            var provider = new WebServerClient(GoogleAuthenticationServer.Description);
            provider.ClientIdentifier = ClientCredentials.ClientID;
            provider.ClientSecret = ClientCredentials.ClientSecret;
            var authenticator = 
                new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true };
            return authenticator;
        }

        private IAuthorizationState GetAuthorization(WebServerClient client)
        {
            // If this user is already authenticated, then just return the auth state.
            IAuthorizationState state = AuthState;
            if (state != null)
            {
                return state;
            }

            // Check if an authorization request already is in progress.
            state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
            if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken)))
            {
                // Store and return the credentials.
                HttpContext.Current.Session["AUTH_STATE"] = _state = state;
                return state;
            }

            // Otherwise do a new authorization request.
            string scope = TasksService.Scopes.TasksReadonly.GetStringValue();
            OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope });
            response.Send(); // Will throw a ThreadAbortException to prevent sending another response.
            return null;
        }

The main issue being this line:

var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true };

The Method signature reads as for this particular line reads as follows:

Public Sub New(tokenProvider As TClient, authProvider As System.Func(Of TClient, DotNetOpenAuth.OAuth2.IAuthorizationState))

My understanding of Delegate functions in VB.net isn't the greatest. However I have read over all of the MSDN documentation and other relevant resources on the web, but I'm still stuck as to how to translate this particular line.

So far all of my attempts have resulted in either the a cast error (see below) or no call to GetAuthorization.

The Code (vb.net on .net 3.5)

    Private Function CreateAuthenticator() As OAuth2Authenticator(Of WebServerClient)
        ' Register the authenticator.
        Dim client As New WebServerClient(GoogleAuthenticationServer.Description, oauth.ClientID, oauth.ClientSecret)

        Dim authDelegate As Func(Of WebServerClient, IAuthorizationState) = AddressOf GetAuthorization
        Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, authDelegate) With {.NoCaching = True}

        'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, GetAuthorization(client)) With {.NoCaching = True}
        'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, New Func(Of WebServerClient, IAuthorizationState)(Function(c) GetAuthorization(c))) With {.NoCaching = True}
        'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, New Func(Of WebServerClient, IAuthorizationState)(AddressOf GetAuthorization)) With {.NoCaching = True}

        Return authenticator
    End Function



    Private Function GetAuthorization(arg As WebServerClient) As IAuthorizationState
        ' If this user is already authenticated, then just return the auth state.
        Dim state As IAuthorizationState = AuthState

        If (Not state Is Nothing) Then
            Return state
        End If

        ' Check if an authorization request already is in progress.
        state = arg.ProcessUserAuthorization(New HttpRequestInfo(HttpContext.Current.Request))
        If (state IsNot Nothing) Then
            If ((String.IsNullOrEmpty(state.AccessToken) = False Or String.IsNullOrEmpty(state.RefreshToken) = False)) Then
                ' Store Credentials
                HttpContext.Current.Session("AUTH_STATE") = state
                _state = state

                Return state
            End If
        End If

        ' Otherwise do a new authorization request.
        Dim scope As String = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue()
        Dim _response As OutgoingWebResponse = arg.PrepareRequestUserAuthorization(New String() {scope})
        ' Add Offline Access and forced Approval
        _response.Headers("location") += "&access_type=offline&approval_prompt=force"
        _response.Send() ' Will throw a ThreadAbortException to prevent sending another response.

        Return Nothing
    End Function

The Cast Error

Server Error in '/' Application.
Unable to cast object of type 'DotNetOpenAuth.OAuth2.AuthorizationState' to type 'System.Func`2[DotNetOpenAuth.OAuth2.WebServerClient,DotNetOpenAuth.OAuth2.IAuthorizationState]'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Unable to cast object of type 'DotNetOpenAuth.OAuth2.AuthorizationState' to type 'System.Func`2[DotNetOpenAuth.OAuth2.WebServerClient,DotNetOpenAuth.OAuth2.IAuthorizationState]'.

I've spent the better part of a day on this, and it's starting to drive me nuts. Help is much appreciated.

© Stack Overflow or respective owner

Related posts about vb.net

Related posts about .net-3.5