iesmerio / google-gdata

Automatically exported from code.google.com/p/google-gdata
0 stars 0 forks source link

Execution of authentication request returned unexpected result: 404 #716

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
What steps will reproduce the problem?
1. After the "GA_Service.Credentials = new GDataCredentials (strGAUserName, 
strGAPassword);"
2.var token = GA_Service.QueryAuthenticationToken(); 
3. GA_Service.SetAuthenticationToken(token);

What is the expected output? What do you see instead?

It was working fine, but now i get this error after 10 times of data pull.

What version of the product are you using? On what operating system?
Google.GData.Analytics V 2.2.0.0

Please provide any additional information below.

Original issue reported on code.google.com by APUS...@gmail.com on 26 May 2015 at 8:39

GoogleCodeExporter commented 8 years ago
I am having the very same problem - my code has been working for two years 
without any issues.  Same exception:

Unhandled Exception: Google.GData.Client.GDataRequestException: Execution of 
aut hentication request returned unexpected result: 404 at 
Google.GData.Client.Utilities.getAuthException(TokenCollection tokens, Htt 
pWebResponse response) at 
Google.GData.Client.Utilities.QueryClientLoginToken(GDataCredentials gc, S 
tring serviceName, String applicationName, Boolean fUseKeepAlive, IWebProxy 
prox yServer, Uri clientLoginHandler) at 
Google.GData.Client.GDataGAuthRequest.QueryAuthToken(GDataCredentials gc) at 
Google.GData.Client.GDataGAuthRequest.EnsureCredentials() at 
Google.GData.Client.GDataRequest.EnsureWebRequest() at 
Google.GData.Client.GDataGAuthRequest.EnsureWebRequest() at 
Google.GData.Client.GDataRequest.Execute() at 
Google.GData.Client.GDataGAuthRequest.Execute(Int32 retryCounter) at 
Google.GData.Client.GDataGAuthRequest.Execute() at 
Google.GData.Client.Service.Query(Uri queryUri, DateTime ifModifiedSince, 
String etag, Int64& contentLength) at 
Google.GData.Client.Service.Query(FeedQuery feedQuery) at 
Google.GData.Documents.DocumentsService.Query(DocumentsListQuery feedQuery ) at 
GoogleLogger.GoogleService.getLastXECLogRows(String folderName, String 
fileName, Int32 rows)

This is occurring on my production system, so it's a huge problem for us.

Original comment by evilstee...@gmail.com on 26 May 2015 at 9:30

GoogleCodeExporter commented 8 years ago
This site is down: https://developers.google.com/accounts/RegistrationForWebApps

Original comment by evilstee...@gmail.com on 26 May 2015 at 9:36

GoogleCodeExporter commented 8 years ago
I am getting a similar issue. Getting 404'ed when it was working fine just 
prior to 14:53 PST. I'm using Google.GData.Spreadsheets 2.2.0.0

Original comment by k...@kuwaitculturela.org on 26 May 2015 at 10:27

GoogleCodeExporter commented 8 years ago
I take it you guys all use the GData API still? I have been digging around and 
it seems that there is a new API:

https://developers.google.com/drive/web/quickstart/quickstart-cs

I really hope that the old GData API is still supported or we'll have to 
rewrite everything. BTW the new Drive API is not supported by .Net 3.5 - so 
this is a huge disaster for me.

Original comment by evilstee...@gmail.com on 26 May 2015 at 10:50

GoogleCodeExporter commented 8 years ago
yes .. it was working fine until 3 PM ET today .. then BOOM!!!!! 

anyone found the solution??? 

Original comment by APUS...@gmail.com on 27 May 2015 at 1:01

GoogleCodeExporter commented 8 years ago
I have the same problem.  Authentication is not working for me at all.  I 
really don't want to rewrite everything either.

Original comment by ad...@dloweb.com on 27 May 2015 at 1:25

GoogleCodeExporter commented 8 years ago
I'm seeing the same issue ...

Type
Google.GData.Client.GDataRequestException

Message
Execution of authentication request returned unexpected result: 404

Stack ...
at Google.GData.Client.Utilities.getAuthException(TokenCollection tokens, 
HttpWebResponse response) at 
Google.GData.Client.Utilities.QueryClientLoginToken(GDataCredentials gc, String 
serviceName, String applicationName, Boolean fUseKeepAlive, IWebProxy 
proxyServer, Uri clientLoginHandler) at 
Google.GData.Client.GDataGAuthRequest.QueryAuthToken(GDataCredentials gc) at 
Google.GData.Client.GDataGAuthRequest.EnsureCredentials() at 
Google.GData.Client.GDataRequest.EnsureWebRequest() at 
Google.GData.Client.GDataGAuthRequest.EnsureWebRequest() at 
Google.GData.Client.GDataRequest.Execute() at 
Google.GData.Client.GDataGAuthRequest.Execute(Int32 retryCounter) at 
Google.GData.Client.Service.Query(Uri queryUri, DateTime ifModifiedSince, 
String etag, Int64& contentLength) at 
Google.GData.Client.Service.Query(FeedQuery feedQuery) at 
Google.GData.Spreadsheets.SpreadsheetsService.Query(SpreadsheetQuery feedQuery) 

