Search code examples
c#oauthgoogle-apigoogle-drive-apigoogle-oauth

Execution of request failed: https://docs.google.com/feeds/default/private/full?max-results=200


I am trying to get google drive list of files from using following code but I got an error Execution of request failed: https://docs.google.com/feeds/default/private/full?max-results=2000

previously it was working but from last few months its not working I am not able to understand where I am going wrong.please help me

OAuth2Parameters parameters = new OAuth2Parameters()
    {
        ClientId = "MYID.apps.googleusercontent.com",
        ClientSecret = "MYSECREAT",
        RedirectUri = currentURL,//"http://localhost:6692/Home.html"
        Scope = "https://docs.google.com/feeds/ ",
        State = "documents",
        AccessType = "offline",//offline means it creats a refreshtoken 
        TokenExpiry = DateTime.Now.AddYears(1)
    };
parameters.AccessCode = code;
Google.GData.Client.OAuthUtil.GetAccessToken(parameters);

GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "NAME", parameters);
DocumentsService service = new DocumentsService("NAME");
service.RequestFactory = requestFactory;
//requestFactory.CustomHeaders["Authorization"] = "Bearer " + parameters.AccessToken;
DocumentsListQuery query = new DocumentsListQuery();
query.NumberToRetrieve = 2000;

// Make a request to the API and get all documents.
//I Got an error in following line
DocumentsFeed feed = service.Query(query);

Solution

  • Part of your problem is that you are using the old Gdata calls. While the old GData API still works its tricky to get it to work with Oauth2 since you can no longer use client login and it was made back when client login was an option.

    I recommend using the Google .net client library which uses the new Google Drive Rest API

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

    Connect with Oauth2 class:

    /// <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 DriveService AuthenticateOauth(string clientId, string clientSecret, string userName)
            {
    
                //Google Drive scopes Documentation:   https://developers.google.com/drive/web/scopes
                string[] scopes = new string[] { DriveService.Scope.Drive,  // view and manage your files and documents
                                                 DriveService.Scope.DriveAppdata,  // view and manage its own configuration data
                                                 DriveService.Scope.DriveAppsReadonly,   // view your drive apps
                                                 DriveService.Scope.DriveFile,   // view and manage files created by this app
                                                 DriveService.Scope.DriveMetadataReadonly,   // view metadata for files
                                                 DriveService.Scope.DriveReadonly,   // view files and documents on your drive
                                                 DriveService.Scope.DriveScripts };  // modify your app scripts
    
    
                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.Drive.Auth.Store")).Result;
    
                    DriveService service = new DriveService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Daimto Drive API Sample",
                    });
                    return service;
                }
                catch (Exception ex)
                {
    
                    Console.WriteLine(ex.InnerException);
                    return null;
    
                }
    
            }
    

    Connect:

      // Connect with Oauth2 Ask user for permission
                String CLIENT_ID = "xxx-d0vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.com";
                String CLIENT_SECRET = "NDmluNfTgUk6wgmy7cFo64RV";      
                DriveService service = Authentication.AuthenticateOauth(CLIENT_ID, CLIENT_SECRET, Environment.UserName);
    

    List files method:

     /// Documentation Search: https://developers.google.com/drive/web/search-parameters
            /// </summary>
            /// <param name="service">a Valid authenticated DriveService</param>        
            /// <param name="search">if Search is null will return all files</param>        
            /// <returns></returns>
            public static IList<File> GetFiles(DriveService service, string search)
            {
    
                IList<File> Files = new List<File>();
    
                try
                {
                    //List all of the files and directories for the current user.  
                    // Documentation: https://developers.google.com/drive/v2/reference/files/list
                    FilesResource.ListRequest list = service.Files.List();
                    list.MaxResults = 1000;
                    if (search != null)
                    {
                        list.Q = search;
                    }
                    FileList filesFeed = list.Execute();
    
                    //// Loop through until we arrive at an empty page
                    while (filesFeed.Items != null)
                    {
                        // Adding each item  to the list.
                        foreach (File item in filesFeed.Items)
                        {
                            Files.Add(item);
                        }
    
                        // We will know we are on the last page when the next page token is
                        // null.
                        // If this is the case, break.
                        if (filesFeed.NextPageToken == null)
                        {
                            break;
                        }
    
                        // Prepare the next page of results
                        list.PageToken = filesFeed.NextPageToken;
    
                        // Execute and process the next page request
                        filesFeed = list.Execute();
                    }
                }
                catch (Exception ex) {
                    // In the event there is an error with the request.
                    Console.WriteLine(ex.Message);                            
                }
                return Files;
            }
    

    Listing the files:

     // Listing files with search.  
                    // This searches for a directory with the name DiamtoSample
                    string Q = "title = 'DiamtoSample' and mimeType = 'application/vnd.google-apps.folder'";
                    IList<File> _Files = DaimtoGoogleDriveHelper.GetFiles(service, Q);
    
                    foreach (File item in _Files)
                    {
                        Console.WriteLine(item.Title + " " + item.MimeType);
                    }
    

    Useful links