/// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Use a test account for which 2 factor authentication has been enabled.
              string loginEmail = "*****@*****.**";
              string password = "******";

              AdWordsAppConfig config = new AdWordsAppConfig();
              config.Email = loginEmail;
              config.Password = password;
              AuthToken authToken = new AuthToken(config, "adwords");

              try {
            // Try to obtain an authToken.
            string token = authToken.GetToken();
            Console.WriteLine("Retrieved an authToken = {0} for user {1}.", token, loginEmail);
              } catch (AuthTokenException ex) {
            // Since the test account has 2 factor authentication enabled, this block
            // of code will be executed.
            if (ex.ErrorCode == AuthTokenErrorCode.BadAuthentication) {
              if (ex.Info == "InvalidSecondFactor") {
            Console.WriteLine("The user has enabled two factor authentication in this " +
                "account. Have the user generate an application-specific password to make " +
                "calls against the AdWords API. See " +
                "http://adwordsapi.blogspot.com/2011/02/authentication-changes-with-2-step.html" +
                " for more details.");
              } else {
            Console.WriteLine("Invalid credentials.");
              }
            } else {
              throw new System.ApplicationException(String.Format("The server raised an {0} error.",
              ex.ErrorCode));
            }
              }
        }
 /// <summary>
 /// Handles the Load event of the Page control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.EventArgs"/> instance containing
 /// the event data.</param>
 protected void Page_Load(object sender, EventArgs e) {
   // Create an AdWordsAppConfig object with the default settings in
   // App.config.
   AdWordsAppConfig config = new AdWordsAppConfig();
   if (config.OAuth2Mode == OAuth2Flow.APPLICATION &&
       string.IsNullOrEmpty(config.OAuth2RefreshToken)) {
     DoAuth2Configuration(config);
   }
 }
    private void DoAuth2Configuration(AdWordsAppConfig config) {
      // Since we use this page for OAuth callback also, we set the callback
      // url as the current page. For a non-web application, this will be null.
      config.OAuth2RedirectUri = Request.Url.GetLeftPart(UriPartial.Path);

      // Create an OAuth2 object for handling OAuth2 flow.
      OAuth2ProviderForApplications oAuth = new OAuth2ProviderForApplications(config);

      if (Request.Params["state"] == null) {
        // This is the first time this page is being loaded.
        // Set the state variable to any value that helps you recognize
        // when this url will be called by the OAuth2 server.
        oAuth.State = "callback";

        // Create an authorization url and redirect the user to that page.
        Response.Redirect(oAuth.GetAuthorizationUrl());
      } else if (Request.Params["state"] == "callback") {
        // This page was loaded because OAuth server did a callback.
        // Retrieve the authorization code from the url and use it to fetch
        // the access token. This call will also fetch the refresh token if
        // your mode is offline.
        oAuth.FetchAccessAndRefreshTokens(Request.Params["code"]);

        // Save the OAuth2 provider for future use. If you wish to save only
        // the values and restore the object later, then save
        // oAuth.RefreshToken, oAuth.AccessToken, oAuth.UpdatedOn and
        // oAuth.ExpiresIn.
        //
        // You can later restore the values as
        // AdWordsUser user = new AdWordsUser();
        // user.Config.OAuth2Mode = OAuth2Flow.APPLICATION;
        // OAuth2ProviderForApplications oAuth =
        //     (user.OAuthProvider as OAuth2ProviderForApplications);
        // oAuth.RefreshToken = xxx;
        // oAuth.AccessToken = xxx;
        // oAuth.UpdatedOn = xxx;
        // oAuth.ExpiresIn = xxx;
        //
        // Note that only oAuth.RefreshToken is mandatory. If you leave
        // oAuth.AccessToken as empty, or if oAuth.UpdatedOn + oAuth.ExpiresIn
        // is in the past, the access token will be refreshed by the library.
        // You can listen to this event as
        //
        // oAuth.OnOAuthTokensObtained += delegate(AdsOAuthProvider provider) {
        //    OAuth2ProviderForApplications oAuth =
        //        (provider as OAuth2ProviderForApplications);
        //    // Save oAuth.RefreshToken, oAuth.AccessToken, oAuth.UpdatedOn and
        //    // oAuth.ExpiresIn.
        //};
        Session["OAuthProvider"] = oAuth;
        // Redirect the user to the main page.
        Response.Redirect("Default.aspx");
      } else {
        throw new Exception("Unknown state for OAuth callback.");
      }
    }
        /// <summary>
        /// Reads the headers from App.config.
        /// </summary>
        /// <param name="config">The configuration class.</param>
        protected override void ReadHeadersFromConfig(AppConfig config)
        {
            AdWordsAppConfig awConfig = (AdWordsAppConfig)config;

            this.requestHeader = new RequestHeader();

            if (!string.IsNullOrEmpty(awConfig.ClientCustomerId))
            {
                requestHeader.clientCustomerId = awConfig.ClientCustomerId;
            }
            requestHeader.developerToken = awConfig.DeveloperToken;
        }
    public void Init() {
      campaignId = utils.CreateSearchCampaign(user, BiddingStrategyType.MANUAL_CPC);
      adGroupId1 = utils.CreateAdGroup(user, campaignId);
      adGroupId2 = utils.CreateAdGroup(user, campaignId);

      // Load defaults from config file.
      AdWordsAppConfig appConfig = new AdWordsAppConfig();
      appConfig.OAuth2RefreshToken = appConfig.GMBOAuth2RefreshToken;

      AdsOAuthProviderForApplications oAuth2Provider = new OAuth2ProviderForApplications(appConfig);
      oAuth2Provider.RefreshAccessToken();
    }