Original comment by lhfied...@gmail.com on 27 May 2015 at 1:54

GoogleCodeExporter commented 8 years ago
Also experiencing the error with em client accessing Google contacts. Works for 
email and calendar, but not for contacts since 12 pm PST today.

Original comment by aynch...@gmail.com on 27 May 2015 at 2:57

GoogleCodeExporter commented 8 years ago
Also Sample Applications give the same error. Anybody get error on  version 2.1 
? 

Original comment by yuceloz...@gmail.com on 27 May 2015 at 2:58

GoogleCodeExporter commented 8 years ago
I get same issue today. hurry!

Original comment by wang.zha...@gosugroup.com on 27 May 2015 at 3:10

GoogleCodeExporter commented 8 years ago
Same here, i'm using GData API v2.2

Original comment by eron...@gmail.com on 27 May 2015 at 3:39

GoogleCodeExporter commented 8 years ago
There is a note on the sheets API page 
(https://developers.google.com/google-apps/spreadsheets/authorize) saying that 
OAuth1.0 will be killed off on May 5th and you have to use the OAuth 2.0 
service.

Original comment by dmonkey1...@gmail.com on 27 May 2015 at 3:47

GoogleCodeExporter commented 8 years ago
I am also started this issue around 12pm PDT.

Google.GData.Client.GDataRequestException: Execution of authentication request 
returned unexpected result: 404
   at Google.GData.Client.Utilities.getAuthException(TokenCollection tokens, HttpWebResponse response)
   at Google.GData.Client.Utilities.QueryClientLoginToken(GDataCredentials gc, String serviceName, String applicationName, Boolean fUseKeepAlive, IWebProxy proxyServer, Uri clientLoginHandler)
   at Google.GData.Client.GDataGAuthRequest.QueryAuthToken(GDataCredentials gc)
   at Google.GData.Client.GDataGAuthRequestFactory.QueryAuthToken(GDataCredentials gc)
   at Google.GData.Client.Service.QueryClientLoginToken()

Original comment by a...@ua.fm on 27 May 2015 at 4:51

GoogleCodeExporter commented 8 years ago
[deleted comment]
GoogleCodeExporter commented 8 years ago
Please update if someone find solution.I am getting this issue when try to read 
group names,till yesterday everything was working fine.
Following is the exception which i am getting:

  at Google.GData.Client.Utilities.getAuthException(TokenCollection tokens, HttpWebResponse response)
   at Google.GData.Client.Utilities.QueryClientLoginToken(GDataCredentials gc, String serviceName, String applicationName, Boolean fUseKeepAlive, IWebProxy proxyServer, Uri clientLoginHandler)
   at Google.GData.Client.GDataGAuthRequest.QueryAuthToken(GDataCredentials gc)
   at Google.GData.Client.GDataGAuthRequest.EnsureCredentials()
   at Google.GData.Client.GDataRequest.EnsureWebRequest()
   at Google.GData.Client.GDataGAuthRequest.EnsureWebRequest()
   at Google.GData.Client.GDataRequest.Execute()
   at Google.GData.Client.GDataGAuthRequest.Execute(Int32 retryCounter)
   at Google.GData.Client.GDataGAuthRequest.Execute()
   at Google.GData.Client.Service.Query(Uri queryUri, DateTime ifModifiedSince, String etag, Int64& contentLength)
   at Google.GData.Client.Service.Query(Uri queryUri, DateTime ifModifiedSince)
   at Google.GData.Client.Service.Query(FeedQuery feedQuery)
   at Google.GData.Client.Feed`1.get_AtomFeed()
   at Google.GData.Client.Feed`1.<get_Entries>d__0.MoveNext()
   at IMAPCommands.GetGroups.PrintAllGroups(ContactsRequest cr) in e:\back\TestFolder\IMAPCommands\IMAPCommands\GetGroups.cs:line 18
   at IMAPCommands.Program.Main(String[] args) in e:\back\TestFolder\IMAPCommands\IMAPCommands\Program.cs:line 22
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Original comment by sunny198...@gmail.com on 27 May 2015 at 5:38

GoogleCodeExporter commented 8 years ago
I have exactly the same problem... My production systems depends on google docs 
and I have a major disaster now. Any knows if google is working on that ?

Original comment by off...@e-cosmetorium.com on 27 May 2015 at 5:44

GoogleCodeExporter commented 8 years ago
Guys isn't it somehow connected with the information:
'OAuth 1.0 is no longer supported and will be disabled on May 5, 2015'
https://developers.google.com/google-apps/spreadsheets/authorize

Anyone migrate code to use OAuth 2.0 and thus solved the problem?

Original comment by off...@e-cosmetorium.com on 27 May 2015 at 5:48

GoogleCodeExporter commented 8 years ago
[deleted comment]
GoogleCodeExporter commented 8 years ago
But today is 27 May :-), Why it is reflecting after almost 20 days. 

Original comment by sunny198...@gmail.com on 27 May 2015 at 5:52

