Receiving Error with DoAuth2Authorization trying to follow ConsoleExample.cs

134 views
Skip to first unread message

Mike Schwartz

unread,
Jun 20, 2018, 5:02:18 AM6/20/18
to AdWords API and Google Ads API Forum

Hi All, 

 

Looking for a bit of help with an error I'm getting while trying to follow ConsoleExample.cs located here. The error occurs in DoAuth2Authorization at the GetAuthorization line and I’m not sure of the cause.

 

Line that errors:

 

string authorizationUrl = oAuth2Provider.GetAuthorizationUrl();

 

The error I’m getting is:

 

System.NullReferenceException: Object reference not set to an instance of an object.

   at Google.Apis.Requests.Parameters.ParameterUtils.<>c__DisplayClass3_0.<InitParameters>b__0(RequestParameterType type, String name, Object value) in C:\Apiary\2018-05-10.07-58-36\Src\Support\Google.Apis.Core\Requests\Parameters\ParameterUtils.cs:line 92

   at Google.Apis.Requests.Parameters.ParameterUtils.IterateParameters(Object request, Action`3 action) in C:\Apiary\2018-05-10.07-58-36\Src\Support\Google.Apis.Core\Requests\Parameters\ParameterUtils.cs:line 131

   at Google.Apis.Auth.OAuth2.Requests.AuthorizationCodeRequestUrl.Build() in C:\Apiary\2018-05-10.07-58-36\Src\Support\Google.Apis.Auth\OAuth2\Requests\AuthorizationCodeRequestUrl.cs:line 50

   at Google.Api.Ads.Common.OAuth.AdsOAuthProviderImpl.CreateAuthorizationUrl(String redirectUri)

   at GoogleAdwords_v2.Program.DoAuth2Authorization(AdWordsUser user) in C:\Users\mschwartz\source\repos\GoogleAdwords_v2\GoogleAdwords_v2\Program.cs:line 155



Code: 







using Google.Api.Ads.AdWords.Lib;

using Google.Api.Ads.AdWords.v201806;

using Google.Api.Ads.Common.Lib;

using System;

using System.Configuration;

using System.IO;


namespace GoogleAdwords_v2

{

   
class Program

   
{

       
static void Main(string[] args)

       
{

           




           
AdWordsUser user = new AdWordsUser();

           
AdWordsAppConfig config = user.Config as AdWordsAppConfig;

            config
.OAuth2RedirectUri = "http://localhost";

            config
.OAuth2Scope = "https://www.googleapis.com/auth/adwords";

            config
.DeveloperToken = "hidden";

            config
.OAuth2ClientId = "hidden";

            config
.OAuth2ClientSecret = "hidden";

            config
.OAuth2Mode = OAuth2Flow.APPLICATION;

            config
.ClientCustomerId = "hidden";

           
//used to get the initial refresh token

           
if (user.Config.OAuth2Mode == OAuth2Flow.APPLICATION && string.IsNullOrEmpty(config.OAuth2RefreshToken))

               
{

                   
DoAuth2Authorization(user);

               
}







           
//Parsing Arguments (date range)

   

           
string startDate;

           
string endDate;




           
if (args.Length == 0) //default daily run is yesterday's data

           
{

               
string previousDay = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");

                startDate
= previousDay;

                endDate
= previousDay;

           
}

           
else if (args.Length == 2)

           
{

             

                startDate
= args[0];

                endDate
= args[1];




           
}

           
else

           
{

               
Console.WriteLine("Invalid Parameters Entered");

               
Console.WriteLine("Reminder: No Parameters for \"Yesterday\"  OR \"\"StartDate\" \"EndDate\" ");

               
Console.WriteLine("Date Format Reminder: \"YYYY-MM-DD\"  ");

               
throw new ArgumentException(String.Format("Incorrect number of paramters entered. Valid parameter counts are 0 or 2.  {0} parameters were entered.", args.Length));

           
}




     

           
var dateRange = new DateRange()

           
{

                min
= startDate,

                max
= endDate

           
};




           
CampaignService campaignService =

                   
(CampaignService)user.GetService(AdWordsService.v201806.CampaignService);




           
Selector selector = new Selector()

           
{

                fields
= new String[] { Campaign.Fields.Name, Campaign.Fields.Id },

                paging
= Paging.Default,

                dateRange
= dateRange

           
};

           




             




           
CampaignPage page = new CampaignPage();




           
try

           
{

               
do

               
{

                    page
= campaignService.get(selector);




                   
if (page != null && page.entries != null)

                   
{

                       
int i = selector.paging.startIndex;

                       
foreach (Campaign campaign in page.entries)

                       
{

                           
Console.WriteLine("{0}) Campaign with id = '{1}', name = '{2}' and status = '{3}'" +

                             
" was found.", i + 1, campaign.id, campaign.name, campaign.status);

                            i
++;

                       
}




                   
}

                    selector
.paging.IncreaseOffset();

               
}

               
while (selector.paging.startIndex < page.totalNumEntries);

               
Console.WriteLine("Number of campaigns found: {0}", page.totalNumEntries);




           
}

           
catch(Exception ex)

           
{

               
throw new System.ApplicationException("Failed to retrieve campaigns", ex);

           
}

           
finally

           
{

               
Console.ReadKey();

           
}

           

         







       
}//end main




       
private static void DoAuth2Authorization(AdWordsUser user)

       
{

           
try  

           
{

               
// Since we are using a console application, set the callback url to null.

               
//user.Config.OAuth2RedirectUri = null;  // configured earlier, commented out and left for reference

               

               
Google.Api.Ads.Common.Lib.AdsOAuthProviderForApplications oAuth2Provider =

                   
(user.OAuthProvider as Google.Api.Ads.Common.Lib.AdsOAuthProviderForApplications);

               
// Get the authorization url.




               
string authorizationUrl = oAuth2Provider.GetAuthorizationUrl();  //<---- ERROR OCCURS HERE

               
Console.WriteLine("Open a fresh web browser and navigate to \n\n{0}\n\n. You will be " +

                   
"prompted to login and then authorize this application to make calls to the " +

                   
"AdWords API. Once approved, you will be presented with an authorization code.",

                    authorizationUrl
);




               
// Accept the OAuth2 authorization code from the user.

               
Console.Write("Enter the authorization code :");

               
string authorizationCode = Console.ReadLine();




               
// Fetch the access and refresh tokens.

                oAuth2Provider
.FetchAccessAndRefreshTokens(authorizationCode);




           
}

           
catch (Exception ex)

           
{

               
Console.WriteLine(ex);

       
Console.ReadKey();

           
}

         




       
} // end DoAuth2Authorization










   
}

}



Thanks in advance for any help you can provide

Mike

Dhanya Sundararaju (AdWords API Team)

unread,
Jun 20, 2018, 2:56:44 PM6/20/18
to AdWords API and Google Ads API Forum
Hi Mike,

I see that you are using the .NET client library. In your example, if you are using a console application, you will need to set the callback url to null. Also, please ensure that you are following the steps as mentioned in the README.md file and let me know if you have any further issues.

Regards,
Dhanya, AdWords API Team

Mike Schwartz

unread,
Jun 22, 2018, 9:51:38 AM6/22/18
to AdWords API and Google Ads API Forum
Hi Dhanya,  I tried with the callback URL as null and it kept returning an error that the redirectURI was invalid.  Once I set the redirectURI to localhost it started working.  To get the refresh token I used the code include as part of the .net zip here and created a separate application to request the refresh token and now I am able to send AWQL requests using that refresh token.   Regardless, there was something with the DoAuth2Authorization that kept erroring as detailed above, but since I found another method I have not investigated further.

Thanks,
Mike

Dhanya Sundararaju (AdWords API Team)

unread,
Jun 22, 2018, 2:27:43 PM6/22/18
to AdWords API and Google Ads API Forum
Hi Mike,

Glad to know that you were able to figure it out and thank you for letting us know. If you face any issues in the future, please feel free to write back.
Reply all
Reply to author
Forward
0 new messages