3

I am writing a Console Application to download data from BigQuery. Once again, the .NET library is vague and confusing. In this question, two Google employees have posted a response and neither of the responses is working on my machine because they haven't quite made it clear which references they are using. I paste the code once again and elaborate:

using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;

using Google.Apis.Bigquery.v2;
using Google.Apis.Util;

{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Register an authenticator.
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);

            // Put your client id and secret here (from https://developers.google.com/console)
            // Use the installed app flow here.
            provider.ClientIdentifier = "<client id>";
            provider.ClientSecret = "<client secret>";

            // Initiate an OAuth 2.0 flow to get an access token
            var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

            // Create the service.
            var service = new BigqueryService(auth);

            // Do something with the BigQuery service here
            // Such as... service.[some BigQuery method].Fetch();
        }

        private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {
            // Get the auth URL:
            IAuthorizationState state = new AuthorizationState(new[] { BigqueryService.Scopes.Bigquery.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri authUri = arg.RequestUserAuthorization(state);

            // Request authorization from the user (by opening a browser window):
            Process.Start(authUri.ToString());
            Console.Write("  Authorization Code: ");
            string authCode = Console.ReadLine();
            Console.WriteLine();

            // Retrieve the access token by using the authorization code:
            return arg.ProcessUserAuthorization(authCode, state);
        }
    }
}
  1. First, the Google.Apis.Authentication is now obsolete and NuGet encourages you to use Google.Api.Auth instead.
  2. The NativeApplicationClient does not resolve using any of the usings in the code. Maybe it was included in the obsolete Google.Apis.Authentication.
  3. One of the employees has posted a link (https://github.com/google/google-api-dotnet-client#Latest_Stable_Release) to the Github repo of the code. But most projects in this repo demand Windows 8.1 which I don't have.

Is there any straightforward and clear code we could use for downloading BigQuery query results? I guess the main problem here is making the auth object.

Community
  • 1
  • 1
disasterkid
  • 6,948
  • 25
  • 94
  • 179
  • Have you read https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth ? I believe you're right that `NativeApplicationClient` is in the old auth nuget package. I believe you want `GoogleWebAuthorizationBroker.AuthorizeAsync` now. – Jon Skeet Sep 22 '15 at 08:54

1 Answers1

3

In order to install this nuget package:

PM> Install-Package Google.Apis.Bigquery.v2

This is the code I normally use.

/// <summary>
/// Authenticate to Google Using Oauth2
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
/// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
/// <param name="userName">A string used to identify a user.</param>
/// <returns></returns>
public static BigqueryService  AuthenticateOauth(string clientId, string clientSecret, string userName)
{

    string[] scopes = new string[] { BigqueryService.Scope.Bigquery,                // view and manage your BigQuery data
                                     BigqueryService.Scope.BigqueryInsertdata ,     // Insert Data into Big query
                                     BigqueryService.Scope.CloudPlatform,           // view and manage your data acroos cloud platform services
                                     BigqueryService.Scope.DevstorageFullControl,   // manage your data on Cloud platform services
                                     BigqueryService.Scope.DevstorageReadOnly ,     // view your data on cloud platform servies
                                     BigqueryService.Scope.DevstorageReadWrite };   // manage your data on cloud platform servies

    try
    {
        // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
        UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                     , scopes
                                                                                     , userName
                                                                                     , CancellationToken.None
                                                                                     , new FileDataStore("Daimto.BigQuery.Auth.Store")).Result;

        BigqueryService service = new BigqueryService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "BigQuery API Sample",
        });
        return service;
    }
    catch (Exception ex)
    {

        Console.WriteLine(ex.InnerException);
        return null;

    }

}
Deano
  • 2,805
  • 3
  • 29
  • 42
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • I will try it right away. What should I use as my username? – disasterkid Sep 22 '15 at 09:08
  • The only purpose of Username is to create the datastore. this might help http://www.daimto.com/google-net-filedatastore-demystified/ – Linda Lawton - DaImTo Sep 22 '15 at 09:09
  • OK! But what should the value be? Can it be anything? – disasterkid Sep 22 '15 at 09:13
  • its basically just a string. it can be anything sometimes I use machine name. It depends on the type of system you have really. read that post you will understand what its used for and be able to decide if you need it or not. If its just a single user you probably wont need it. if you have more then one user whos accounts you want to access you will need it. – Linda Lawton - DaImTo Sep 22 '15 at 09:14