GoogleCodeExporter commented 8 years ago
No idea why it may take an effect 20 days later. 
Any one who have code snippet in .NET with the authentication OAuth 2.0 , I try 
to solve it on production as fast as I can now.

Thanks

Original comment by off...@e-cosmetorium.com on 27 May 2015 at 5:56

GoogleCodeExporter commented 8 years ago
Anybody has a fix ? Please let us know immediately

Original comment by pallavi....@paxcel.net on 27 May 2015 at 6:37

GoogleCodeExporter commented 8 years ago

While fetching gmail contact details m getting "Execution of authentication 
request returned unexpected result: 404" Exception ... please kindly help me to 
sort out this issue as earlier as possible.

Below mention is my Code
RequestSettings rs = new RequestSettings("MyNetwork Web Application!", 
TEmailID, Tpass);
rs.AutoPaging = true;
ContactsRequest cr = new ContactsRequest(rs);
Feed<Contact> f = cr.GetContacts();

Original comment by sangeeth...@gmail.com on 27 May 2015 at 6:41

GoogleCodeExporter commented 8 years ago
Clearly we'll need to use OAuth2 but the only examples I've run across use 
copy/pasting a URL into a web browser and retrieving it, and then pasting it 
into the command line:

https://developers.google.com/google-apps/spreadsheets/authorize

I'm running an application outside of a web browser, so that's not an option. 
We need to find an OAuth2 example that works without manually accepting a token.

Original comment by evilstee...@gmail.com on 27 May 2015 at 7:54

GoogleCodeExporter commented 8 years ago
M using GContacts Data API provided by Google to retrieve contacts from gmail 
...  using asp.net c#(VS2010). Please guide me how to solve this problem.

what is this OAuth2?

Original comment by sangeeth...@gmail.com on 27 May 2015 at 8:05

GoogleCodeExporter commented 8 years ago
I've managed to solve this by using this solution with Service Account with 
oAuth2.0 
http://stackoverflow.com/questions/13664731/accessing-older-gdata-apis-spreadshe
et-api-using-oauth-2-and-a-service-account

The solution:
1. Create Project and Google Service Account in 
https://console.developers.google.com/project
2. Generate your p12 key.
3. Allow APIs in Developer console you want to use (basically we are going to 
use old API, so you can skip this step, but just in case)
4. Use the code below (.NET Framework 4.5!):

using System.Security.Cryptography.X509Certificates;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Spreadsheets;
using Google.Apis.Auth.OAuth2;

string keyFilePath = @"C:\key.p12";    // found in developer console
string serviceAccountEmail = "youraccount@developer.gserviceaccount.com";   // 
found in developer console
var certificate = new X509Certificate2(keyFilePath, "notasecret", 
X509KeyStorageFlags.Exportable);

ServiceAccountCredential credential = new ServiceAccountCredential(new 
ServiceAccountCredential.Initializer(serviceAccountEmail) //create credential 
using certigicate
            {
                Scopes = new[] { "https://spreadsheets.google.com/feeds/" } //this scopr is for spreadsheets, check google scope FAQ for others
            }.FromCertificate(certificate));

credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Wait
(); //request token

var requestFactory = new GDataRequestFactory("Some Name"); 
requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", 
credential.Token.AccessToken));

SpreadsheetsService myService = new SpreadsheetsService("You App Name"); 
//create your old service
myService.RequestFactory = requestFactory; //add new request factory to your 
old service

SpreadsheetQuery query = new SpreadsheetQuery(); //do the job as you done it 
before
SpreadsheetFeed feed = myService.Query(query);

Original comment by a.kopa...@oorraa.net on 27 May 2015 at 10:38

GoogleCodeExporter commented 8 years ago
Also don't forget to grant "youraccount@developer.gserviceaccount.com" access 
to your spreadsheet document as you grant permissions for usual users by 
pressing Share.

Original comment by a.kopa...@oorraa.net on 27 May 2015 at 10:49

GoogleCodeExporter commented 8 years ago
Looks like this is the right direction for me as well, but now i'm getting 
exception when I call Query method.

            var query = new SpreadsheetQuery();
            query.Title ="some title";
            var feed = Service.Query(query);//<- exception

Any idea what could be wrong, or what should I do to check it out?

[XmlException: Root element is missing.]
   System.Xml.XmlTextReaderImpl.Throw(Exception e) +69
   System.Xml.XmlTextReaderImpl.ParseDocumentContent() +5674146
   System.Xml.XmlTextReaderImpl.Read() +213
   System.Xml.XmlTextReader.Read() +13
   Google.GData.Client.BaseFeedParser.MoveToStartElement(XmlReader reader) +174
   Google.GData.Client.AtomFeedParser.Parse(Stream streamInput, AtomFeed feed) +117

