Google Drive API v2 for ASP.Net webforms

  • Monday, November 3, 2014 11:14 PM EST
  • Last Edited: Monday, November 3, 2014 11:30 PM EST

This is a sample working code for Google Drive API v2 for webforms

1. Namespaces

using System;

using System.Reflection;

using System.Drawing;

using System.IO;

using System.Linq;

using System.Threading;

using System.Web;

using System.Web.UI.WebControls;

 

using Google;

using Google.Apis.Auth.OAuth2;

using Google.Apis.Auth.OAuth2.Flows;

using Google.Apis.Auth.OAuth2.Web;

using Google.Apis.Services;

 

//for drive

using Google.Apis.Drive.v2;

using Google.Apis.Drive.v2.Data;

 

using Google.Apis.Util.Store;

//for AuthorizationCodeRequestUrl

using Google.Apis.Auth.OAuth2.Requests;

 

2. Main function

private DriveService service;

 

// Application logic should manage users authentication. This sample works with only one user. You can change

// it by retrieving data from the session.

private string UserId = "user";

 

       protected void Page_Load(object sender, EventArgs e)

       {

           string[] SCOPES = new String[]

           {

               "https://www.googleapis.com/auth/drive",

               "https://www.googleapis.com/auth/userinfo.email",

               "https://www.googleapis.com/auth/userinfo.profile",

               "https://www.googleapis.com/auth/drive.install"

         

           };

           GoogleAuthorizationCodeFlow flow;

           //use extended class to create google authorization code flow

           flow = new ForceOfflineGoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer

           {

               //use custom own datastore

               DataStore = new CustomGoogleDataStore("[Data Store Name]"),

               ClientSecrets = new ClientSecrets { ClientId = "[client_id]", ClientSecret = "[client_secret]" },

               Scopes = SCOPES,

           });

 

           var uri = Request.Url.ToString();

           string redirecturi = "http://localhost/googlesignin";

           var code = Request["code"];

           if (code != null)

           {

               var token = flow.ExchangeCodeForTokenAsync(UserId, code,

                   uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;

 

               // Extract the right state.

              var oauthState = AuthWebUtility.ExtracRedirectFromState(

                   flow.DataStore, UserId, Request["state"]).Result;

               Response.Redirect(oauthState);

           }

           else

           {

               

              var result = new AuthorizationCodeWebApp(flow, redirecturi, uri).AuthorizeAsync(UserId,

                   CancellationToken.None).Result;

 

               if (result.RedirectUri != null)

               {

                   // Redirect the user to the authorization server.

                   Response.Redirect(result.RedirectUri);

               }

               else

               {

                   // The data store contains the user credential, so the user has been already authenticated.

                   

                   service = new DriveService(new BaseClientService.Initializer()

                   {

                       HttpClientInitializer = result.Credential,

                       ApplicationName = "Drive API Sample"

                   });

                   

               }

           }

 

       }

 

       ///<summary>Gets the TasksLists of the user.</summary>

       public async System.Threading.Tasks.Task FetchFilelists()

       {

           try

           {

               // Get all files of the user asynchronously.

               FilesResource.ListRequest request = service.Files.List();

               

               //get only my files

               request.Q = "'me' in owners";

               

               FileList response = await request.ExecuteAsync();

 

               ShowFilelists(response);

           }

           catch (Exception ex)

           {

               var str = ex.ToString();

               str = str.Replace(Environment.NewLine, Environment.NewLine + "<br/>");

               str = str.Replace("  ", " &nbsp;");

               output.Text = string.Format("<font color=\"red\">{0}</font>", str);

           }

       }

 

       private void ShowFilelists(FileList response)

       {

           if (response.Items == null)

           {

               output.Text += "You have no files!<br/>";

               return;

           }

 

           output.Text += "Showing files...<br/>";

           int ctr = 0;

           foreach (Google.Apis.Drive.v2.Data.File file in response.Items)

           {

               ctr++;

               Panel listPanel = new Panel() { BorderWidth = Unit.Pixel(1), BorderColor = Color.Black };

               listPanel.Controls.Add(new Label { Text = file.Title + "--" + file.MimeType});

               listPanel.Controls.Add(new Label { Text = "<hr/>" });

               

               if(!file.MimeType.ToString().Contains("folder"))

                   listPanel.Controls.Add(new HyperLink { Text = "Download", NavigateUrl = file.WebContentLink });

               lists.Controls.Add(listPanel);

           }

 

           output.Text += "Total Files: " + ctr;

       }

 

       protected async void listButton_Click(object sender, EventArgs e)

       {

           await FetchFilelists();

       }

 

3. Overwriting the GoogleAuthorizationCodeFlow to force a prompt login

//overwrite. force offline.

       internal class ForceOfflineGoogleAuthorizationCodeFlow : GoogleAuthorizationCodeFlow

       {

           //source: //gotoanswer.stanford.edu/google_analytics_oauth_with_accesstype__offline_in_c-4478263/

 

           public ForceOfflineGoogleAuthorizationCodeFlow(GoogleAuthorizationCodeFlow.Initializer initializer) : base(initializer) { }

 

           public override AuthorizationCodeRequestUrl CreateAuthorizationCodeRequest(string redirectUri)

           {

               var ss = new Google.Apis.Auth.OAuth2.Requests.GoogleAuthorizationCodeRequestUrl(new Uri(AuthorizationServerUrl));

               ss.AccessType = "offline";

               ss.ApprovalPrompt = "force";

               ss.ClientId = ClientSecrets.ClientId;

               ss.Scope = string.Join(" ", Scopes);

               ss.RedirectUri = redirectUri;

               return ss;

           }

       };

 

 

Sources:

http://gotoanswer.stanford.edu/google_analytics_oauth_with_accesstype__offline_in_c-4478263/

https://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.ASP.NET.SimpleOAuth2/Default.aspx.cs?repo=samples

https://code.google.com/p/google-api-dotnet-client/source/browse/Drive.Sample/Program.cs?repo=samples

https://developers.google.com/drive/web/examples/dotnet

https://developers.google.com/drive/web/scopes

 

comments powered by Disqus