Exemple #6
0
        /// <summary>
        /// Initializes the service before MakeApiCall.
        /// </summary>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="parameters">The method parameters.</param>
        protected override void InitForCall(string methodName, object[] parameters)
        {
            AdWordsAppConfig config = this.User.Config as AdWordsAppConfig;
            RequestHeader    header = GetRequestHeader();

            if (string.IsNullOrEmpty(header.developerToken))
            {
                throw new ArgumentNullException(AdWordsErrorMessages.DeveloperTokenCannotBeEmpty);
            }

            if (string.IsNullOrEmpty(header.clientCustomerId))
            {
                TraceUtilities.WriteGeneralWarnings(AdWordsErrorMessages.ClientCustomerIdIsEmpty);
            }

            // Validate Express business headers.
            if (this.Signature.ServiceName == "PromotionService")
            {
                if (header.expressBusinessIdSpecified && header.pageIdSpecified)
                {
                    throw new ArgumentException(AdWordsErrorMessages.OnlyOneExpressHeaderShouldBeSpecified);
                }
                else if (!header.expressBusinessIdSpecified && !header.pageIdSpecified)
                {
                    throw new ArgumentException(AdWordsErrorMessages.MissingExpressHeaders + ' ' +
                                                AdWordsErrorMessages.OnlyOneExpressHeaderShouldBeSpecified);
                }
            }
            else
            {
                if (header.expressBusinessIdSpecified || header.pageIdSpecified)
                {
                    throw new ArgumentException(AdWordsErrorMessages.ExpressHeadersShouldNotBeSpecified);
                }
            }

            header.userAgent = config.GetUserAgent();

            string oAuthHeader = null;

            if (this.User.OAuthProvider != null)
            {
                oAuthHeader = this.User.OAuthProvider.GetAuthHeader();
            }
            else
            {
                throw new AdWordsApiException(null, AdWordsErrorMessages.OAuthProviderCannotBeNull);
            }
            ContextStore.AddKey("OAuthHeader", oAuthHeader);
            base.InitForCall(methodName, parameters);
        }
        /// <summary>
        /// Create a service object.
        /// </summary>
        /// <param name="signature">Signature of the service being created.</param>
        /// <param name="user">The user for which the service is being created.
        /// <param name="serverUrl">The server to which the API calls should be
        /// made.</param>
        /// </param>
        /// <returns>An object of the desired service type.</returns>
        public override AdsClient CreateService(ServiceSignature signature, AdsUser user,
                                                Uri serverUrl)
        {
            AdWordsAppConfig awConfig = (AdWordsAppConfig)Config;

            if (serverUrl == null)
            {
                serverUrl = new Uri(awConfig.AdWordsApiServer);
            }

            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            CheckServicePreconditions(signature);

            AdWordsServiceSignature awapiSignature = signature as AdWordsServiceSignature;

            AdsClient    service  = (AdsClient)Activator.CreateInstance(awapiSignature.ServiceType);
            PropertyInfo propInfo = awapiSignature.ServiceType.GetProperty("RequestHeader");

            if (propInfo != null)
            {
                RequestHeader clonedHeader = (RequestHeader)requestHeader.Clone();
                clonedHeader.Version   = awapiSignature.Version;
                clonedHeader.GroupName = awapiSignature.GroupName;
                propInfo.SetValue(service, clonedHeader, null);
            }

            if (awConfig.Proxy != null)
            {
                service.Proxy = awConfig.Proxy;
            }
            service.Timeout = awConfig.Timeout;
            service.Url     = string.Format("{0}api/adwords/{1}/{2}/{3}",
                                            serverUrl.AbsoluteUri, awapiSignature.GroupName, awapiSignature.Version,
                                            awapiSignature.ServiceName);
            service.EnableDecompression = awConfig.EnableGzipCompression;
            service.User      = user;
            service.Signature = awapiSignature;
            return(service);
        }
 /// <summary>
 /// Public constructor. Use this version if you want to construct
 /// an AdWordsUser with a custom configuration.
 /// </summary>
 public AdWordsUser(AdWordsAppConfig config) : base(config)
 {
 }
        /// <summary>
        /// Create a service object.
        /// </summary>
        /// <param name="signature">Signature of the service being created.</param>
        /// <param name="user">The user for which the service is being created.</param>
        /// <param name="serverUrl">The server to which the API calls should be
        /// made.</param>
        /// <returns>An object of the desired service type.</returns>
        public override AdsClient CreateService(ServiceSignature signature, AdsUser user,
                                                Uri serverUrl)
        {
            AdWordsAppConfig awConfig = (AdWordsAppConfig)Config;

            if (serverUrl == null)
            {
                serverUrl = new Uri(awConfig.AdWordsApiServer);
            }

            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            CheckServicePreconditions(signature);

            AdWordsServiceSignature awapiSignature = signature as AdWordsServiceSignature;
            EndpointAddress         endpoint       = new EndpointAddress(string.Format(ENDPOINT_TEMPLATE,
                                                                                       serverUrl, awapiSignature.GroupName, awapiSignature.Version,
                                                                                       awapiSignature.ServiceName));

            // Create the binding for the service.
            BasicHttpBinding binding = new BasicHttpBinding();

            binding.Security.Mode = BasicHttpSecurityMode.Transport;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            binding.MaxReceivedMessageSize = int.MaxValue;
            binding.TextEncoding           = Encoding.UTF8;

            AdsClient service = (AdsClient)Activator.CreateInstance(
                awapiSignature.ServiceType,
                new object[] { binding, endpoint });

            ServiceEndpoint serviceEndpoint =
                (ServiceEndpoint)service.GetType().GetProperty("Endpoint").GetValue(service, null);

            AdsServiceInspectorBehavior inspectorBehavior = new AdsServiceInspectorBehavior();

            inspectorBehavior.Add(new OAuth2ClientMessageInspector(user.OAuthProvider));

            RequestHeader clonedHeader = (RequestHeader)requestHeader.Clone();

            clonedHeader.Version   = awapiSignature.Version;
            clonedHeader.GroupName = awapiSignature.GroupName;
            inspectorBehavior.Add(new AdWordsSoapHeaderInspector()
            {
                RequestHeader = clonedHeader,
                User          = (AdWordsUser)user,
            });
            inspectorBehavior.Add(new SoapListenerInspector(user, awapiSignature.ServiceName));
            inspectorBehavior.Add(new SoapFaultInspector <AdWordsApiException>()
            {
                ErrorType = awapiSignature.ServiceType.Assembly.GetType(
                    awapiSignature.ServiceType.Namespace + ".ApiException")
            });
#if NET452
            serviceEndpoint.Behaviors.Add(inspectorBehavior);
#else
            serviceEndpoint.EndpointBehaviors.Add(inspectorBehavior);
#endif

            if (awConfig.Proxy != null)
            {
                service.Proxy = awConfig.Proxy;
            }
            service.Timeout             = awConfig.Timeout;
            service.EnableDecompression = awConfig.EnableGzipCompression;
            service.User      = user;
            service.Signature = awapiSignature;
            return(service);
        }
 /// <summary>
 /// Gets the OAuth scope parameter for getting request token.
 /// </summary>
 /// <returns>The OAuth scope parameter for AdWords API.</returns>
 public static string GetOAuthScope(AdWordsAppConfig config) {
   return string.Format("{0}/api/adwords/", config.AdWordsApiServer);
 }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="gmbEmailAddress">The email address for Google My Business
    /// account.</param>
    /// <param name="gmbAccessToken">The OAuth2 access token for Google
    /// My Business account.</param>
    /// <param name="businessAccountIdentifier">The account identifier for
    /// Google My Business account.</param>
    public void Run(AdWordsUser user, string gmbEmailAddress, string gmbAccessToken,
        string businessAccountIdentifier) {
      FeedService feedService = (FeedService) user.GetService(AdWordsService.v201409.FeedService);

      CustomerFeedService customerFeedService = (CustomerFeedService) user.GetService(
          AdWordsService.v201409.CustomerFeedService);

      // Create a feed that will sync to the Google My Business account
      // specified by gmbEmailAddress. Do not add FeedAttributes to this object,
      // as AdWords will add them automatically because this will be a
      // system generated feed.
      Feed gmbFeed = new Feed();
      gmbFeed.name = String.Format("Google My Business feed #{0}",
          ExampleUtilities.GetRandomString());

      PlacesLocationFeedData feedData = new PlacesLocationFeedData();
      feedData.emailAddress = gmbEmailAddress;
      feedData.businessAccountIdentifier = businessAccountIdentifier;

      OAuthInfo oAuthInfo = new OAuthInfo();
      oAuthInfo.httpMethod = "GET";

      // Permissions for the AdWords API scope will also cover GMB.
      oAuthInfo.httpRequestUrl = user.Config.GetDefaultOAuth2Scope();
      oAuthInfo.httpAuthorizationHeader = string.Format("Bearer {0}", gmbAccessToken);
      feedData.oAuthInfo = oAuthInfo;

      gmbFeed.systemFeedGenerationData = feedData;

      // Since this feed's feed items will be managed by AdWords,
      // you must set its origin to ADWORDS.
      gmbFeed.origin = FeedOrigin.ADWORDS;

      // Create an operation to add the feed.
      FeedOperation feedOperation = new FeedOperation();
      feedOperation.operand = gmbFeed;
      feedOperation.@operator = Operator.ADD;

      try {
        // Add the feed. Since it is a system generated feed, AdWords will
        // automatically:
        // 1. Set up the FeedAttributes on the feed.
        // 2. Set up a FeedMapping that associates the FeedAttributes of the
        //    feed with the placeholder fields of the LOCATION placeholder
        //    type.
        FeedReturnValue addFeedResult = feedService.mutate(new FeedOperation[] { feedOperation });
        Feed addedFeed = addFeedResult.value[0];
        Console.WriteLine("Added GMB feed with ID {0}", addedFeed.id);

        // Add a CustomerFeed that associates the feed with this customer for
        // the LOCATION placeholder type.
        CustomerFeed customerFeed = new CustomerFeed();
        customerFeed.feedId = addedFeed.id;
        customerFeed.placeholderTypes = new int[] { PLACEHOLDER_LOCATION };

        // Create a matching function that will always evaluate to true.
        Function customerMatchingFunction = new Function();
        ConstantOperand constOperand = new ConstantOperand();
        constOperand.type = ConstantOperandConstantType.BOOLEAN;
        constOperand.booleanValue = true;
        customerMatchingFunction.lhsOperand = new FunctionArgumentOperand[] { constOperand };
        customerMatchingFunction.@operator = FunctionOperator.IDENTITY;
        customerFeed.matchingFunction = customerMatchingFunction;

        // Create an operation to add the customer feed.
        CustomerFeedOperation customerFeedOperation = new CustomerFeedOperation();
        customerFeedOperation.operand = customerFeed;
        customerFeedOperation.@operator = Operator.ADD;

        // After the completion of the Feed ADD operation above the added feed
        // will not be available for usage in a CustomerFeed until the sync
        // between the AdWords and GMB accounts completes.  The loop below
        // will retry adding the CustomerFeed up to ten times with an
        // exponential back-off policy.
        CustomerFeed addedCustomerFeed = null;

        AdWordsAppConfig config = new AdWordsAppConfig();
        config.RetryCount = 10;

        ErrorHandler errorHandler = new ErrorHandler(config);
        do {
          try {
            CustomerFeedReturnValue customerFeedResult =
                customerFeedService.mutate(new CustomerFeedOperation[] { customerFeedOperation });
            addedCustomerFeed = customerFeedResult.value[0];

            Console.WriteLine("Added CustomerFeed for feed ID {0} and placeholder type {1}",
                addedCustomerFeed.feedId, addedCustomerFeed.placeholderTypes[0]);
            break;
          } catch (AdWordsApiException e) {
            ApiException apiException = (ApiException) e.ApiException;
            foreach (ApiError error in apiException.errors) {
              if (error is CustomerFeedError) {
                if ((error as CustomerFeedError).reason ==
                    CustomerFeedErrorReason.MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE) {
                  errorHandler.DoExponentialBackoff();
                  errorHandler.IncrementRetriedAttempts();
                } else {
                  throw;
                }
              }
            }
          }
        } while (errorHandler.HaveMoreRetryAttemptsLeft());

        // OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at
        // the Campaign level.  This will be similar to the CampaignFeed in the
        // AddSiteLinks example, except you can also filter based on the
        // business name and category of each FeedItem by using a
        // FeedAttributeOperand in your matching function.

        // OPTIONAL: Create an AdGroupFeed for even more fine grained control
        // over which feed items are used at the AdGroup level.
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to create customer feed.", ex);
      }
    }
 private void ConfigureForOAuth2()
 {
     AdWordsAppConfig config = new AdWordsAppConfig();
       config.AuthorizationMethod = AdWordsAuthorizationMethod.OAuth2;
       serviceFactory.Config = config;
 }
 private void ConfigureForClientLogin()
 {
     AdWordsAppConfig config = new AdWordsAppConfig();
       config.AuthorizationMethod = AdWordsAuthorizationMethod.ClientLogin;
       serviceFactory.Config = config;
 }
 /// <summary>
 /// Gets a useragent string that can be used with the library.
 /// </summary>
 protected string GetUseragent(AdWordsAppConfig awConfig) {
   return String.Join("", new string[] {awConfig.Signature, "|", awConfig.UserAgent});
 }
 /// <summary>
 /// Initializes the <see cref="AdWordsRequestInterceptor"/> class.
 /// </summary>
 static AdWordsRequestInterceptor() {
   AdWordsAppConfig config = new AdWordsAppConfig();
   instance = new AdWordsRequestInterceptor();
   WebRequest.RegisterPrefix(config.AdWordsApiServer, instance);
 }