[ClientFeedException: Parsing failed]
   Google.GData.Client.AtomFeedParser.Parse(Stream streamInput, AtomFeed feed) +202
   Google.GData.Client.AtomFeed.Parse(Stream stream, AlternativeFormat format) +273
   Google.GData.Client.Service.CreateAndParseFeed(Stream inputStream, Uri uriToUse) +207
   Google.GData.Client.Service.Query(FeedQuery feedQuery) +417
   Google.GData.Spreadsheets.SpreadsheetsService.Query(SpreadsheetQuery feedQuery) +42
   ECosmetorium.Web.BLL.ManagerSpreadsheet.GetSpreadSheet(String url) in c:\Users\Administrator\Source\Workspaces\Clip - Prototype\ECosmetorium.Web\BLL\ManagerSpreadsheet.cs:1104
   ECosmetorium.Web.BLL.ManagerSpreadsheet.GetListFeed(String spreadsheetUrl, String worksheetname) in c:\Users\Administrator\Source\Workspaces\Clip - Prototyp\BLL\ManagerSpreadsheet.cs:902
   ECosmetorium.Web.BLL.ManagerSpreadsheet.LoadAllProducts() in c:\Users\Administrator\Source\Workspaces\Clip - Prototype\ECosmetorium.Web\BLL\ManagerSpreadsheet.cs:406
  b.BLL.ManagerSpreadsheet..ctor() in c:\Users\Administrator\Source\Workspaces\Clip - PrototypeLL\ManagerSpreadsheet.cs:56
   eb.Pages.ExportOptimaInvoices.Page_Load(Object sender, EventArgs e) in c:\Users\Administrator\Source\WoProPages\ExportOptimaInvoices.aspx.cs:25
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +92
   System.Web.UI.Control.LoadRecursive() +54
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772

Original comment by magda.se...@gmail.com on 27 May 2015 at 11:30

GoogleCodeExporter commented 8 years ago
thanks Kopa. 

I followed all the steps you mention, i get the below error. 
"<internalReason>Login Required</internalReason>"

Google.GData.Client.GDataRequestException was unhandled
  HResult=-2146233088
  Message=Execution of request failed: https://www.google.com/analytics/feeds/data?max-results=10000&dimensions=ga:dimension2,ga:source,ga:medium,ga:campaign,ga:keyword,ga:date,ga:hour&end-date=2015-05-23&ids=ga:19249406&metrics=ga:sessions,ga:goalCompletionsAll,ga:goal2Completions,ga:goal3Completions,ga:goal9Completions,ga:goal10Completions,ga:goal13Completions,ga:goal14Completions&sort=ga:date,ga:hour&start-date=2015-05-22
  Source=Google.GData.Client
  ResponseString=<?xml version="1.0" encoding="UTF-8"?><errors xmlns="http://schemas.google.com/g/2005"><error><domain>GData</domain><code>required</code><location type="header">Authorization</location><internalReason>Login Required</internalReason></error></errors>

Original comment by APUS...@gmail.com on 27 May 2015 at 2:38

GoogleCodeExporter commented 8 years ago
[deleted comment]
GoogleCodeExporter commented 8 years ago
how do I get the dll for using Google.Apis.Auth.OAuth2;. I'm trying to fix 
http://www.statslice.com/leveraging-google-docs-with-ssis to get it working 
again. Any help would be great

Original comment by Sherwood...@gmail.com on 27 May 2015 at 3:51

GoogleCodeExporter commented 8 years ago
Alright, I figured it out. Step by step instructions as follows - also see the 
code I provided below. FYI, this runs in .Net 3.5 and unlike the solution 
offered previously there are no new dependencies. You should be up and running 
in no time.

1. If you haven't yet create your OAuth 2.0 credentials - I assume you already 
know how to get those but here:
   a) Log into your Google developer console: http://console.developers.google.com
   b) Create a project
   c) Create your credentials - use 'installed application'
   d) add the APIs that you need - I think Drive API is definitely required. I also added Drive SDK just in case.
2. Copy the code below into VS and edit the first Main() method with your 
client key and secret key. 
3. Run the app and copy both the new access token and the refresh token. Put 
those and your remaining credentials into the second Main() method below.
4. You now should be able to run the second Main() method (just reverse the 
naming). From now on that will be all you need - there is no need to re-run the 
first Main() method.

BTW, the first Main() method below was found here: 
https://developers.google.com/google-apps/spreadsheets/authorize

CODE:

using System;
using Google.GData.Client;
using Google.GData.Spreadsheets;
using Google.GData.Documents;
using System.Configuration;
using System.Collections.Specialized;

namespace GoogleSpreadsheet
{
  class GoogleOAutho2
  {

    private static String folderName = "crazy.ivan";

    static void Main(string[] args)
    {
      ////////////////////////////////////////////////////////////////////////////
      // STEP 1: Configure how to perform OAuth 2.0
      ////////////////////////////////////////////////////////////////////////////

      // TODO: Update the following information with that obtained from
      // https://code.google.com/apis/console. After registering
      // your application, these will be provided for you.

      string CLIENT_ID = "your_client_id";

      // This is the OAuth 2.0 Client Secret retrieved
      // above.  Be sure to store this value securely.  Leaking this
      // value would enable others to act on behalf of your application!
      string CLIENT_SECRET = "your_secret_key"

      // Space separated list of scopes for which to request access.
      string SCOPE = "https://www.googleapis.com/auth/drive https://spreadsheets.google.com/feeds https://docs.google.com/feeds";

      // This is the Redirect URI for installed applications.
      // If you are building a web application, you have to set your
      // Redirect URI at https://code.google.com/apis/console.
      string REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";

      string TOKEN_TYPE = "refresh";

      ////////////////////////////////////////////////////////////////////////////
      // STEP 2: Set up the OAuth 2.0 object
      ////////////////////////////////////////////////////////////////////////////

      // OAuth2Parameters holds all the parameters related to OAuth 2.0.
      OAuth2Parameters parameters = new OAuth2Parameters();

      // Set your OAuth 2.0 Client Id (which you can register at
      // https://code.google.com/apis/console).
      parameters.ClientId = CLIENT_ID;

      // Set your OAuth 2.0 Client Secret, which can be obtained at
      // https://code.google.com/apis/console.
      parameters.ClientSecret = CLIENT_SECRET;

      // Set your Redirect URI, which can be registered at
      // https://code.google.com/apis/console.
      parameters.RedirectUri = REDIRECT_URI;

      ////////////////////////////////////////////////////////////////////////////
      // STEP 3: Get the Authorization URL
      ////////////////////////////////////////////////////////////////////////////

      // Set the scope for this particular service.
      parameters.Scope = SCOPE;

      parameters.AccessType = "offline"; // IMPORTANT and was missing in the original

      parameters.TokenType = TOKEN_TYPE; // IMPORTANT and was missing in the original

      // Get the authorization url.  The user of your application must visit
      // this url in order to authorize with Google.  If you are building a
      // browser-based application, you can redirect the user to the authorization
      // url.
      string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
      Console.WriteLine(authorizationUrl);
      Console.WriteLine("Please visit the URL above to authorize your OAuth "
        + "request token.  Once that is complete, type in your access code to "
        + "continue...");
      parameters.AccessCode = Console.ReadLine();

      ////////////////////////////////////////////////////////////////////////////
      // STEP 4: Get the Access Token
      ////////////////////////////////////////////////////////////////////////////

      // Once the user authorizes with Google, the request token can be exchanged
      // for a long-lived access token.  If you are building a browser-based
      // application, you should parse the incoming request token from the url and
      // set it in OAuthParameters before calling GetAccessToken().
      OAuthUtil.GetAccessToken(parameters);
      string accessToken = parameters.AccessToken;
      string refreshToken = parameters.RefreshToken;
      Console.WriteLine("OAuth Access Token: " + accessToken + "\n");
      Console.WriteLine("OAuth Refresh Token: " + refreshToken + "\n");

      ////////////////////////////////////////////////////////////////////////////
      // STEP 5: Make an OAuth authorized request to Google
      ////////////////////////////////////////////////////////////////////////////

      // Initialize the variables needed to make the request
      GOAuth2RequestFactory requestFactory =
          new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters);
      SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
      service.RequestFactory = requestFactory;

      // Make the request to Google
      // See other portions of this guide for code to put here...

      // Instantiate a SpreadsheetQuery object to retrieve spreadsheets.
      Google.GData.Spreadsheets.SpreadsheetQuery query = new Google.GData.Spreadsheets.SpreadsheetQuery();

      // Make a request to the API and get all spreadsheets.
      SpreadsheetFeed feed = service.Query(query);

      // Iterate through all of the spreadsheets returned
      foreach (SpreadsheetEntry entry in feed.Entries)
      {
        // Print the title of this spreadsheet to the screen
        Console.WriteLine(entry.Title.Text);
      }
      Console.ReadLine();

     }

    // once you copied your access and refresh tokens
    // then you can run this method directly from now on...
    static void MainX(string[] args)
    {
    GOAuth2RequestFactory requestFactory = RefreshAuthenticate();

         SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");  
         service.RequestFactory = requestFactory;

      // Instantiate a SpreadsheetQuery object to retrieve spreadsheets.
      Google.GData.Spreadsheets.SpreadsheetQuery query = new Google.GData.Spreadsheets.SpreadsheetQuery();

      // Make a request to the API and get all spreadsheets.
      SpreadsheetFeed feed = service.Query(query);

      // Iterate through all of the spreadsheets returned
      foreach (SpreadsheetEntry entry in feed.Entries)
      {
        // Print the title of this spreadsheet to the screen
        Console.WriteLine(entry.Title.Text);
      }
      Console.ReadLine();

    public static GOAuth2RequestFactory RefreshAuthenticate() {
        OAuth2Parameters parameters = new OAuth2Parameters(){
            RefreshToken = "the_refresh_token_you_copied_from_the_CLI_running_the_first_method";
            AccessToken = "the_access_token_you_copied_from_the_CLI_running_the_first_method";
            ClientId = "your_client_id";
            ClientSecret = "your_dirty_little_secret";
            Scope = "https://www.googleapis.com/auth/drive https://spreadsheets.google.com/feeds",
            AccessType = "offline",
            TokenType = "refresh"
        };
        string authUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
        return new GOAuth2RequestFactory(null, "evilspeculator", parameters);
    }
  }
}

Hope that works for you guys - best of luck!

Original comment by evilstee...@gmail.com on 27 May 2015 at 5:46

GoogleCodeExporter commented 8 years ago
I get same issue  with this code. Anybody has a fix?... please

Dim gkey As String = "?key=" & PublicAPIkey

        Dim dataFeedUrl As String = "https://www.google.com/analytics/feeds/data" + gkey
               Dim service As Google.GData.Analytics.AnalyticsService = New Google.GData.Analytics.AnalyticsService("All Web Site Data")
        service.setUserCredentials(username, pass)

        Dim query1 As DataQuery = New DataQuery(dataFeedUrl)

        query1.Ids = "ga:99999999"
        query1.Metrics = "ga:users"

        query1.GAStartDate = DateTime.Now.ToString("yyyy-MM-dd")
        query1.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd")
        query1.StartIndex = 1

        Dim dataFeedVisits As DataFeed = service.Query(query1)

        For Each entry As DataEntry In dataFeedVisits.Entries

            Dim st As String = entry.Title.Text
            Dim ss As String = entry.Metrics(0).Value
            visits = ss
        Next

Original comment by fernando...@gmail.com on 28 May 2015 at 3:20

GoogleCodeExporter commented 8 years ago
I posted detailed steps with the screenshots on Stackoverflow to lay out the 
solution that worked for me.

http://stackoverflow.com/a/30497154/732945

Original comment by it-produ...@cantaloupesys.com on 28 May 2015 at 4:26

GoogleCodeExporter commented 8 years ago
Please help me how to retrieve gmail contact details(Only Email ID) in c#.net 
(windows service)

I created new project and got client ID, Client Secret code, generated p12key  
but still not able to fetch records.. i created project with service account 
type.

Original comment by sangeeth...@gmail.com on 28 May 2015 at 9:42

GoogleCodeExporter commented 8 years ago
@Alex - yeah, saw that - brilliant and thanks for doing that. I found a 
solution that works for me. Not sure why Sangeeth and Fernando are still having 
issues - just follow the steps outlined and that ought to fix it.

Original comment by evilstee...@gmail.com on 28 May 2015 at 12:05

GoogleCodeExporter commented 8 years ago
[deleted comment]
GoogleCodeExporter commented 8 years ago
Please Find my code
Am still getting error.
Help me plz

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPSnippets.GoogleAPI;
using System.Web.Script.Serialization;
using System.Data;
using Google.GData.Extensions.Apps;
using Google.GData.Client;
using Google.Contacts;

public partial class Default2 : System.Web.UI.Page
{
    private static string clientId;
    private static string clientSecret;
    private static string domain;
    private static string applicationName = "Test-OAuth2";
    private static string redirectUri = "http://localhost:51598/WebSite1/Default2.aspx";
    private static string scopes = "https://www.google.com/m8/feeds/";
    protected void Page_Load(object sender, EventArgs e)
    {
        clientId = "clientid";
        clientSecret = "secret code";
        domain = "";
        OAuth2Parameters parameters = new OAuth2Parameters()
        {
            ClientId = clientId,
            ClientSecret = clientSecret,
            RedirectUri = redirectUri,
            Scope = scopes
        };

        string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
        Console.WriteLine("Authorize URI: " + url);
        parameters.AccessCode = Console.ReadLine();
        parameters.AccessCode = "Authorize URI: " + url;

        OAuthUtil.GetAccessToken(parameters);

        // Testing OAuth 2.0 with a Request-based library
        RunContactsSample(parameters);

    }
    private static void RunContactsSample(OAuth2Parameters parameters)
    {
        try
        {
            RequestSettings settings = new RequestSettings(applicationName, parameters);
            ContactsRequest cr = new ContactsRequest(settings);

            Feed<Contact> f = cr.GetContacts();
            foreach (Contact c in f.Entries)
            {
                Console.WriteLine(c.Name.FullName);
            }
        }
        catch (Exception a)
        {
            Console.WriteLine("A Google Apps error occurred.");
            Console.WriteLine();
        }
    }
}

Original comment by sangeeth...@gmail.com on 28 May 2015 at 12:33

GoogleCodeExporter commented 8 years ago
Hi, evilstee... your solution looks pretty good, well commented, etc. We have 
the user visiting a URL manually (outside our application, via web browser) and 
pasting in the "authorization code" that he receives from Google OAuth. I am 
wondering if that can be automated? In my case, I know the user's Google login 
and password because... the user is me! It's a personal app just for me. I 
would like to automate that exchange and skip the manual copy-and-paste of the 
authorization code. Any ideas?

Original comment by w3jgvo...@gmail.com on 29 May 2015 at 4:15

GoogleCodeExporter commented 8 years ago
w3jgvo - you need to use Service Account to automate it. Check #33, this does 
not require manual copy-paste.

Original comment by a...@ua.fm on 29 May 2015 at 4:59

GoogleCodeExporter commented 8 years ago
#33 it's with service account, not for Blogger API. Any ideas?

Original comment by carlosma...@gmail.com on 29 May 2015 at 11:24

GoogleCodeExporter commented 8 years ago
authentication to google was working fine but now it throwing error: An 
unhandled exception of type 'Google.GData.Client.GDataRequestException' 
occurred in Google.GData.Client.dll

Additional information: Execution of authentication request returned unexpected 
result: 404
please solve it as soon as possible

Original comment by amitkana...@gmail.com on 29 May 2015 at 2:31

GoogleCodeExporter commented 8 years ago
Thanks Alex. Yeah, #33 it's the solution.

Original comment by fernando...@gmail.com on 30 May 2015 at 6:00

GoogleCodeExporter commented 8 years ago

I implement the solution from #33 in Script task in SSIS, but ny execute i 
receive message "Could not load file or assembly 
'Google.Apis.Auth.PlatformServices, Version=1.9.1.12399, Culture=neutral, 
PublicKeyToken=null' or one of its dependencies. The system cannot find the 
file specified."

i think it because the reference Google.Apis.Auth.PlatformServices from Nuget 
has not strong name and cannot install to GAC.

Please help me, what need I do?

Original comment by anton.sm...@friendsurance.de on 1 Jun 2015 at 2:01

GoogleCodeExporter commented 8 years ago

Thanks #31 for the solution provided. This works fine for me for accessing 
docs/spreadsheets.
However, I am getting the following error when I try to upload a document to 
the google drive:
"When performing a write operation with AllowWriteStreamBuffering set to false, 
you must either set ContentLength to a non-negative number or set SendChunked 
to true."

My code for uploading documents is:

GOAuth2RequestFactory requestFactory = RefreshAuthenticate();   
DocumentsService service = new 
DocumentsService("MyDocumentsListIntegration-v1"); service.RequestFactory = 
requestFactory; 
DocumentEntry entry = 
service.UploadDocument("C:\TempGoogleDocFolder\Test.docx", "Test");

The RefreshAuthenticate() function is coded as described above in #31.

Any ideas what is causing this or how it can be resolved?

Original comment by johncus...@arantico.com on 2 Jun 2015 at 11:21

GoogleCodeExporter commented 8 years ago
  protected void Page_Load(object sender, EventArgs e)
    {

        if (Session["Access_Token"] != null)
        {
            //For Google Contacts in case of page reload or 'Import from Gmail button' reclicked

            //Same button's click event has been fired using Javascript
            ScriptManager.RegisterStartupScript(this, this.GetType(), "googleContactclick", "<script>GoogleContacts();;</Script>", false);

            //In GoogleContacts() javascript I've fired button's click event.
        }

        else if (Request.QueryString["code"] != null)
        {
            //For Google Contacts while returning from Google SignIN page
            OAuth2Parameters parameters = new OAuth2Parameters();
            parameters.ClientId = "";
            parameters.ClientSecret = "";
            parameters.RedirectUri = "http://localhost:56943/WebSite4/page3.aspx";
            //parameters.Scope = "https://www.google.com/m8/feeds";
            parameters.Scope = "https://www.googleapis.com/auth/contacts.readonly";
            parameters.ResponseType = "code";
            parameters.AccessCode = Request.QueryString["code"];
            string accecode = parameters.AccessCode;
            OAuthUtil.GetAccessToken(parameters);

            Session["Access_Token"] = parameters.AccessToken;
            string aaa = parameters.AccessToken;
            //Response.Redirect("~/YourCurrentPage.aspx");
            RequestSettings rs = new RequestSettings("MyApplicationName", Session["Access_Token"].ToString());
            rs.AutoPaging = true;
            ContactsRequest cr = new ContactsRequest(rs);

            //Function that retrieves all my google contacts and binds to the grid.
            BindGoogleGrid(cr);
        }
     }
    public void BindGoogleGrid(ContactsRequest cr)
    {

        string Fullname = "";
        string EmailID = "";
        string FirstName = "";
        string LastName = "";

        try
        {
            Feed<Contact> f = cr.GetContacts();

            DataSet dtImportedContacts = new DataSet();

            DataTable dtName = new DataTable();

            //dtName.Columns.Add("Name");
            dtName.Columns.Add("FirstName");
            dtName.Columns.Add("LastName");
            dtName.Columns.Add("EmailID");

            foreach (Contact entry in f.Entries)
            {

                //EMail email = entry.Emails[0];
                if (entry.Emails.Count > 0)
                {
                    //for fetching EmailID
                    foreach (EMail email in entry.Emails)
                    {
                        if (email != null)
                        {
                            EmailID = entry.Emails[0].Address;
                            if (EmailID == string.Empty)
                                EmailID = "";
                        }
                        else
                        {
                            EmailID = "";
                        }
                    }

                    //For fetching Contact Name
                    if (entry.Name != null)
                    {
                        Name name = entry.Name;

                        if (!string.IsNullOrEmpty(name.FullName))
                        {
                            Fullname = name.FullName;
                            var Name = name.FullName.Split(' ');

                            if (Name.Length >= 2)
                            {
                                FirstName = Name[0];
                                LastName = Name[1];
                            }

                            else
                            {
                                FirstName = Name[0];
                                LastName = "";
                            }

                        }

                        else
                        {
                            FirstName = "";
                            LastName = "";
                        }

                    }

                    else
                    {
                        FirstName = "";
                        LastName = "";
                    }

                    dtName.Rows.Add(FirstName, LastName, EmailID);
                }
            }

            dtImportedContacts.Tables.Add(dtName);

            if (dtImportedContacts.Tables[0].Rows.Count < 0)
            {

                //lbl.Text = "No Contacts Found";

            }

            else
            {
              //  ImgBtnGImportAdd.Visible = true;

                GridView1.DataSource = dtImportedContacts;
                GridView1.DataBind();

            }

        }

        catch (Exception ex)
        {
          // lbl.Text = ex.Message;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Session["Access_Token"] != null)
        {
            RequestSettings rs = new RequestSettings("MyApplicationName", Session["Access_Token"].ToString());
            rs.AutoPaging = true;
            ContactsRequest cr = new ContactsRequest(rs);

            //Function that retrieves all my google contacts and binds to the grid.
            BindGoogleGrid(cr);
        }

        else //no auth data, print link
        {

            OAuth2Parameters parameters = new OAuth2Parameters();

            parameters.ClientId = "";
            parameters.ClientSecret = "";
            parameters.RedirectUri = "http://localhost:56943/WebSite4/page3.aspx";
            parameters.Scope = "https://www.google.com/m8/feeds";
            parameters.ResponseType = "code";

            Response.Redirect(OAuthUtil.CreateOAuth2AuthorizationUrl(parameters));

        }
    }

This code is working well with webApplication(Aap.Net)
Please help me how to make this code run with dekstop Application(Windows 
Form)..
Its urgent for me my working system got stopped

Original comment by amitgson...@gmail.com on 5 Jun 2015 at 4:58

GoogleCodeExporter commented 8 years ago
#43 It can't find the new dlls. I resolved this by copying them to the Binn 
folder of the DTS execution program (default: C:\Program Files (x86)\Microsoft 
SQL Server\120\DTS\Binn\). I believe by registering them in the GAC this 
problem would also be resolved.

Original comment by Spartan1...@gmail.com on 5 Jun 2015 at 6:53

GoogleCodeExporter commented 8 years ago
#33 - Does anybody know how to get this working with the SpreadsheetService 
from the python gdata libraries?

I've got this far:

    flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE,
                               redirect_uri=REDIRECT_URI)
    authorize_url = flow.step1_get_authorize_url()
    code = raw_input('Enter verification code: ').strip()
    credentials = flow.step2_exchange(code)

But I can't see how to use the credentials with SpreadsheetService.  The 
examples in the docs show how to use the credentials with the Drive API, like 
this:

    # Create an httplib2.Http object and authorize it with our credentials
    http = httplib2.Http()
    http = credentials.authorize(http)

    drive_service = build('drive', 'v2', http=http)

But again SpreadsheetService doesn't seem to have a way to set the authorized 
http object.

Any clues much appreciated.

Original comment by Carlos.R...@celoxica.com on 5 Jun 2015 at 1:52

GoogleCodeExporter commented 8 years ago
i need to save user accounts on google api.  I need a .net code to do the 
authorization first then need to code to do the saving part. 

Original comment by varsha.a...@umail.uom.ac.mu on 2 Jul 2015 at 9:49

GoogleCodeExporter commented 8 years ago
[deleted comment]
GoogleCodeExporter commented 8 years ago
please help me how to read google document from google drive ...
am getting this error
Execution of request failed: https://docs.google.com/feeds/default/private/full

below mentioned is my code :
 OAuth2Parameters parameters = new OAuth2Parameters();
      parameters.ClientId = CLIENT_ID;
      parameters.ClientSecret = CLIENT_SECRET;
      parameters.RedirectUri = REDIRECT_URI;
      parameters.Scope = SCOPE;
      parameters.AccessType = "offline"; // IMPORTANT and was missing in the original
      parameters.TokenType = TOKEN_TYPE; // IMPORTANT and was missing in the original
      parameters.ResponseType = "code";
      //string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
      //Console.WriteLine(authorizationUrl);
      parameters.AccessCode = Request.QueryString["code"];
      string accecode = parameters.AccessCode;
        if (accecode == null)
       {
           Button1_Click(null, null);
       }
      //parameters.AccessCode = Console.ReadLine();
      OAuthUtil.GetAccessToken(parameters);
       accessToken = parameters.AccessToken;
      refreshToken = parameters.RefreshToken;
 GOAuth2RequestFactory requestFactory = RefreshAuthenticate();

        Google.GData.Documents.DocumentsListQuery query = new Google.GData.Documents.DocumentsListQuery();

        Google.GData.Documents.DocumentsFeed feed = d_service.Query(query);
        var docs = new List<string>();
        foreach (DocumentEntry entry in feed.Entries)
        {
            docs.Add(entry.Title.Text);
        }

Original comment by sangeeth...@gmail.com on 22 Jul 2015 at 12:51