示例#1
0
            /// <summary>
            /// Creates an AdGroupCriterionOperation for the given criterion
            /// </summary>
            /// <param name="criterion">The criterion we want to add</param>
            private void CreateAddOperation(AdGroupCriterion criterion)
            {
                AdGroupCriterionOperation operation = new AdGroupCriterionOperation();

                operation.operand   = criterion;
                operation.@operator = Operator.ADD;
                this.operations.Add(operation);
            }
示例#2
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupId">The ad group to which new keyword ia added.</param>
        /// <param name="keywordText">The new keyword text.</param>
        public void Run(GoogleAdsClient client, long customerId, long adGroupId, string keywordText)
        {
            if (string.IsNullOrEmpty(keywordText))
            {
                keywordText = KEYWORD_TEXT;
            }
            // Get the AdGroupCriterionService.
            AdGroupCriterionServiceClient adGroupCriterionService =
                client.GetService(Services.V6.AdGroupCriterionService);

            // Create a keyword.
            AdGroupCriterion criterion = new AdGroupCriterion()
            {
                AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
                Status  = AdGroupCriterionStatus.Enabled,
                Keyword = new KeywordInfo()
                {
                    Text      = keywordText,
                    MatchType = KeywordMatchType.Exact
                }
            };

            // Create the operation.
            AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
            {
                Create = criterion,
            };

            try
            {
                // Add the keywords.
                MutateAdGroupCriteriaResponse retVal =
                    adGroupCriterionService.MutateAdGroupCriteria(customerId.ToString(),
                                                                  new AdGroupCriterionOperation[] { operation });

                // Display the results.
                if (retVal.Results.Count > 0)
                {
                    foreach (MutateAdGroupCriterionResult newCriterion in retVal.Results)
                    {
                        Console.WriteLine($"Created keyword with resource ID = " +
                                          "'{newCriterion.ResourceName}'.");
                    }
                }
                else
                {
                    Console.WriteLine("No keywords were added.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group that contains the keyword.
    /// </param>
    /// <param name="keywordId">Id of the keyword to be updated.</param>
    public void Run(AdWordsUser user, long adGroupId, long keywordId) {
      using (AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(
              AdWordsService.v201806.AdGroupCriterionService)) {

        // Since we are not updating any keyword-specific fields, it is enough to
        // create a criterion object.
        Criterion criterion = new Criterion();
        criterion.id = keywordId;

        // Create ad group criterion.
        BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion();
        biddableAdGroupCriterion.adGroupId = adGroupId;
        biddableAdGroupCriterion.criterion = criterion;

        // Create the bids.
        BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
        CpcBid cpcBid = new CpcBid();
        cpcBid.bid = new Money();
        cpcBid.bid.microAmount = 1000000;
        biddingConfig.bids = new Bids[] { cpcBid };

        biddableAdGroupCriterion.biddingStrategyConfiguration = biddingConfig;

        // Create the operation.
        AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
        operation.@operator = Operator.SET;
        operation.operand = biddableAdGroupCriterion;

        try {
          // Update the keyword.
          AdGroupCriterionReturnValue retVal =
              adGroupCriterionService.mutate(new AdGroupCriterionOperation[] { operation });

          // Display the results.
          if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
            AdGroupCriterion adGroupCriterion = retVal.value[0];
            long bidAmount = 0;
            foreach (Bids bids in (adGroupCriterion as BiddableAdGroupCriterion).
                biddingStrategyConfiguration.bids) {
              if (bids is CpcBid) {
                bidAmount = (bids as CpcBid).bid.microAmount;
                break;
              }
            }

            Console.WriteLine("Keyword with ad group id = '{0}', id = '{1}' was updated with " +
                "bid amount = '{2}' micros.", adGroupCriterion.adGroupId,
                adGroupCriterion.criterion.id, bidAmount);
          } else {
            Console.WriteLine("No keyword was updated.");
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to update keyword.", e);
        }
      }
    }
示例#4
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="adGroupId">ID of the ad group to which keywords are added.</param>
        /// <param name="keywordText">The keyword text to add to the ad group.</param>
        public void Run(GoogleAdsClient client, long customerId, long adGroupId,
                        string keywordText)
        {
            // Get the AdGroupCriterionServiceClient.
            AdGroupCriterionServiceClient service = client.GetService(
                Services.V4.AdGroupCriterionService);

            // Configures the keyword text and match type settings.
            KeywordInfo keywordInfo = new KeywordInfo()
            {
                Text      = keywordText,
                MatchType = KeywordMatchType.Exact
            };

            // Constructs an ad group criterion using the keyword text info above.
            AdGroupCriterion adGroupCriterion = new AdGroupCriterion()
            {
                AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
                Status  = AdGroupCriterionStatus.Paused,
                Keyword = keywordInfo
            };

            AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
            {
                Create = adGroupCriterion
            };

            try
            {
                try
                {
                    // Try sending a mutate request to add the keyword.
                    MutateAdGroupCriteriaResponse response = service.MutateAdGroupCriteria(
                        customerId.ToString(), new[] { operation });
                    Console.WriteLine($"Added a keyword with resource name " +
                                      $"'{response.Results[0].ResourceName}'.");
                }
                catch (GoogleAdsException ex)
                {
                    PolicyViolationKey[] exemptPolicyViolationKeys =
                        FetchExemptPolicyViolationKeys(ex);

                    // Try sending exemption requests for creating a keyword. However, if your
                    // keyword contains many policy violations, but not all of them are exemptible,
                    // the request will not be sent.
                    RequestExemption(customerId, service, operation, exemptPolicyViolationKeys);
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group to which placements are added.
    /// </param>
    public void Run(AdWordsUser user, long adGroupId) {
      // Get the AdGroupCriterionService.
      AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(AdWordsService.v201509.AdGroupCriterionService);

      // Create the placement.
      Placement placement1 = new Placement();
      placement1.url = "http://mars.google.com";

      // Create biddable ad group criterion.
      AdGroupCriterion placementCriterion1 = new BiddableAdGroupCriterion();
      placementCriterion1.adGroupId = adGroupId;
      placementCriterion1.criterion = placement1;

      // Create the placement.
      Placement placement2 = new Placement();
      placement2.url = "http://venus.google.com";

      // Create biddable ad group criterion.
      AdGroupCriterion placementCriterion2 = new BiddableAdGroupCriterion();
      placementCriterion2.adGroupId = adGroupId;
      placementCriterion2.criterion = placement2;

      // Create the operations.
      AdGroupCriterionOperation placementOperation1 = new AdGroupCriterionOperation();
      placementOperation1.@operator = Operator.ADD;
      placementOperation1.operand = placementCriterion1;

      AdGroupCriterionOperation placementOperation2 = new AdGroupCriterionOperation();
      placementOperation2.@operator = Operator.ADD;
      placementOperation2.operand = placementCriterion2;

      try {
        // Create the placements.
        AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(
            new AdGroupCriterionOperation[] {placementOperation1, placementOperation2});

        // Display the results.
        if (retVal != null && retVal.value != null) {
          foreach (AdGroupCriterion adGroupCriterion in retVal.value) {
            // If you are adding multiple type of criteria, then you may need to
            // check for
            //
            // if (adGroupCriterion is Placement) { ... }
            //
            // to identify the criterion type.
            Console.WriteLine("Placement with ad group id = '{0}, placement id = '{1}, url = " +
                "'{2}' was created.", adGroupCriterion.adGroupId,
                adGroupCriterion.criterion.id, (adGroupCriterion.criterion as Placement).url);
          }
        } else {
          Console.WriteLine("No placements were added.");
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to create placements.", e);
      }
    }
示例#6
0
        /// <summary>
        /// Set custom targeting for the page feed URLs based on a list of labels.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Ad group ID.</param>
        /// <param name="labelName">The label name.</param>
        /// <returns>The newly created webpage criterion.</returns>
        private static BiddableAdGroupCriterion AddDsaTargeting(AdWordsUser user, long adGroupId,
                                                                string labelName)
        {
            using (AdGroupCriterionService adGroupCriterionService =
                       (AdGroupCriterionService)user.GetService(
                           AdWordsService.v201802.AdGroupCriterionService)) {
                // Create a webpage criterion.
                Webpage webpage = new Webpage();

                WebpageParameter parameter = new WebpageParameter();
                parameter.criterionName = "Test criterion";
                webpage.parameter       = parameter;

                // Add a condition for label=specified_label_name.
                WebpageCondition condition = new WebpageCondition();
                condition.operand    = WebpageConditionOperand.CUSTOM_LABEL;
                condition.argument   = labelName;
                parameter.conditions = new WebpageCondition[] { condition };

                BiddableAdGroupCriterion criterion = new BiddableAdGroupCriterion();
                criterion.adGroupId = adGroupId;
                criterion.criterion = webpage;

                // Set a custom bid for this criterion.
                BiddingStrategyConfiguration biddingStrategyConfiguration =
                    new BiddingStrategyConfiguration();

                biddingStrategyConfiguration.bids = new Bids[] {
                    new CpcBid()
                    {
                        bid = new Money()
                        {
                            microAmount = 1500000
                        }
                    }
                };

                criterion.biddingStrategyConfiguration = biddingStrategyConfiguration;

                AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
                operation.operand   = criterion;
                operation.@operator = Operator.ADD;

                try {
                    AdGroupCriterionReturnValue retval = adGroupCriterionService.mutate(
                        new AdGroupCriterionOperation[] { operation });
                    BiddableAdGroupCriterion newCriterion = (BiddableAdGroupCriterion)retval.value[0];

                    Console.WriteLine("Web page criterion with ID = {0} and status = {1} was created.",
                                      newCriterion.criterion.id, newCriterion.userStatus);
                    return(newCriterion);
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to create webpage criterion for " +
                                                          "custom page feed label.", e);
                }
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group that contains the keyword.
        /// </param>
        /// <param name="keywordId">Id of the keyword to be removed.</param>
        public void Run(AdWordsUser user, long adGroupId, long keywordId)
        {
            using (AdGroupCriterionService adGroupCriterionService =
                       (AdGroupCriterionService)user.GetService(AdWordsService.v201806
                                                                .AdGroupCriterionService))
            {
                // Create base class criterion to avoid setting keyword-specific fields.
                Criterion criterion = new Criterion
                {
                    id = keywordId
                };

                // Create the ad group criterion.
                BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion
                {
                    adGroupId = adGroupId,
                    criterion = criterion
                };

                // Create the operation.
                AdGroupCriterionOperation operation = new AdGroupCriterionOperation
                {
                    operand   = adGroupCriterion,
                    @operator = Operator.REMOVE
                };

                try
                {
                    // Remove the keyword.
                    AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(
                        new AdGroupCriterionOperation[]
                    {
                        operation
                    });

                    // Display the results.
                    if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                    {
                        AdGroupCriterion removedKeyword = retVal.value[0];
                        Console.WriteLine(
                            "Keyword with ad group id = \"{0}\" and id = \"{1}\" was removed.",
                            removedKeyword.adGroupId, removedKeyword.criterion.id);
                    }
                    else
                    {
                        Console.WriteLine("No keywords were removed.");
                    }
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to remove keyword.", e);
                }
            }
        }
        /// <summary>Add webpage targeting criteria for the DSA ad group.</summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupResourceName">The resource name of the ad group for which targeting
        /// is aded.</param>
        private static void AddWebPageCriteria(GoogleAdsClient client, long customerId,
                                               string adGroupResourceName)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionServiceClient adGroupCriterionService =
                client.GetService(Services.V4.AdGroupCriterionService);

            // Create the criterion.
            AdGroupCriterion adGroupCriterion = new AdGroupCriterion()
            {
                AdGroup      = adGroupResourceName,
                CpcBidMicros = 1_000_000,
                Status       = AdGroupCriterionStatus.Paused,

                // Set the webpage targeting criteria.
                Webpage = new WebpageInfo()
                {
                    CriterionName = "Special Offers",
                    Conditions    =
                    {
                        // Adds the url targeting criteria.
                        new WebpageConditionInfo()
                        {
                            Operand  = WebpageConditionOperand.Url,
                            Argument = "/specialoffers"
                        },
                        // Adds the page title criteria.
                        // The list of webpage targeting conditions are
                        // and-ed together when evaluated for targeting.
                        new WebpageConditionInfo()
                        {
                            Operand  = WebpageConditionOperand.PageTitle,
                            Argument = "Special Offer"
                        }
                    }
                }
            };

            // Create the operation.
            AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
            {
                Create = adGroupCriterion
            };

            // Add the webpage criteria.
            MutateAdGroupCriteriaResponse response =
                adGroupCriterionService.MutateAdGroupCriteria(
                    customerId.ToString(), new[] { operation });

            // Displays the results.
            Console.WriteLine($"Added ad group criterion with resource name " +
                              $"'{response.Results[0].ResourceName}'");
        }
    }
示例#9
0
 /// <summary>Snippet for MutateAdGroupCriteria</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void MutateAdGroupCriteria()
 {
     // Create client
     AdGroupCriterionServiceClient adGroupCriterionServiceClient = AdGroupCriterionServiceClient.Create();
     // Initialize request argument(s)
     string customerId = "";
     IEnumerable <AdGroupCriterionOperation> operations = new AdGroupCriterionOperation[]
     {
         new AdGroupCriterionOperation(),
     };
     // Make the request
     MutateAdGroupCriteriaResponse response = adGroupCriterionServiceClient.MutateAdGroupCriteria(customerId, operations);
 }
        /// <summary>
        /// Creates a SET operation for the specified node.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <returns>An operation pair for the specified operation and node.
        /// </returns>
        private OperationPair CreateSetBidOperation(ProductPartitionNode node)
        {
            // TODO(Anash): This check is dangerous, since we should only depend on parent-child
            // relationships, not ID relationships.
            PreconditionUtilities.CheckArgument(node.ProductPartitionId >= NEW_ROOT_ID,
                                                string.Format(ShoppingMessages.NodeForSetCannotHaveNegativeId, node));
            AdGroupCriterionOperation setOp = new AdGroupCriterionOperation();

            setOp.@operator = Operator.SET;
            setOp.operand   = ProductPartitionNodeAdapter.CreateCriterionForSetBid(node, adGroupId);

            return(new OperationPair(node, setOp));
        }
        /// <summary>
        /// Creates a REMOVE operation for the specified node.
        /// </summary>
        /// <param name="node">The node to be removed.</param>
        /// <returns>An operation pair for the node and the REMOVE operation.
        /// </returns>
        private OperationPair CreateRemoveOperation(ProductPartitionNode node)
        {
            PreconditionUtilities.CheckArgument(node.ProductPartitionId >= NEW_ROOT_ID,
                                                string.Format(ShoppingMessages.NodeForRemoveCannotHaveNegativeId,
                                                              node.ProductPartitionId));

            AdGroupCriterionOperation removeOp = new AdGroupCriterionOperation();

            removeOp.@operator = Operator.REMOVE;
            removeOp.operand   = ProductPartitionNodeAdapter.CreateCriterionForRemove(node, adGroupId);

            return(new OperationPair(node, removeOp));
        }
        // [END add_shopping_product_listing_group_tree]

        /// <summary>
        /// Removes all the ad group criteria that define the existing listing group tree for an
        /// ad group. Returns without an error if all listing group criterion are successfully
        /// removed.
        /// </summary>
        /// <param name="client">The Google Ads API client..</param>
        /// <param name="customerId">The client customer ID.</param>
        /// <param name="adGroupId">The ID of the ad group that the new listing group tree will
        /// be removed from.</param>
        /// <exception cref="GoogleAdsException">Thrown if an API request failed with one or more
        /// service errors.</exception>
        private void RemoveListingGroupTree(GoogleAdsClient client, long customerId,
                                            long adGroupId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V10.GoogleAdsService);

            // Get the AdGroupCriterionService.
            AdGroupCriterionServiceClient adGroupCriterionService =
                client.GetService(Services.V10.AdGroupCriterionService);

            String searchQuery = "SELECT ad_group_criterion.resource_name FROM " +
                                 "ad_group_criterion WHERE ad_group_criterion.type = LISTING_GROUP AND " +
                                 "ad_group_criterion.listing_group.parent_ad_group_criterion IS NULL " +
                                 $"AND ad_group.id = {adGroupId}";

            // Creates a request that will retrieve all listing groups where the parent ad group
            // criterion is NULL (and hence the root node in the tree) for a given ad group ID.
            SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
            {
                CustomerId = customerId.ToString(),
                PageSize   = PAGE_SIZE,
                Query      = searchQuery
            };

            // Issues the search request.
            GoogleAdsRow googleAdsRow = googleAdsService.Search(request).FirstOrDefault();

            if (googleAdsRow == null)
            {
                return;
            }

            AdGroupCriterion adGroupCriterion = googleAdsRow.AdGroupCriterion;

            Console.WriteLine("Found ad group criterion with the resource name: '{0}'.",
                              adGroupCriterion.ResourceName);

            AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
            {
                Remove = adGroupCriterion.ResourceName
            };

            MutateAdGroupCriteriaResponse response =
                adGroupCriterionService.MutateAdGroupCriteria(
                    customerId.ToString(), new AdGroupCriterionOperation[] { operation });

            Console.WriteLine($"Removed {response.Results.Count}.");
        }
        // [END add_campaign_asset_set]

        // [START add_dsa_target]
        /// <summary>
        /// Adds the DSA target.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupId">The ad group to which DSA label targeting is added.</param>
        /// <param name="dsaPageUrlLabel">The DSA page URL label.</param>
        private static void AddDsaTarget(
            GoogleAdsClient client, long customerId, long adGroupId, string dsaPageUrlLabel)
        {
            AdGroupCriterionServiceClient adGroupCriterionService = client.GetService(
                Services.V10.AdGroupCriterionService);

            string adGroupResourceName = ResourceNames.AdGroup(customerId, adGroupId);

            // Creates the webpage condition info that targets an advertiser's webpages
            // based on the custom label specified by the dsaPageUrlLabel (e.g. "discounts").
            WebpageConditionInfo webpageConditionInfo = new WebpageConditionInfo()
            {
                Operand  = WebpageConditionOperand.CustomLabel,
                Argument = dsaPageUrlLabel
            };

            // Creates the webpage info, or criterion for targeting webpages of an
            // advertiser's website.
            WebpageInfo webpageInfo = new WebpageInfo()
            {
                CriterionName = "Test Criterion",
                Conditions    = { webpageConditionInfo }
            };

            // Creates the ad group criterion.
            AdGroupCriterion adGroupCriterion = new AdGroupCriterion()
            {
                AdGroup      = adGroupResourceName,
                Webpage      = webpageInfo,
                CpcBidMicros = 1_500_000
            };

            // Creates the operation.
            AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
            {
                Create = adGroupCriterion
            };

            // Adds the ad group criterion.
            MutateAdGroupCriteriaResponse response =
                adGroupCriterionService.MutateAdGroupCriteria(
                    customerId.ToString(), new[] { operation });

            string resourceName = response.Results[0].ResourceName;

            // Displays the results.
            Console.WriteLine($"Created ad group criterion with resource " +
                              $"name '{resourceName}'.");
        }
示例#14
0
        // [END add_dynamic_page_feed]

        // [START add_dynamic_page_feed_2]
        private void AddDsaTarget(GoogleAdsClient client, long customerId, long adGroupId,
                                  string dsaPageUrlLabel)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionServiceClient adGroupCriterionService = client.GetService(
                Services.V10.AdGroupCriterionService);

            // Create the webpage condition info.
            WebpageConditionInfo webpageConditionInfo = new WebpageConditionInfo()
            {
                Operand  = WebpageConditionOperand.CustomLabel,
                Argument = dsaPageUrlLabel,
            };

            // Creates the webpage info.
            WebpageInfo webpageInfo = new WebpageInfo()
            {
                CriterionName = "Test Criterion",
                Conditions    = { webpageConditionInfo }
            };

            // Creates the ad group criterion.
            AdGroupCriterion adGroupCriterion = new AdGroupCriterion()
            {
                AdGroup      = ResourceNames.AdGroup(customerId, adGroupId),
                Webpage      = webpageInfo,
                CpcBidMicros = 1_500_000
            };

            // Create the operation.
            AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
            {
                Create = adGroupCriterion
            };

            // Add the ad group criterion.
            MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
                adGroupCriterionService.MutateAdGroupCriteria(customerId.ToString(),
                                                              new[] { operation });

            // Display the results.
            foreach (MutateAdGroupCriterionResult result in mutateAdGroupCriteriaResponse.Results)
            {
                Console.WriteLine($"Created ad group criterion with resource name " +
                                  $"'{result.ResourceName}'.");
            }
        }
示例#15
0
        /// <summary>
        /// Attach a user list to an ad group. The user list provides positive targeting and feed
        /// information to drive the dynamic content of the ad.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="adGroup">The ad group which will have the user list attached.</param>
        /// <param name="userListId">The user list to use for targeting and dynamic content.</param>
        /// <remarks>User lists must be attached at the ad group level for positive targeting in
        /// Shopping dynamic remarketing campaigns.</remarks>
        private static void AttachUserList(AdWordsUser user, AdGroup adGroup, long userListId)
        {
            using (AdGroupCriterionService adGroupCriterionService =
                       (AdGroupCriterionService)user.GetService(
                           AdWordsService.v201806.AdGroupCriterionService)) {
                CriterionUserList userList = new CriterionUserList();
                userList.userListId = userListId;
                BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion();
                adGroupCriterion.criterion = userList;
                adGroupCriterion.adGroupId = adGroup.id;

                AdGroupCriterionOperation op = new AdGroupCriterionOperation();
                op.operand   = adGroupCriterion;
                op.@operator = Operator.ADD;

                adGroupCriterionService.mutate(new AdGroupCriterionOperation[] { op });
            }
        }
        /// <summary>Snippet for MutateAdGroupCriteriaAsync</summary>
        public async Task MutateAdGroupCriteriaAsync()
        {
            // Snippet: MutateAdGroupCriteriaAsync(string, IEnumerable<AdGroupCriterionOperation>, CallSettings)
            // Additional: MutateAdGroupCriteriaAsync(string, IEnumerable<AdGroupCriterionOperation>, CancellationToken)
            // Create client
            AdGroupCriterionServiceClient adGroupCriterionServiceClient = await AdGroupCriterionServiceClient.CreateAsync();

            // Initialize request argument(s)
            string customerId = "";
            IEnumerable <AdGroupCriterionOperation> operations = new AdGroupCriterionOperation[]
            {
                new AdGroupCriterionOperation(),
            };
            // Make the request
            MutateAdGroupCriteriaResponse response = await adGroupCriterionServiceClient.MutateAdGroupCriteriaAsync(customerId, operations);

            // End snippet
        }
        /// <summary>
        /// Sends exemption requests for creating a keyword.
        /// </summary>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="service">The ad group criterion service.</param>
        /// <param name="operation">The ad group criterion operation to request exemption for.
        /// </param>
        /// <param name="exemptPolicyViolationKeys">The exemptable policy violation keys.</param>
        private static void RequestExemption(
            long customerId, AdGroupCriterionServiceClient service,
            AdGroupCriterionOperation operation, PolicyViolationKey[] exemptPolicyViolationKeys)
        {
            Console.WriteLine("Try adding a keyword again by requesting exemption for its policy "
                              + "violations.");
            PolicyValidationParameter validationParameter = new PolicyValidationParameter();

            validationParameter.ExemptPolicyViolationKeys.AddRange(exemptPolicyViolationKeys);
            operation.ExemptPolicyViolationKeys.AddRange(exemptPolicyViolationKeys);

            MutateAdGroupCriteriaResponse response = service.MutateAdGroupCriteria(
                customerId.ToString(), new[] { operation });

            Console.WriteLine($"Successfully added a keyword with resource name " +
                              $"'{response.Results[0].ResourceName}' by requesting for policy violation " +
                              $"exemption.");
        }
示例#18
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer Id.</param>
        /// <param name="adGroupId">The Google Ads ad group Id.</param>
        /// <param name="keywordId">The Google Ads keyword Id.</param>
        public void Run(GoogleAdsClient client, long customerId, long adGroupId, long keywordId)
        {
            // Get the CampaignCriterionService.
            AdGroupCriterionServiceClient adGroupCriterionService =
                client.GetService(Services.V4.AdGroupCriterionService);

            // Create the keyword for update.
            AdGroupCriterion keyword = new AdGroupCriterion()
            {
                ResourceName = ResourceNames.AdGroupCriterion(customerId, adGroupId, keywordId),
                CriterionId  = keywordId,
                Status       = AdGroupCriterionStatus.Enabled,
                FinalUrls    = { "https://www.example.com" }
            };

            AdGroupCriterionOperation keywordOperation = new AdGroupCriterionOperation()
            {
                Update     = keyword,
                UpdateMask = FieldMasks.AllSetFieldsOf(keyword)
            };

            try
            {
                // Update the keyword.
                MutateAdGroupCriteriaResponse response =
                    adGroupCriterionService.MutateAdGroupCriteria(customerId.ToString(),
                                                                  new AdGroupCriterionOperation[] { keywordOperation });

                // Display the results.
                foreach (MutateAdGroupCriterionResult criterionResult in response.Results)
                {
                    Console.WriteLine($"Keyword with resource name = " +
                                      $"'{criterionResult.ResourceName}' was updated.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group that contains the placement.
        /// </param>
        /// <param name="placementId">Id of the placement to be removed.</param>
        public void Run(AdWordsUser user, long adGroupId, long placementId)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService(
                AdWordsService.v201506.AdGroupCriterionService);

            // Create base class criterion to avoid setting placement-specific fields.
            Criterion criterion = new Criterion();

            criterion.id = placementId;

            // Create the ad group criterion.
            BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion();

            adGroupCriterion.adGroupId = adGroupId;
            adGroupCriterion.criterion = criterion;

            // Create the operation.
            AdGroupCriterionOperation operation = new AdGroupCriterionOperation();

            operation.operand   = adGroupCriterion;
            operation.@operator = Operator.REMOVE;

            try {
                // Remove the placement.
                AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(
                    new AdGroupCriterionOperation[] { operation });

                // Display the results.
                if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                {
                    AdGroupCriterion removedPlacement = retVal.value[0];
                    Console.WriteLine("Placement with ad group id = \"{0}\" and id = \"{1}\" was removed.",
                                      removedPlacement.adGroupId, removedPlacement.criterion.id);
                }
                else
                {
                    Console.WriteLine("No placement was removed.");
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to remove placement.", ex);
            }
        }
        /// <summary>
        /// Creates the operations for uploading via batch job.
        /// </summary>
        /// <param name="adGroupId">The ad group ID.</param>
        /// <returns>The list of operations.</returns>
        private static List <AdGroupCriterionOperation> CreateOperations(long adGroupId)
        {
            List <AdGroupCriterionOperation> operations = new List <AdGroupCriterionOperation>();

            // Create AdGroupCriterionOperations to add keywords, and upload every 10 operations
            // incrementally.
            for (int i = 0; i < NUMBER_OF_KEYWORDS_TO_ADD; i++)
            {
                // Create Keyword.
                string text = string.Format("mars{0}", i);

                // Make 10% of keywords invalid to demonstrate error handling.
                if (i % 10 == 0)
                {
                    text = text + "!!!";
                }

                // Create BiddableAdGroupCriterion.
                BiddableAdGroupCriterion bagc = new BiddableAdGroupCriterion()
                {
                    adGroupId = adGroupId,
                    criterion = new Keyword()
                    {
                        text      = text,
                        matchType = KeywordMatchType.BROAD
                    }
                };

                // Create AdGroupCriterionOperation.
                AdGroupCriterionOperation agco = new AdGroupCriterionOperation()
                {
                    operand   = bagc,
                    @operator = Operator.ADD
                };

                // Add to the list of operations.
                operations.Add(agco);
            }

            return(operations);
        }
示例#21
0
        /// <summary>
        /// Attach a user list to an ad group. The user list provides positive targeting and feed
        /// information to drive the dynamic content of the ad.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="adGroup">The ad group which will have the user list attached.</param>
        /// <param name="userListId">The user list to use for targeting and dynamic content.</param>
        /// <remarks>User lists must be attached at the ad group level for positive targeting in
        /// Shopping dynamic remarketing campaigns.</remarks>
        private static void AttachUserList(AdWordsUser user, AdGroup adGroup, long userListId)
        {
            using (AdGroupCriterionService adGroupCriterionService =
                       (AdGroupCriterionService)user.GetService(
                           AdWordsService.v201806.AdGroupCriterionService)) {
                CriterionUserList userList = new CriterionUserList {
                    userListId = userListId
                };
                BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion {
                    criterion = userList,
                    adGroupId = adGroup.id
                };

                AdGroupCriterionOperation op = new AdGroupCriterionOperation {
                    operand   = adGroupCriterion,
                    @operator = Operator.ADD
                };

                adGroupCriterionService.mutate(new AdGroupCriterionOperation[] { op });
            }
        }
        /// <summary>
        /// Builds the operations for creating keywords within an ad group.
        /// </summary>
        /// <param name="adGroupId">ID of the ad group for which keywords are
        /// created.</param>
        /// <returns>A list of operations for creating keywords.</returns>
        private static List <AdGroupCriterionOperation> BuildAdGroupCriterionOperations(
            long adGroupId)
        {
            List <AdGroupCriterionOperation> adGroupCriteriaOperations =
                new List <AdGroupCriterionOperation>();

            // Create AdGroupCriterionOperations to add keywords.

            for (int i = 0; i < NUMBER_OF_KEYWORDS_TO_ADD; i++)
            {
                // Create Keyword.
                string text = string.Format("mars{0}", i);

                // Make 50% of keywords invalid to demonstrate error handling.
                if ((i % 2) == 0)
                {
                    text = text + "!!!";
                }

                // Create AdGroupCriterionOperation.
                AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
                {
                    operand = new BiddableAdGroupCriterion()
                    {
                        adGroupId = adGroupId,
                        criterion = new Keyword()
                        {
                            text      = text,
                            matchType = KeywordMatchType.BROAD
                        }
                    },
                    @operator = Operator.ADD
                };

                // Add to list.
                adGroupCriteriaOperations.Add(operation);
            }

            return(adGroupCriteriaOperations);
        }
示例#23
0
        /// <summary>
        /// Creates a keyword for running further tests.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">The adgroup id for which the keyword is
        /// created.</param>
        /// <returns>The keyword id.</returns>
        public long CreateKeyword(AdWordsUser user, long adGroupId)
        {
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(AdWordsService.v201406.AdGroupCriterionService);

            AdGroupCriterionOperation operation = new AdGroupCriterionOperation();

            operation.@operator         = Operator.ADD;
            operation.operand           = new BiddableAdGroupCriterion();
            operation.operand.adGroupId = adGroupId;

            Keyword keyword = new Keyword();

            keyword.matchType = KeywordMatchType.BROAD;
            keyword.text      = "mars cruise";

            operation.operand.criterion = keyword;
            AdGroupCriterionReturnValue retVal =
                adGroupCriterionService.mutate(new AdGroupCriterionOperation[] { operation });

            return(retVal.value[0].criterion.id);
        }
        /// <summary>
        /// Builds new ad group criterion operations for creating keywords. 50% of keywords are
        /// created some invalid characters to demonstrate how BatchJobService returns information
        /// about such errors.
        /// </summary>
        /// <param name="adGroupOperations">The ad group operations to be used to create ad group
        /// criteria.</param>
        /// <returns>The ad group criterion operations.</returns>
        private static List <AdGroupCriterionOperation> BuildAdGroupCriterionOperations(
            List <AdGroupOperation> adGroupOperations)
        {
            List <AdGroupCriterionOperation> operations = new List <AdGroupCriterionOperation>();

            foreach (AdGroupOperation adGroupOperation in adGroupOperations)
            {
                for (int i = 0; i < NUMBER_OF_KEYWORDS_TO_ADD; i++)
                {
                    // Creates a keyword text by making 50% of keywords invalid to demonstrate
                    // error handling.
                    string keywordText = "mars" + i;
                    if (i % 2 == 0)
                    {
                        keywordText += "!!!";
                    }
                    // Creates an ad group criterion using the created keyword text.
                    AdGroupCriterion adGroupCriterion = new AdGroupCriterion()
                    {
                        Keyword = new KeywordInfo()
                        {
                            Text      = keywordText,
                            MatchType = KeywordMatchType.Broad,
                        },
                        AdGroup = adGroupOperation.Create.ResourceName,
                        Status  = AdGroupCriterionStatus.Paused
                    };

                    // Creates an ad group criterion operation and adds it to the operations list.
                    AdGroupCriterionOperation op = new AdGroupCriterionOperation()
                    {
                        Create = adGroupCriterion
                    };
                    operations.Add(op);
                }
            }

            return(operations);
        }
        public void TestCreateUltimatelyEmptyTree()
        {
            ProductPartitionTree tree =
                ProductPartitionTree.CreateAdGroupTree(new List <AdGroupCriterion>());

            ProductPartitionNode rootNode = tree.Root.AsSubdivision();
            ProductPartitionNode brand1   = rootNode.AddChild(ProductDimensions.CreateBrand("google"))
                                            .AsSubdivision();
            ProductPartitionNode offerNode = brand1.AddChild(ProductDimensions.CreateOfferId("A"));

            offerNode.AsBiddableUnit().CpcBid = 1000000L;

            brand1.AddChild(ProductDimensions.CreateOfferId()).AsExcludedUnit();
            ProductPartitionNode brand2 =
                rootNode.AddChild(ProductDimensions.CreateBrand()).AsExcludedUnit();

            // Now remove the two child nodes under the root and set the root back
            // to a UNIT. This should result in operations that simply create the
            // root node.
            rootNode.RemoveChild(brand1.Dimension);
            rootNode.RemoveChild(brand2.Dimension);
            rootNode = rootNode.AsBiddableUnit();

            AdGroupCriterionOperation[] mutateOperations = tree.GetMutateOperations();

            Assert.AreEqual(mutateOperations.Count(), 1, "Number of operations is incorrect.");
            AdGroupCriterionOperation operation = mutateOperations[0];

            Assert.AreEqual(Operator.ADD, operation.@operator,
                            "Should have a single operation to ADD the root node.");
            BiddableAdGroupCriterion adGroupCriterion =
                (BiddableAdGroupCriterion)operation.operand;

            Assert.Null(((ProductPartition)adGroupCriterion.criterion).caseValue,
                        "Product dimension of operation's operand should be null.");
            Assert.True(adGroupCriterion.criterion.id < 0L,
                        "Partition ID of the operand should be negative.");
        }
        public void TestCreateEmptyTree()
        {
            ProductPartitionTree tree = ProductPartitionTree.CreateAdGroupTree(
                new List <AdGroupCriterion>());

            Assert.NotNull(tree.Root, "Even an empty tree should automatically have a root node.");
            Assert.True(tree.Root.ProductPartitionId < 0L,
                        "The root node for an empty tree should have a negative (temporary) ID.");
            Assert.True(tree.Root.IsUnit, "The root node for an empty tree should be a UNIT.");

            AdGroupCriterionOperation[] mutateOperations = tree.GetMutateOperations();

            Assert.That(mutateOperations.Count() == 1, "Number of operations is incorrect.");
            AdGroupCriterionOperation operation = mutateOperations[0];

            Assert.AreEqual(Operator.ADD, operation.@operator,
                            "Should have a single operation to ADD the root node.");
            BiddableAdGroupCriterion adGroupCriterion = (BiddableAdGroupCriterion)operation.operand;

            Assert.Null(((ProductPartition)adGroupCriterion.criterion).caseValue,
                        "Product dimension of operation's operand should be null.");
            Assert.True(adGroupCriterion.criterion.id < 0L);
        }
        // [END add_shopping_product_ad]

        /// <summary>
        /// Creates a new default shopping listing group for the specified ad group. A listing
        /// group is the Google Ads API representation of a "product group" described in the
        /// Google Ads user interface. The listing group will be added to the ad group using an
        /// "ad group criterion".
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The client customer ID.</param>
        /// <param name="adGroupResourceName">The resource name of the ad group that the new
        /// listing group will belong to.</param>
        /// <returns>Resource name of the newly created ad group criterion containing the
        /// listing group.</returns>
        /// <exception cref="GoogleAdsException">Thrown if an API request failed with one or more
        /// service errors.</exception>
        private string AddDefaultShoppingListingGroup(GoogleAdsClient client, long customerId,
                                                      string adGroupResourceName)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionServiceClient adGroupCriterionService = client.GetService(
                Services.V10.AdGroupCriterionService);

            // Creates a new ad group criterion. This will contain the "default" listing group (All
            // products).
            AdGroupCriterion adGroupCriterion = new AdGroupCriterion()
            {
                AdGroup = adGroupResourceName,
                Status  = AdGroupCriterionStatus.Enabled,

                // Creates a new listing group. This will be the top-level "root" node.
                // Set the type of the listing group to be a biddable unit.
                ListingGroup = new ListingGroupInfo()
                {
                    Type = ListingGroupType.Unit
                },
                // Set the bid for products in this listing group unit.
                CpcBidMicros = 500_000L
            };

            AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
            {
                Create = adGroupCriterion
            };

            MutateAdGroupCriterionResult mutateAdGroupCriteriaResult =
                adGroupCriterionService.MutateAdGroupCriteria(customerId.ToString(),
                                                              new AdGroupCriterionOperation[] { operation }).Results[0];

            Console.WriteLine("Added an ad group criterion containing a listing group with " +
                              "resource name: '{0}'.", mutateAdGroupCriteriaResult.ResourceName);
            return(mutateAdGroupCriteriaResult.ResourceName);
        }
示例#28
0
        // [END setup_remarketing]

        /// <summary>
        /// Creates an ad group criterion that targets a user list with an ad group.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupId">The ad group on which the user list will be targeted.</param>
        /// <param name="userListResourceName">The resource name of the user list to be
        /// targeted.</param>
        /// <returns>The resource name of the newly created ad group criterion.</returns>
        // [START setup_remarketing_1]
        private string TargetAdsInAdGroupToUserList(
            GoogleAdsClient client, long customerId, long adGroupId, string userListResourceName)
        {
            // Get the AdGroupCriterionService client.
            AdGroupCriterionServiceClient adGroupCriterionServiceClient = client.GetService
                                                                              (Services.V10.AdGroupCriterionService);

            // Create the ad group criterion targeting members of the user list.
            AdGroupCriterion adGroupCriterion = new AdGroupCriterion
            {
                AdGroup  = ResourceNames.AdGroup(customerId, adGroupId),
                UserList = new UserListInfo
                {
                    UserList = userListResourceName
                }
            };

            // Create the operation.
            AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation
            {
                Create = adGroupCriterion
            };

            // Add the ad group criterion, then print and return the new criterion's resource name.
            MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
                adGroupCriterionServiceClient.MutateAdGroupCriteria(customerId.ToString(),
                                                                    new[] { adGroupCriterionOperation });

            string adGroupCriterionResourceName =
                mutateAdGroupCriteriaResponse.Results.First().ResourceName;

            Console.WriteLine("Successfully created ad group criterion with resource name " +
                              $"'{adGroupCriterionResourceName}' targeting user list with resource name " +
                              $"'{userListResourceName}' with ad group with ID {adGroupId}.");
            return(adGroupCriterionResourceName);
        }
示例#29
0
        /// <summary>
        /// Creates the placement.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">The adgroup id for which the placement is
        /// created.</param>
        /// <returns>The placement id.</returns>
        public long CreatePlacement(AdWordsUser user, long adGroupId)
        {
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(AdWordsService.v201406.AdGroupCriterionService);

            Placement placement = new Placement();

            placement.url = "http://mars.google.com";

            AdGroupCriterion placementCriterion = new BiddableAdGroupCriterion();

            placementCriterion.adGroupId = adGroupId;
            placementCriterion.criterion = placement;

            AdGroupCriterionOperation placementOperation = new AdGroupCriterionOperation();

            placementOperation.@operator = Operator.ADD;
            placementOperation.operand   = placementCriterion;

            AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(
                new AdGroupCriterionOperation[] { placementOperation });

            return(retVal.value[0].criterion.id);
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group that contains the keyword.
    /// </param>
    /// <param name="keywordId">Id of the keyword to be removed.</param>
    public void Run(AdWordsUser user, long adGroupId, long keywordId) {
      // Get the AdGroupCriterionService.
      AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService(
          AdWordsService.v201509.AdGroupCriterionService);

      // Create base class criterion to avoid setting keyword-specific fields.
      Criterion criterion = new Criterion();
      criterion.id = keywordId;

      // Create the ad group criterion.
      BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion();
      adGroupCriterion.adGroupId = adGroupId;
      adGroupCriterion.criterion = criterion;

      // Create the operation.
      AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
      operation.operand = adGroupCriterion;
      operation.@operator = Operator.REMOVE;

      try {
        // Remove the keyword.
        AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(
            new AdGroupCriterionOperation[] {operation});

        // Display the results.
        if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
          AdGroupCriterion removedKeyword = retVal.value[0];
          Console.WriteLine("Keyword with ad group id = \"{0}\" and id = \"{1}\" was removed.",
              removedKeyword.adGroupId, removedKeyword.criterion.id);
        } else {
          Console.WriteLine("No keywords were removed.");
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to remove keyword.", e);
      }
    }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group that contains the keyword.
    /// </param>
    /// <param name="keywordId">Id of the keyword to be updated.</param>
    public void Run(AdWordsUser user, long adGroupId, long keywordId) {
      // Get the AdGroupCriterionService.
      AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(AdWordsService.v201509.AdGroupCriterionService);

      // Since we are not updating any keyword-specific fields, it is enough to
      // create a criterion object.
      Criterion criterion = new Criterion();
      criterion.id = keywordId;

      // Create ad group criterion.
      BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion();
      biddableAdGroupCriterion.adGroupId = adGroupId;
      biddableAdGroupCriterion.criterion = criterion;

      // Create the bids.
      BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
      CpcBid cpcBid = new CpcBid();
      cpcBid.bid = new Money();
      cpcBid.bid.microAmount = 1000000;
      biddingConfig.bids = new Bids[] {cpcBid};

      biddableAdGroupCriterion.biddingStrategyConfiguration = biddingConfig;

      // Create the operation.
      AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
      operation.@operator = Operator.SET;
      operation.operand = biddableAdGroupCriterion;

      try {
        // Update the keyword.
        AdGroupCriterionReturnValue retVal =
            adGroupCriterionService.mutate(new AdGroupCriterionOperation[] {operation});

        // Display the results.
        if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
          AdGroupCriterion adGroupCriterion = retVal.value[0];
          long bidAmount = 0;
          foreach (Bids bids in (adGroupCriterion as BiddableAdGroupCriterion).
              biddingStrategyConfiguration.bids) {
            if (bids is CpcBid) {
              bidAmount = (bids as CpcBid).bid.microAmount;
              break;
            }
          }

          Console.WriteLine("Keyword with ad group id = '{0}', id = '{1}' was updated with " +
              "bid amount = '{2}' micros.", adGroupCriterion.adGroupId,
              adGroupCriterion.criterion.id, bidAmount);
        } else {
          Console.WriteLine("No keyword was updated.");
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to update keyword.", e);
      }
    }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group to which keywords are added.
    /// </param>
    public void Run(AdWordsUser user, long adGroupId) {
      // Get the AdGroupCriterionService.
      AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(AdWordsService.v201509.AdGroupCriterionService);

      // Set partial failure mode for the service.
      adGroupCriterionService.RequestHeader.partialFailure = true;

      List<AdGroupCriterionOperation> operations = new List<AdGroupCriterionOperation>();

      // Create the placements.
      string[] urls = new String[] {"http://mars.google.com", "http:/mars.google.com",
          "mars.google.com"};

      foreach (String url in urls) {
        Placement placement = new Placement();
        placement.url = url;

        // Create biddable ad group criterion.
        BiddableAdGroupCriterion placementBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
        placementBiddableAdGroupCriterion.adGroupId = adGroupId;
        placementBiddableAdGroupCriterion.criterion = placement;

        // Create the operation.
        AdGroupCriterionOperation placementAdGroupCriterionOperation =
            new AdGroupCriterionOperation();
        placementAdGroupCriterionOperation.operand = placementBiddableAdGroupCriterion;
        placementAdGroupCriterionOperation.@operator = Operator.ADD;
        operations.Add(placementAdGroupCriterionOperation);
      }

      try {
        // Create the placements.
        AdGroupCriterionReturnValue result = adGroupCriterionService.mutate(operations.ToArray());

        // Display the results.
        if (result != null && result.value != null) {
          foreach (AdGroupCriterion adGroupCriterionResult in result.value) {
            if (adGroupCriterionResult.criterion != null) {
              Console.WriteLine("Placement with ad group id '{0}', and criterion " +
                  "id '{1}', and url '{2}' was added.\n", adGroupCriterionResult.adGroupId,
                  adGroupCriterionResult.criterion.id,
                  ((Placement) adGroupCriterionResult.criterion).url);
            }
          }
        } else {
          Console.WriteLine("No placements were added.");
        }

        // Display the partial failure errors.
        if (result != null && result.partialFailureErrors != null) {
          foreach (ApiError apiError in result.partialFailureErrors) {
            int operationIndex = ErrorUtilities.GetOperationIndex(apiError.fieldPath);
            if (operationIndex != -1) {
              AdGroupCriterion adGroupCriterion = operations[operationIndex].operand;
              Console.WriteLine("Placement with ad group id '{0}' and url '{1}' "
                  + "triggered a failure for the following reason: '{2}'.\n",
                  adGroupCriterion.adGroupId, ((Placement) adGroupCriterion.criterion).url,
                  apiError.errorString);
            } else {
              Console.WriteLine("A failure for the following reason: '{0}' has occurred.\n",
                  apiError.errorString);
            }
          }
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to add placements in partial failure mode.",
            e);
      }
    }
        /// <summary>
        /// Creates a SET operation for the specified node.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <returns>An operation pair for the specified operation and node.
        /// </returns>
        private OperationPair CreateSetBidOperation(ProductPartitionNode node)
        {
            // TODO(Anash): This check is dangerous, since we should only depend on parent-child
              // relationships, not ID relationships.
              PreconditionUtilities.CheckArgument(node.ProductPartitionId >= NEW_ROOT_ID,
              string.Format(ShoppingMessages.NodeForSetCannotHaveNegativeId, node));
              AdGroupCriterionOperation setOp = new AdGroupCriterionOperation();
              setOp.@operator = Operator.SET;
              setOp.operand = ProductPartitionNodeAdapter.CreateCriterionForSetBid(node, adGroupId);

              return new OperationPair(node, setOp);
        }
            /// <summary>
            /// Main method for the thread.
            /// </summary>
            /// <param name="obj">The thread parameter.</param>
            public void Run(Object obj)
            {
                // Create the operations.
                List<AdGroupCriterionOperation> operations = new List<AdGroupCriterionOperation>();

                for (int j = 0; j < NUM_KEYWORDS; j++) {
                  // Create the keyword.
                  Keyword keyword = new Keyword();
                  keyword.text = "mars cruise thread " + threadIndex.ToString() + " seed " + j.ToString();
                  keyword.matchType = KeywordMatchType.BROAD;

                  // Create the biddable ad group criterion.
                  AdGroupCriterion keywordCriterion = new BiddableAdGroupCriterion();
                  keywordCriterion.adGroupId = adGroupId;
                  keywordCriterion.criterion = keyword;

                  // Create the operations.
                  AdGroupCriterionOperation keywordOperation = new AdGroupCriterionOperation();
                  keywordOperation.@operator = Operator.ADD;
                  keywordOperation.operand = keywordCriterion;

                  operations.Add(keywordOperation);
                }

                // Get the AdGroupCriterionService. This should be done within the
                // thread, since a service can only handle one outgoing HTTP request
                // at a time.
                AdGroupCriterionService service = (AdGroupCriterionService) user.GetService(
                AdWordsService.v201601.AdGroupCriterionService);
                service.RequestHeader.validateOnly = true;
                int retryCount = 0;
                const int NUM_RETRIES = 3;
                try {
                  while (retryCount < NUM_RETRIES) {
                try {
                  // Validate the keywords.
                  AdGroupCriterionReturnValue retval = service.mutate(operations.ToArray());
                  break;
                } catch (AdWordsApiException e) {
                  // Handle API errors.
                  ApiException innerException = e.ApiException as ApiException;
                  if (innerException == null) {
                throw new Exception("Failed to retrieve ApiError. See inner exception for more " +
                    "details.", e);
                  }
                  foreach (ApiError apiError in innerException.errors) {
                if (!(apiError is RateExceededError)) {
                  // Rethrow any errors other than RateExceededError.
                  throw;
                }
                // Handle rate exceeded errors.
                RateExceededError rateExceededError = (RateExceededError) apiError;
                Console.WriteLine("Got Rate exceeded error - rate name = '{0}', scope = '{1}', " +
                    "retry After {2} seconds.", rateExceededError.rateScope,
                    rateExceededError.rateName, rateExceededError.retryAfterSeconds);
                Thread.Sleep(rateExceededError.retryAfterSeconds * 1000);
                retryCount = retryCount + 1;
                  }
                } finally {
                  if (retryCount == NUM_RETRIES) {
                throw new Exception(String.Format("Could not recover after making {0} attempts.",
                    retryCount));
                  }
                }
                  }
                } catch (Exception e) {
                  throw new System.ApplicationException("Failed to validate keywords.", e);
                }
            }
        /// <summary>
        /// Removes the root of the tree.
        /// </summary>
        private void SetRootToEmpty()
        {
            ProductPartitionNode root = tree.Root;
              if (root != null && root.ProductPartitionId >= 0L) {
            AdGroupCriterion rootCriterion = new AdGroupCriterion() {
              adGroupId = ADGROUP_ID,
              criterion = new Criterion() {
            id = root.ProductPartitionId
              }
            };

            AdGroupCriterionOperation removeOp = new AdGroupCriterionOperation() {
              @operator = Operator.REMOVE,
              operand = rootCriterion
            };

            AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)
            user.GetService(AdWordsService.v201601.AdGroupCriterionService);
            adGroupCriterionService.mutate(new AdGroupCriterionOperation[] { removeOp });
              }

              Assert.DoesNotThrow(delegate() {
            tree = ProductPartitionTree.DownloadAdGroupTree(user, ADGROUP_ID);
              });
        }
示例#36
0
        /// <summary>
        /// Creates the placement.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">The adgroup id for which the placement is
        /// created.</param>
        /// <returns>The placement id.</returns>
        public long CreatePlacement(AdWordsUser user, long adGroupId)
        {
            AdGroupCriterionService adGroupCriterionService =
              (AdGroupCriterionService) user.GetService(AdWordsService.v201601.AdGroupCriterionService);

              Placement placement = new Placement();
              placement.url = "http://mars.google.com";

              AdGroupCriterion placementCriterion = new BiddableAdGroupCriterion();
              placementCriterion.adGroupId = adGroupId;
              placementCriterion.criterion = placement;

              AdGroupCriterionOperation placementOperation = new AdGroupCriterionOperation();
              placementOperation.@operator = Operator.ADD;
              placementOperation.operand = placementCriterion;

              AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(
              new AdGroupCriterionOperation[] { placementOperation });

              return retVal.value[0].criterion.id;
        }
示例#37
0
        /// <summary>
        /// Creates a keyword for running further tests.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">The adgroup id for which the keyword is
        /// created.</param>
        /// <returns>The keyword id.</returns>
        public long CreateKeyword(AdWordsUser user, long adGroupId)
        {
            AdGroupCriterionService adGroupCriterionService =
             (AdGroupCriterionService) user.GetService(AdWordsService.v201601.AdGroupCriterionService);

              AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
              operation.@operator = Operator.ADD;
              operation.operand = new BiddableAdGroupCriterion();
              operation.operand.adGroupId = adGroupId;

              Keyword keyword = new Keyword();
              keyword.matchType = KeywordMatchType.BROAD;
              keyword.text = "mars cruise";

              operation.operand.criterion = keyword;
              AdGroupCriterionReturnValue retVal =
              adGroupCriterionService.mutate(new AdGroupCriterionOperation[] { operation });
              return retVal.value[0].criterion.id;
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group to which keywords are added.
    /// </param>
    public void Run(AdWordsUser user, long adGroupId) {
      // Get the AdGroupCriterionService.
      AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(
              AdWordsService.v201509.AdGroupCriterionService);

      List<AdGroupCriterionOperation> operations = new List<AdGroupCriterionOperation>();

      foreach (string keywordText in KEYWORDS) {
        // Create the keyword.
        Keyword keyword = new Keyword();
        keyword.text = keywordText;
        keyword.matchType = KeywordMatchType.BROAD;

        // Create the biddable ad group criterion.
        BiddableAdGroupCriterion keywordCriterion = new BiddableAdGroupCriterion();
        keywordCriterion.adGroupId = adGroupId;
        keywordCriterion.criterion = keyword;

        // Optional: Set the user status.
        keywordCriterion.userStatus = UserStatus.PAUSED;

        // Optional: Set the keyword destination url.
        keywordCriterion.finalUrls = new UrlList() {
          urls = new string[] { "http://example.com/mars/cruise/?kw=" +
              HttpUtility.UrlEncode(keywordText) }
        };

        // Create the operations.
        AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
        operation.@operator = Operator.ADD;
        operation.operand = keywordCriterion;

        operations.Add(operation);
      }
      try {
        // Create the keywords.
        AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(operations.ToArray());

        // Display the results.
        if (retVal != null && retVal.value != null) {
          foreach (AdGroupCriterion adGroupCriterion in retVal.value) {
            // If you are adding multiple type of criteria, then you may need to
            // check for
            //
            // if (adGroupCriterion is Keyword) { ... }
            //
            // to identify the criterion type.
            Console.WriteLine("Keyword with ad group id = '{0}', keyword id = '{1}', text = " +
                "'{2}' and match type = '{3}' was created.", adGroupCriterion.adGroupId,
                adGroupCriterion.criterion.id, (adGroupCriterion.criterion as Keyword).text,
                (adGroupCriterion.criterion as Keyword).matchType);
          }
        } else {
          Console.WriteLine("No keywords were added.");
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to create keywords.", e);
      }
    }
        /// <summary>
        /// Builds the operations for creating keywords within an ad group.
        /// </summary>
        /// <param name="adGroupId">ID of the ad group for which keywords are
        /// created.</param>
        /// <returns>A list of operations for creating keywords.</returns>
        private static List<AdGroupCriterionOperation> BuildAdGroupCriterionOperations(
        long adGroupId)
        {
            List<AdGroupCriterionOperation> adGroupCriteriaOperations =
              new List<AdGroupCriterionOperation>();

              // Create AdGroupCriterionOperations to add keywords.

              for (int i = 0; i < NUMBER_OF_KEYWORDS_TO_ADD; i++) {
            // Create Keyword.
            String text = String.Format("mars{0}", i);

            // Make 50% of keywords invalid to demonstrate error handling.
            if ((i % 2) == 0) {
              text = text + "!!!";
            }

            // Create AdGroupCriterionOperation.
            AdGroupCriterionOperation operation = new AdGroupCriterionOperation() {
              operand = new BiddableAdGroupCriterion() {
            adGroupId = adGroupId,
            criterion = new Keyword() {
              text = text,
              matchType = KeywordMatchType.BROAD
            }
              },
              @operator = Operator.ADD
            };

            // Add to list.
            adGroupCriteriaOperations.Add(operation);
              }
              return adGroupCriteriaOperations;
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which experiments are
        /// added.</param>
        /// <param name="adGroupId">Id of the ad group to which experiments are
        /// added.</param>
        /// <param name="criterionId">Id of the criterion for which experiments
        /// are added.</param>
        public void Run(AdWordsUser user, long campaignId, long adGroupId, long criterionId)
        {
            // Get the ExperimentService.
              ExperimentService experimentService =
              (ExperimentService) user.GetService(AdWordsService.v201601.ExperimentService);

              // Get the AdGroupService.
              AdGroupService adGroupService =
              (AdGroupService) user.GetService(AdWordsService.v201601.AdGroupService);

              // Get the AdGroupCriterionService.
              AdGroupCriterionService adGroupCriterionService =
              (AdGroupCriterionService) user.GetService(AdWordsService.v201601.AdGroupCriterionService);

              // Create the experiment.
              Experiment experiment = new Experiment();
              experiment.campaignId = campaignId;
              experiment.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString();
              experiment.queryPercentage = 10;
              experiment.startDateTime = DateTime.Now.AddDays(1).ToString("yyyyMMdd HHmmss");

              // Optional: Set the end date.
              experiment.endDateTime = DateTime.Now.AddDays(30).ToString("yyyyMMdd HHmmss");

              // Optional: Set the status.
              experiment.status = ExperimentStatus.ENABLED;

              // Create the operation.
              ExperimentOperation experimentOperation = new ExperimentOperation();
              experimentOperation.@operator = Operator.ADD;
              experimentOperation.operand = experiment;

              try {
            // Add the experiment.
            ExperimentReturnValue experimentRetVal = experimentService.mutate(
            new ExperimentOperation[] {experimentOperation});

            // Display the results.
            if (experimentRetVal != null && experimentRetVal.value != null && experimentRetVal.value.
            Length > 0) {
              long experimentId = 0;

              Experiment newExperiment = experimentRetVal.value[0];

              Console.WriteLine("Experiment with name = \"{0}\" and id = \"{1}\" was added.\n",
              newExperiment.name, newExperiment.id);
              experimentId = newExperiment.id;

              // Set ad group for the experiment.
              AdGroup adGroup = new AdGroup();
              adGroup.id = adGroupId;

              // Create experiment bid multiplier rule that will modify ad group bid
              // for the experiment.
              ManualCPCAdGroupExperimentBidMultipliers adGroupBidMultiplier =
              new ManualCPCAdGroupExperimentBidMultipliers();
              adGroupBidMultiplier.maxCpcMultiplier = new BidMultiplier();
              adGroupBidMultiplier.maxCpcMultiplier.multiplier = 1.5;

              // Set experiment data to the ad group.
              AdGroupExperimentData adGroupExperimentData = new AdGroupExperimentData();
              adGroupExperimentData.experimentId = experimentId;
              adGroupExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED;
              adGroupExperimentData.experimentBidMultipliers = adGroupBidMultiplier;

              adGroup.experimentData = adGroupExperimentData;

              // Create the operation.
              AdGroupOperation adGroupOperation = new AdGroupOperation();
              adGroupOperation.operand = adGroup;
              adGroupOperation.@operator = Operator.SET;

              // Update the ad group.
              AdGroupReturnValue adGroupRetVal = adGroupService.mutate(new AdGroupOperation[] {
              adGroupOperation});

              // Display the results.
              if (adGroupRetVal != null && adGroupRetVal.value != null &&
              adGroupRetVal.value.Length > 0) {
            AdGroup updatedAdGroup = adGroupRetVal.value[0];
            Console.WriteLine("Ad group with name = \"{0}\", id = \"{1}\" and status = \"{2}\" " +
                "was updated for the experiment.\n", updatedAdGroup.name, updatedAdGroup.id,
                updatedAdGroup.status);
              } else {
            Console.WriteLine("No ad groups were updated.");
              }

              // Set ad group criteria for the experiment.
              Criterion criterion = new Criterion();
              criterion.id = criterionId;

              BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion();
              adGroupCriterion.adGroupId = adGroupId;
              adGroupCriterion.criterion = criterion;

              // Create experiment bid multiplier rule that will modify criterion bid
              // for the experiment.
              ManualCPCAdGroupCriterionExperimentBidMultiplier bidMultiplier =
              new ManualCPCAdGroupCriterionExperimentBidMultiplier();
              bidMultiplier.maxCpcMultiplier = new BidMultiplier();
              bidMultiplier.maxCpcMultiplier.multiplier = 1.5;

              // Set experiment data to the criterion.
              BiddableAdGroupCriterionExperimentData adGroupCriterionExperimentData =
              new BiddableAdGroupCriterionExperimentData();
              adGroupCriterionExperimentData.experimentId = experimentId;
              adGroupCriterionExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED;
              adGroupCriterionExperimentData.experimentBidMultiplier = bidMultiplier;

              adGroupCriterion.experimentData = adGroupCriterionExperimentData;

              // Create the operation.
              AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation();
              adGroupCriterionOperation.operand = adGroupCriterion;
              adGroupCriterionOperation.@operator = Operator.SET;

              // Update the ad group criteria.
              AdGroupCriterionReturnValue adGroupCriterionRetVal = adGroupCriterionService.mutate(
              new AdGroupCriterionOperation[] {adGroupCriterionOperation});

              // Display the results.
              if (adGroupCriterionRetVal != null && adGroupCriterionRetVal.value != null &&
              adGroupCriterionRetVal.value.Length > 0) {
            AdGroupCriterion updatedAdGroupCriterion = adGroupCriterionRetVal.value[0];
            Console.WriteLine("Ad group criterion with ad group id = \"{0}\", criterion id = "
                + "\"{1}\" and type = \"{2}\" was updated for the experiment.\n",
                updatedAdGroupCriterion.adGroupId, updatedAdGroupCriterion.criterion.id,
                updatedAdGroupCriterion.criterion.CriterionType);
              } else {
            Console.WriteLine("No ad group criteria were updated.");
              }
            } else {
              Console.WriteLine("No experiments were added.");
            }
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to add experiment.", e);
              }
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group to which keywords are added.
    /// </param>
    public void Run(AdWordsUser user, long adGroupId) {
      // Get the AdGroupCriterionService.
      AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(AdWordsService.v201509.AdGroupCriterionService);

      // Set partial failure mode for the service.
      adGroupCriterionService.RequestHeader.partialFailure = true;

      List<AdGroupCriterionOperation> operations = new List<AdGroupCriterionOperation>();

      // Create the keywords.
      string[] keywords = new String[] {"mars cruise", "inv@lid cruise", "venus cruise",
          "b(a)d keyword cruise"};

      foreach (String keywordText in keywords) {
        Keyword keyword = new Keyword();
        keyword.text = keywordText;
        keyword.matchType = KeywordMatchType.BROAD;

        // Create biddable ad group criterion.
        BiddableAdGroupCriterion keywordBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
        keywordBiddableAdGroupCriterion.adGroupId = adGroupId;
        keywordBiddableAdGroupCriterion.criterion = keyword;

        // Create the operation.
        AdGroupCriterionOperation keywordAdGroupCriterionOperation =
            new AdGroupCriterionOperation();
        keywordAdGroupCriterionOperation.operand = keywordBiddableAdGroupCriterion;
        keywordAdGroupCriterionOperation.@operator = Operator.ADD;
        operations.Add(keywordAdGroupCriterionOperation);
      }

      try {
        // Create the keywords.
        AdGroupCriterionReturnValue result = adGroupCriterionService.mutate(operations.ToArray());

        // Display the results.
        if (result != null && result.value != null) {
          foreach (AdGroupCriterion adGroupCriterionResult in result.value) {
            if (adGroupCriterionResult.criterion != null) {
              Console.WriteLine("Keyword with ad group id '{0}', criterion id '{1}', and " +
                  "text '{2}' was added.\n", adGroupCriterionResult.adGroupId,
                  adGroupCriterionResult.criterion.id,
                  ((Keyword) adGroupCriterionResult.criterion).text);
            }
          }
        } else {
          Console.WriteLine("No keywords were added.");
        }

        // Display the partial failure errors.
        if (result != null && result.partialFailureErrors != null) {
          foreach (ApiError apiError in result.partialFailureErrors) {
            int operationIndex = ErrorUtilities.GetOperationIndex(apiError.fieldPath);
            if (operationIndex != -1) {
              AdGroupCriterion adGroupCriterion = operations[operationIndex].operand;
              Console.WriteLine("Keyword with ad group id '{0}' and text '{1}' "
                  + "triggered a failure for the following reason: '{2}'.\n",
                  adGroupCriterion.adGroupId, ((Keyword) adGroupCriterion.criterion).text,
                  apiError.errorString);
            } else {
              Console.WriteLine("A failure for the following reason: '{0}' has occurred.\n",
                  apiError.errorString);
            }
          }
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to add keywords in partial failure mode.",
            e);
      }
    }
        /// <summary>
        /// Creates a REMOVE operation for the specified node.
        /// </summary>
        /// <param name="node">The node to be removed.</param>
        /// <returns>An operation pair for the node and the REMOVE operation.
        /// </returns>
        private OperationPair CreateRemoveOperation(ProductPartitionNode node)
        {
            PreconditionUtilities.CheckArgument(node.ProductPartitionId >= NEW_ROOT_ID,
              string.Format(ShoppingMessages.NodeForRemoveCannotHaveNegativeId,
              node.ProductPartitionId));

              AdGroupCriterionOperation removeOp = new AdGroupCriterionOperation();
              removeOp.@operator = Operator.REMOVE;
              removeOp.operand = ProductPartitionNodeAdapter.CreateCriterionForRemove(node, adGroupId);

              return new OperationPair(node, removeOp);
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group to which criteria are
    /// added.</param>
    public void Run(AdWordsUser user, long adGroupId) {
      // Get the AdGroupCriterionService.
      AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(AdWordsService.v201509.AdGroupCriterionService);

      // Create biddable ad group criterion for gender
      Gender genderTarget = new Gender();
      // Criterion Id for male. The IDs can be found here
      // https://developers.google.com/adwords/api/docs/appendix/genders
      genderTarget.id = 10;

      BiddableAdGroupCriterion genderBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
      genderBiddableAdGroupCriterion.adGroupId = adGroupId;
      genderBiddableAdGroupCriterion.criterion = genderTarget;

      // Create negative ad group criterion for age range
      AgeRange ageRangeNegative = new AgeRange();
      // Criterion Id for age 18 to 24. The IDs can be found here
      // https://developers.google.com/adwords/api/docs/appendix/ages

      ageRangeNegative.id = 503001;
      NegativeAdGroupCriterion ageRangeNegativeAdGroupCriterion = new NegativeAdGroupCriterion();
      ageRangeNegativeAdGroupCriterion.adGroupId = adGroupId;
      ageRangeNegativeAdGroupCriterion.criterion = ageRangeNegative;

      // Create operations.
      AdGroupCriterionOperation genderBiddableAdGroupCriterionOperation =
          new AdGroupCriterionOperation();
      genderBiddableAdGroupCriterionOperation.operand = genderBiddableAdGroupCriterion;
      genderBiddableAdGroupCriterionOperation.@operator = Operator.ADD;

      AdGroupCriterionOperation ageRangeNegativeAdGroupCriterionOperation =
          new AdGroupCriterionOperation();
      ageRangeNegativeAdGroupCriterionOperation.operand = ageRangeNegativeAdGroupCriterion;
      ageRangeNegativeAdGroupCriterionOperation.@operator = Operator.ADD;

      AdGroupCriterionOperation[] operations = new AdGroupCriterionOperation[] {
          genderBiddableAdGroupCriterionOperation, ageRangeNegativeAdGroupCriterionOperation};

      try {
        // Add ad group criteria.
        AdGroupCriterionReturnValue result = adGroupCriterionService.mutate(operations);

        // Display ad group criteria.
        if (result != null && result.value != null) {
          foreach (AdGroupCriterion adGroupCriterionResult in result.value) {
            Console.WriteLine("Ad group criterion with ad group id \"{0}\", criterion id " +
                "\"{1}\", and type \"{2}\" was added.", adGroupCriterionResult.adGroupId,
                adGroupCriterionResult.criterion.id,
                adGroupCriterionResult.criterion.CriterionType);
          }
        } else {
          Console.WriteLine("No ad group criteria were added.");
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to create ad group criteria.", e);
      }
    }
        /// <summary>
        /// Gets the operations for node.
        /// </summary>
        /// <param name="partitionNode">The partition node.</param>
        /// <param name="mutateOperations">The list of all mutate operations.</param>
        /// <returns>The list of operations that apply to partitionNode.</returns>
        internal List<AdGroupCriterionOperation> GetOperationsForNode(
        ProductPartitionNode partitionNode, AdGroupCriterionOperation[] mutateOperations)
        {
            ProductDimensionEqualityComparer comparer = new ProductDimensionEqualityComparer();
              List<AdGroupCriterionOperation> retval = new List<AdGroupCriterionOperation>();

              foreach (AdGroupCriterionOperation operation in mutateOperations) {
            switch (operation.@operator) {
              case Operator.SET:
              case Operator.REMOVE:
            if (operation.operand.criterion.id == partitionNode.ProductPartitionId) {
              retval.Add(operation);
            }
            break;

              case Operator.ADD:
            if (comparer.Equals((operation.operand.criterion as ProductPartition).caseValue,
                partitionNode.Dimension)) {
              retval.Add(operation);
            }
            break;
            }
              }
              return retval;
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad groups to which keywords are
        /// added.</param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            // Get the MutateJobService.
            MutateJobService mutateJobService = (MutateJobService)user.GetService(
                AdWordsService.v201601.MutateJobService);

            const int    RETRY_INTERVAL = 30;
            const int    RETRIES_COUNT  = 30;
            const int    KEYWORD_NUMBER = 100;
            const string INDEX_REGEX    = "operations\\[(\\d+)\\].operand";

            List <Operation> operations = new List <Operation>();

            // Create AdGroupCriterionOperation to add keywords.
            for (int i = 0; i < KEYWORD_NUMBER; i++)
            {
                Keyword keyword = new Keyword();
                keyword.text      = string.Format("mars cruise {0}", i);
                keyword.matchType = KeywordMatchType.BROAD;

                BiddableAdGroupCriterion criterion = new BiddableAdGroupCriterion();
                criterion.adGroupId = adGroupId;
                criterion.criterion = keyword;

                AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation();
                adGroupCriterionOperation.@operator = Operator.ADD;
                adGroupCriterionOperation.operand   = criterion;

                operations.Add(adGroupCriterionOperation);
            }

            BulkMutateJobPolicy policy = new BulkMutateJobPolicy();

            // You can specify up to 3 job IDs that must successfully complete before
            // this job can be processed.
            policy.prerequisiteJobIds = new long[] {};

            SimpleMutateJob job = mutateJobService.mutate(operations.ToArray(), policy);

            // Wait for the job to complete.
            bool completed  = false;
            int  retryCount = 0;

            Console.WriteLine("Retrieving job status...");

            while (completed == false && retryCount < RETRIES_COUNT)
            {
                BulkMutateJobSelector selector = new BulkMutateJobSelector();
                selector.jobIds = new long[] { job.id };

                try {
                    Job[] allJobs = mutateJobService.get(selector);
                    if (allJobs != null && allJobs.Length > 0)
                    {
                        job = (SimpleMutateJob)allJobs[0];
                        if (job.status == BasicJobStatus.COMPLETED || job.status == BasicJobStatus.FAILED)
                        {
                            completed = true;
                            break;
                        }
                        else
                        {
                            Console.WriteLine("{0}: Current status is {1}, waiting {2} seconds to retry...",
                                              retryCount, job.status, RETRY_INTERVAL);
                            Thread.Sleep(RETRY_INTERVAL * 1000);
                            retryCount++;
                        }
                    }
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to fetch simple mutate job with " +
                                                          "id = {0}.", e);
                }
            }

            if (job.status == BasicJobStatus.COMPLETED)
            {
                // Handle cases where the job completed.

                // Create the job selector.
                BulkMutateJobSelector selector = new BulkMutateJobSelector();
                selector.jobIds = new long[] { job.id };

                // Get the job results.
                JobResult jobResult = mutateJobService.getResult(selector);
                if (jobResult != null)
                {
                    SimpleMutateResult results = (SimpleMutateResult)jobResult.Item;
                    if (results != null)
                    {
                        // Display the results.
                        if (results.results != null)
                        {
                            for (int i = 0; i < results.results.Length; i++)
                            {
                                Operand operand = results.results[i];
                                Console.WriteLine("Operation {0} - {1}", i, (operand.Item is PlaceHolder) ?
                                                  "FAILED" : "SUCCEEDED");
                            }
                        }

                        // Display the errors.
                        if (results.errors != null)
                        {
                            foreach (ApiError apiError in results.errors)
                            {
                                Match  match = Regex.Match(apiError.fieldPath, INDEX_REGEX, RegexOptions.IgnoreCase);
                                string index = (match.Success)? match.Groups[1].Value : "???";
                                Console.WriteLine("Operation index {0} failed due to reason: '{1}', " +
                                                  "trigger: '{2}'", index, apiError.errorString, apiError.trigger);
                            }
                        }
                    }
                }
                Console.WriteLine("Job completed successfully!");
            }
            else if (job.status == BasicJobStatus.FAILED)
            {
                // Handle the cases where job failed.
                Console.WriteLine("Job failed with reason: " + job.failureReason);
            }
            else if (job.status == BasicJobStatus.PROCESSING || job.status == BasicJobStatus.PENDING)
            {
                // Handle the cases where job didn't complete after wait period.
                Console.WriteLine("Job did not complete in {0} secconds.", RETRY_INTERVAL * RETRIES_COUNT);
            }
        }
        /// <summary>
        /// Creates ADD operations for the node and ALL of its children.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="idGenerator">The temporary ID generator for new nodes.</param>
        /// <returns>A list of operation pair for the specified operation and nodes.
        /// </returns>
        private List<OperationPair> CreateAddOperations(ProductPartitionNode node,
        TemporaryIdGenerator idGenerator)
        {
            AdGroupCriterionOperation addOp = new AdGroupCriterionOperation();
              addOp.@operator = Operator.ADD;

              // Overwrite the ID set by the user when doing ADD operations. This
              // minimizes the chances of a malformed tree.
              node.ProductPartitionId = idGenerator.Next;

              addOp.operand = ProductPartitionNodeAdapter.CreateCriterionForAdd(node, adGroupId,
              idGenerator);

              List<OperationPair> operationsList = new List<OperationPair>();
              operationsList.Add(new OperationPair(node, addOp));

              // Recursively add all of this node's children to the operations list.
              foreach (ProductPartitionNode child in node.Children) {
            operationsList.AddRange(CreateAddOperations(child, idGenerator));
              }
              return operationsList;
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group to which keywords are added.
        /// </param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            using (AdGroupCriterionService adGroupCriterionService =
                       (AdGroupCriterionService)user.GetService(AdWordsService.v201802
                                                                .AdGroupCriterionService))
            {
                List <AdGroupCriterionOperation> operations = new List <AdGroupCriterionOperation>();

                foreach (string keywordText in KEYWORDS)
                {
                    // Create the keyword.
                    Keyword keyword = new Keyword
                    {
                        text      = keywordText,
                        matchType = KeywordMatchType.BROAD
                    };

                    // Create the biddable ad group criterion.
                    BiddableAdGroupCriterion keywordCriterion = new BiddableAdGroupCriterion
                    {
                        adGroupId = adGroupId,
                        criterion = keyword,

                        // Optional: Set the user status.
                        userStatus = UserStatus.PAUSED,

                        // Optional: Set the keyword destination url.
                        finalUrls = new UrlList()
                        {
                            urls = new string[]
                            {
                                "http://example.com/mars/cruise/?kw=" +
                                HttpUtility.UrlEncode(keywordText)
                            }
                        }
                    };

                    // Create the operations.
                    AdGroupCriterionOperation operation = new AdGroupCriterionOperation
                    {
                        @operator = Operator.ADD,
                        operand   = keywordCriterion
                    };

                    operations.Add(operation);
                }

                try
                {
                    // Create the keywords.
                    AdGroupCriterionReturnValue retVal =
                        adGroupCriterionService.mutate(operations.ToArray());

                    // Display the results.
                    if (retVal != null && retVal.value != null)
                    {
                        foreach (AdGroupCriterion adGroupCriterion in retVal.value)
                        {
                            // If you are adding multiple type of criteria, then you may need to
                            // check for
                            //
                            // if (adGroupCriterion is Keyword) { ... }
                            //
                            // to identify the criterion type.
                            Console.WriteLine(
                                "Keyword with ad group id = '{0}', keyword id = '{1}', text = " +
                                "'{2}' and match type = '{3}' was created.",
                                adGroupCriterion.adGroupId, adGroupCriterion.criterion.id,
                                (adGroupCriterion.criterion as Keyword).text,
                                (adGroupCriterion.criterion as Keyword).matchType);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No keywords were added.");
                    }
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to create keywords.", e);
                }
            }
        }
 /// <summary>
 /// Creates an AdGroupCriterionOperation for the given criterion
 /// </summary>
 /// <param name="criterion">The criterion we want to add</param>
 private void CreateAddOperation(AdGroupCriterion criterion)
 {
     AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
     operation.operand = criterion;
     operation.@operator = Operator.ADD;
     this.operations.Add(operation);
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="UseSandbox"></param>
        /// <param name="Name"></param>
        /// <param name="Countries"></param>
        /// <param name="Languages"></param>
        /// <param name="BudgetPeriod"></param>
        /// <param name="BudgetAmount"></param>
        /// <param name="MaxAdGroups"></param>
        /// <param name="DisplayUrl"></param>
        /// <param name="destinationUrlPrefix"></param>
        public void CreateCampaignByKeywordDensityContentMatch(bool UseSandbox, Guid AffiliateSiteRefId, int BudgetPeriod,
            Moneyv200906 BudgetAmount, AdGroupCriterionMoneyv200906 KeywordMaxCpc, string DisplayUrl, int MaxAdGroups, int AdKeywordType, int MinKeywordDensity,
            int MaxKeywordDensity, int MinContentMatch, decimal maxApiUsageDollars)
        {
            // Create a user (reads headers from App.config file).
            AdWordsUser user = new AdWordsUser();
            if (UseSandbox)
                user.UseSandbox();	// use sandbox

            AccountService accountService = (AccountService)user.GetService(ApiServices.v13.AccountService);
            string[] accounts = accountService.getClientAccounts();

            try
            {
                #region Create Campaign

                PpcNetwork ppcNetwork = DataRepository.PpcNetworkProvider.GetByName("AdWords");

                TList<PpcCampaign> Campaigns =
                    DataRepository.PpcCampaignProvider.GetByPpcNetworkRefId(ppcNetwork.PpcNetworkRefId);

                foreach (PpcCampaign campaign in Campaigns)
                {
                    // Target the campaign at
                    CampaignServicev200906 campaignService =
                        (com.google.api.adwords.v200906.CampaignService.CampaignService)
                        user.GetService(ApiServices.v200906.CampaignService);

                    // Create a new campaign with an ad group.  First create a
                    // campaign, so we can get its id.
                    Campaignv200906 newCampaign = new Campaignv200906();

                    // The campaign name is optional.  An error results if a campaign
                    // of the same name already exists.
                    newCampaign.name = campaign.CampaignName + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();

                    // Set the campaign status to paused, we don't want to start
                    // paying for this test.
                    // Required: Set the campaign status.
                    newCampaign.status = CampaignStatusv200906.ACTIVE;
                    newCampaign.statusSpecified = true;

                    // Required: Specify the currency and budget amount.
                    Budget budget = new Budget();
                    BudgetAmount.microAmountSpecified = true;
                    budget.amount = BudgetAmount;

                    // Required: Specify the bidding strategy.
                    newCampaign.biddingStrategy = new ManualCPC();

                    // Optional: Specify the budget period and delivery method.
                    budget.periodSpecified = true;
                    budget.period = BudgetBudgetPeriod.DAILY;
                    budget.deliveryMethodSpecified = true;
                    budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD;
                    newCampaign.budget = budget;

                    // Optional: Specify an endDate for the campaign.
                    newCampaign.endDate = DateTime.Now.AddDays(campaign.DurationInDays).ToString("yyyyMMdd");

                    // Define an Add operation to add the campaign.
                    CampaignOperation campaignOperation = new CampaignOperation();

                    campaignOperation.operatorSpecified = true;
                    campaignOperation.@operator = CampaignOperatorv200906.ADD;
                    campaignOperation.operand = newCampaign;

                    try
                    {
                        CampaignReturnValue results =
                            campaignService.mutate(new CampaignOperation[] { campaignOperation });
                        if (results != null && results.value != null && results.value.Length > 0)
                        {
                            newCampaign.id = results.value[0].id;
                            newCampaign.idSpecified = true;
                            Trace.TraceInformation(
                                "New campaign with name = \"{0}\" and id = " + "\"{1}\" was created.",
                                results.value[0].name, results.value[0].id);
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Error:" + ex.Message);
                        throw new Exception("Failed to create campaign. " + ex.Message);
                    }

                #endregion

                    #region Targeting

                    CampaignTargetService service =
                        (CampaignTargetService)user.GetService(ApiServices.v200906.CampaignTargetService);

                    // Create a language target - for English language.
                    LanguageTargetv200906 languageTarget = new LanguageTargetv200906();
                    languageTarget.languageCode = "en"; //TODO: Add as property
                    LanguageTargetList languageTargetList = new LanguageTargetList();
                    languageTargetList.targets = new LanguageTargetv200906[] { languageTarget };
                    languageTargetList.campaignId = newCampaign.id;
                    languageTargetList.campaignIdSpecified = true;

                    // Create a country target - include US, exclude metrocode 743.
                    CountryTargetv200906 countryTarget = new CountryTargetv200906();
                    countryTarget.countryCode = campaign.TargetCountry;
                    countryTarget.excludedSpecified = true;
                    countryTarget.excluded = false;
                    MetroTargetv200906 metroTarget = new MetroTargetv200906();
                    metroTarget.excludedSpecified = true;
                    metroTarget.excluded = true;
                    metroTarget.metroCode = campaign.ExcludeMetroTarget;

                    GeoTargetList geoTargetList = new GeoTargetList();
                    geoTargetList.targets = new GeoTargetv200906[] { countryTarget, metroTarget };
                    geoTargetList.campaignId = newCampaign.id;
                    geoTargetList.campaignIdSpecified = true;

                    // Create a network target - Google Search.
                    NetworkTargetv200906 networkTarget1 = new NetworkTargetv200906();
                    networkTarget1.networkCoverageTypeSpecified = true;
                    networkTarget1.networkCoverageType = NetworkCoverageTypev200906.GOOGLE_SEARCH;
                    NetworkTargetv200906 networkTarget2 = new NetworkTargetv200906();
                    networkTarget2.networkCoverageTypeSpecified = true;
                    networkTarget2.networkCoverageType = NetworkCoverageTypev200906.SEARCH_NETWORK;

                    NetworkTargetList networkTargetList = new NetworkTargetList();
                    networkTargetList.targets = new NetworkTargetv200906[] { networkTarget1, networkTarget2 };
                    networkTargetList.campaignId = newCampaign.id;
                    networkTargetList.campaignIdSpecified = true;

                    TargetList[] targets =
                        new TargetList[] { languageTargetList, geoTargetList, networkTargetList };

                    ArrayList campaignTargetOperations = new ArrayList();

                    foreach (TargetList target in targets)
                    {
                        CampaignTargetOperation ops = new CampaignTargetOperation();
                        ops.operatorSpecified = true;
                        ops.@operator = CampaignTargetOperatorv200906.SET;
                        ops.operand = target;
                        campaignTargetOperations.Add(ops);
                    }

                    try
                    {
                        service.mutate((CampaignTargetOperation[])
                                       campaignTargetOperations.ToArray(typeof(CampaignTargetOperation)));
                        Trace.TraceInformation("Geo, language, and network targeting were " +
                                               "successfully added to campaign id = \"{0}\".", newCampaign.id);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Failed to create campaign targeting. " +
                                         "Exception says \"{0}\"", ex.Message);
                    }

                    #endregion

                    #region Create your Services

                    //create your services
                    List<SeedKeyword> keywords = new List<SeedKeyword>();

                    AdGroupAdServicev200906 adService =
                        (AdGroupAdServicev200906)user.GetService(ApiServices.v200906.AdGroupAdService);
                    KeywordToolService keywordToolService =
                        (KeywordToolService)user.GetService(ApiServices.v13.KeywordToolService);
                    AdGroupServicev200906 adgroupService =
                        (AdGroupServicev200906)user.GetService(ApiServices.v200906.AdGroupService);
                    TrafficEstimatorService trafficEstimatorService =
                        (TrafficEstimatorService)user.GetService(ApiServices.v13.TrafficEstimatorService);

                    #endregion

                    #region Enumerate thru all the keywords by category

                    AdGroupv200906 newAdGroup = null;

                    foreach (
                        SiteCategory siteCategory in
                            DataRepository.SiteCategoryProvider.GetByAffiliateSiteRefId(AffiliateSiteRefId))
                    {
                        int adGroupCnt = 1;
                        //enumerate thru all the keywords
                        foreach (
                            KeywordUrLsDistinct keywordUrLsDistinct in
                                DataRepository.KeywordUrLsDistinctProvider.GetBySiteCategoryRefId(
                                    siteCategory.SiteCategoryRefId))
                        {
                            VList<KeywordDensity> keywordDensityList =
                                DataRepository.KeywordDensityProvider.GetURLKeywordDensity(keywordUrLsDistinct.Url,
                                                                                           MinKeywordDensity,
                                                                                           MaxKeywordDensity).
                                    FindAllDistinct("SiteContent");

                            int GroupAdCount = 0;

                            //check the avg keyword density
                            if (keywordDensityList.Count >= MinContentMatch)
                            {
                                if (adGroupCnt == 1)
                                {
                                    #region Ad AdGroup

                                    if (GroupAdCount >= MaxAdGroups)
                                        break;

                                    //Create an ad group by site category
                                    newAdGroup = new AdGroupv200906();
                                    newAdGroup.name = siteCategory.Name;

                                    newAdGroup.campaignId = newCampaign.id;
                                    newAdGroup.campaignIdSpecified = true;
                                    //newAdGroup.campaignName = newCampaign.name;

                                    // Optional: set the status of adgroup.
                                    newAdGroup.statusSpecified = true;
                                    newAdGroup.status = AdGroupStatus.ENABLED;

                                    // Optional: Create a Manual CPC Bid.
                                    ManualCPCAdGroupBids bids = new ManualCPCAdGroupBids();

                                    // Set the keyword content max cpc.
                                    bids.keywordContentMaxCpc = new Bid();

                                    Money kwdContentMaxCpc = new Money();
                                    kwdContentMaxCpc.microAmountSpecified = true;
                                    kwdContentMaxCpc.microAmount = KeywordMaxCpc.microAmount;
                                    bids.keywordContentMaxCpc.amount = kwdContentMaxCpc;

                                    // Set the keyword max cpc.
                                    bids.keywordMaxCpc = new Bid();
                                    Money kwdMaxCpc = new Money();
                                    kwdMaxCpc.microAmountSpecified = true;
                                    kwdMaxCpc.microAmount = KeywordMaxCpc.microAmount;
                                    bids.keywordMaxCpc.amount = kwdMaxCpc;

                                    // Set the manual bid to the adgroup.
                                    newAdGroup.bids = bids;

                                    AdGroupOperation adGroupOperation = new AdGroupOperation();
                                    adGroupOperation.operatorSpecified = true;
                                    adGroupOperation.@operator = AddGroupOperatorv200906.ADD;
                                    adGroupOperation.operand = newAdGroup;

                                    try
                                    {
                                        AdGroupReturnValue results =
                                            adgroupService.mutate(new AdGroupOperation[] { adGroupOperation });
                                        if (results != null && results.value != null && results.value.Length > 0)
                                        {
                                            newAdGroup.id = results.value[0].id;
                                            newAdGroup.idSpecified = true;
                                            Trace.TraceInformation(
                                                "New ad group with name = \"{0}\" and id = \"{1}\" was created.",
                                                results.value[0].name, results.value[0].id);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Trace.TraceError("Failed to create ad group. Exception says \"{0}\"", ex.Message);
                                    }

                                    adGroupCnt++;

                                    #endregion
                                }

                                Trace.TraceInformation(keywordUrLsDistinct.Url);

                                //Create an add for each product
                                //
                                // IMPORTANT: create an ad before adding keywords!  Else the
                                // minCpc will have a higher value.
                                TList<PpcAdTemplate> ppcAdTemplateList =
                                    DataRepository.PpcAdTemplateProvider.GetByPpcCampaignRefId(campaign.PpcCampaignRefId);
                                foreach (var ppcAdTemplate in ppcAdTemplateList)
                                {

                                    TextAdv200906 newTextAd = new TextAdv200906();
                                    Product prod =
                                        DataRepository.ProductProvider.GetByProductRefId(
                                            (Guid)keywordUrLsDistinct.ProductRefId);
                                    newTextAd.headline = StringUtils.ScrubProdName(prod.Name);

                                    while (newTextAd.headline.Length > 25)
                                    {
                                        // if one word longer than 25 chars
                                        if (newTextAd.headline.LastIndexOf(" ") < 0)
                                            continue;

                                        newTextAd.headline =
                                            newTextAd.headline.Substring(0, newTextAd.headline.LastIndexOf(" ")).
                                                Substring(
                                                0,
                                                newTextAd.headline.Substring(0, newTextAd.headline.LastIndexOf(" "))
                                                    .
                                                    LastIndexOf(" "));
                                    }

                                    newTextAd.description1 = ppcAdTemplate.AdLine1.Replace(KeywordToken,
                                                                                           keywordDensityList[0].Keywords).Replace(ProductNameToken, newTextAd.headline);
                                    newTextAd.description2 = ppcAdTemplate.AdLine2;

                                    //}

                                    newTextAd.displayUrl = DisplayUrl;
                                    newTextAd.url = keywordUrLsDistinct.Url;
                                    //don't add it yet, there is a check below to see if it meets criteria

                                    //SeedKeyword[] keywordsArray = new SeedKeyword[] { new SeedKeyword() };
                                    //keywordsArray = keywords.ToArray();

                                    // Associate this ad group with the newly created campaign.  Send
                                    // the request to add the new ad group.

                                    try
                                    {
                                        //we found a keyword that meets criteria so ad the new Ad.
                                        AdGroupAd adGroupAd = new AdGroupAd();
                                        adGroupAd.adGroupId = newAdGroup.id;
                                        adGroupAd.adGroupIdSpecified = true;
                                        adGroupAd.ad = newTextAd;

                                        AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation();
                                        adGroupAdOperation.operatorSpecified = true;
                                        adGroupAdOperation.@operator = AddGroupAdOperatorv200906.ADD;
                                        adGroupAdOperation.operand = adGroupAd;

                                        AdGroupAdReturnValue result = null;
                                        try
                                        {
                                            result = adService.mutate(new AdGroupAdOperation[] { adGroupAdOperation });

                                            if (result.value != null && result.value.Length > 0)
                                            {
                                                foreach (AdGroupAd tempAdGroupAd in result.value)
                                                {
                                                    Trace.TraceInformation(
                                                        String.Format(
                                                            "New text ad with headline = \"{0}\" and id = \"{1}\" was created.",
                                                            ((TextAdv200906)tempAdGroupAd.ad).headline,
                                                            tempAdGroupAd.ad.id));
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Trace.TraceError("Failed to create Ad(s). Exception says \"{0}\"",
                                                             ex.Message);
                                        }

                                        GroupAdCount++;
                                        Trace.TraceInformation("Text ad" + GroupAdCount + ": " + newTextAd.headline +
                                                               " Text Line1:" +
                                                               newTextAd.description1 + " Text Line2:" +
                                                               newTextAd.description2);

                                        //Trace.TraceInformation("Text ad: " + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2);
                                    }
                                    catch
                                    {
                                        //do nothing
                                        Trace.TraceError("***Text ad Failed:" + newTextAd.headline + " Text Line1:" +
                                                         newTextAd.description1 + " Text Line2:" +
                                                         newTextAd.description2);
                                    }

                                }

                                //Add the Product name as a whole phrase
                                AdGroupCriterionServicev200906 criterionService =
                                    (AdGroupCriterionServicev200906)
                                    user.GetService(ApiServices.v200906.AdGroupCriterionService);

                                foreach (KeywordDensity kd in keywordDensityList)
                                {
                                    try
                                    {
                                        Keywordv200906 newKeyword = new Keywordv200906();
                                        newKeyword.matchTypeSpecified = true;
                                        newKeyword.matchType =
                                            com.google.api.adwords.v200906.AdGroupCriterionService.KeywordMatchType.
                                                BROAD;
                                        newKeyword.text = kd.Keywords;

                                        BiddableAdGroupCriterion criterion = new BiddableAdGroupCriterion();
                                        criterion.adGroupId = newAdGroup.id;
                                        criterion.adGroupIdSpecified = true;
                                        criterion.criterion = newKeyword;
                                        criterion.destinationUrl = kd.Url;

                                        //TODO: Use the Traffic Estimator to determine the
                                        // the maxCpc to use
                                        //newKeyword.maxCpc = KeywordMaxCpc;
                                        //newKeyword.maxCpcSpecified = true;

                                        var adGroupCriterionBids =
                                            new com.google.api.adwords.v200906.AdGroupCriterionService.
                                                ManualCPCAdGroupCriterionBids();

                                        adGroupCriterionBids.maxCpc =
                                            new com.google.api.adwords.v200906.AdGroupCriterionService.Bid();
                                        adGroupCriterionBids.maxCpc.amount = KeywordMaxCpc;
                                        criterion.bids = adGroupCriterionBids;

                                        AdGroupCriterionOperation adGroupCriterionOperation =
                                            new AdGroupCriterionOperation();
                                        adGroupCriterionOperation.@operator =
                                            com.google.api.adwords.v200906.AdGroupCriterionService.Operator.ADD;
                                        adGroupCriterionOperation.operatorSpecified = true;
                                        adGroupCriterionOperation.operand = criterion;

                                        try
                                        {
                                            AdGroupCriterionReturnValue results =
                                                criterionService.mutate(new AdGroupCriterionOperation[] { adGroupCriterionOperation });
                                            if (results != null && results.value != null && results.value.Length > 0)
                                            {
                                                Keywordv200906 result = results.value[0].criterion as Keywordv200906;
                                                Trace.TraceInformation(
                                                    String.Format(
                                                        "New keyword with text = \"{0}\" and id = \"{1}\" was created.",
                                                        result.text, result.id));
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Trace.TraceError(
                                                String.Format(
                                                    "Failed to create keyword at Ad group level. Exception says \"{0}\"",
                                                    ex.Message));
                                        }

                                    }
                                    catch
                                    {
                                        //do nothing
                                        Trace.TraceError("***Add Criteria Failed: Keyword" + kd.Keywords);
                                    }
                                }

                                if (GroupAdCount >= MaxAdGroups)
                                    break;
                            }
                        }
                    }

                    #endregion
                }

                #region Check api usage
                // check api usage
                ApiUsage apiUsage = new ApiUsage();
                APIQuotaValues aPIQuotaValues = apiUsage.GetApiUsage(UseSandbox);

                Trace.TraceInformation("FreeQuotaUsed:" + aPIQuotaValues.FreeQuotaUsed.ToString() + " FreeUnitsRemaining:" + aPIQuotaValues.FreeUnitsRemaining.ToString() + " SysDefinesQuotaCap:" + aPIQuotaValues.SysDefinesQuotaCap.ToString() + " TotalUsed:" + aPIQuotaValues.TotalUsed.ToString());

                #endregion

                #region Log everything created
                //AdGroup[] adGroups = adgroupService.getAllAdGroups(campaignId);

                //foreach (AdGroup adGroup in adGroups)
                //{
                //    Trace.TraceInformation("Ad group: " + adGroup.name);

                //    Ad[] ads = adService.getAllAds(new long[] { adGroup.id });

                //    foreach (Ad ad in ads)
                //    {
                //        if (ad is TextAd)
                //        {
                //            TextAd textAd = (TextAd)ad;
                //            Trace.TraceInformation("Text ad: " + textAd.headline + " Text Line1:" + textAd.description1 + " Text Line2:" + textAd.description2);
                //        }
                //    }
                //}

                #endregion

            }
            catch (Exception ex)
            {
                Trace.TraceError("Error:" + ex.Message);
                throw ex;
            }
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad groups to which keywords are
    /// added.</param>
    public void Run(AdWordsUser user, long adGroupId) {
      // Get the MutateJobService.
      MutateJobService mutateJobService = (MutateJobService) user.GetService(
          AdWordsService.v201509.MutateJobService);

      const int RETRY_INTERVAL = 30;
      const int RETRIES_COUNT = 30;
      const int KEYWORD_NUMBER = 100;
      const string INDEX_REGEX = "operations\\[(\\d+)\\].operand";

      List<Operation> operations = new List<Operation>();

      // Create AdGroupCriterionOperation to add keywords.
      for (int i = 0; i < KEYWORD_NUMBER; i++) {
        Keyword keyword = new Keyword();
        keyword.text = string.Format("mars cruise {0}", i);
        keyword.matchType = KeywordMatchType.BROAD;

        BiddableAdGroupCriterion criterion = new BiddableAdGroupCriterion();
        criterion.adGroupId = adGroupId;
        criterion.criterion = keyword;

        AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation();
        adGroupCriterionOperation.@operator = Operator.ADD;
        adGroupCriterionOperation.operand = criterion;

        operations.Add(adGroupCriterionOperation);
      }

      BulkMutateJobPolicy policy = new BulkMutateJobPolicy();
      // You can specify up to 3 job IDs that must successfully complete before
      // this job can be processed.
      policy.prerequisiteJobIds = new long[] {};

      SimpleMutateJob job = mutateJobService.mutate(operations.ToArray(), policy);

      // Wait for the job to complete.
      bool completed = false;
      int retryCount = 0;
      Console.WriteLine("Retrieving job status...");

      while (completed == false && retryCount < RETRIES_COUNT) {
        BulkMutateJobSelector selector = new BulkMutateJobSelector();
        selector.jobIds = new long[] {job.id};

        try {
          Job[] allJobs = mutateJobService.get(selector);
          if (allJobs != null && allJobs.Length > 0) {
            job = (SimpleMutateJob) allJobs[0];
            if (job.status == BasicJobStatus.COMPLETED || job.status == BasicJobStatus.FAILED) {
              completed = true;
              break;
            } else {
              Console.WriteLine("{0}: Current status is {1}, waiting {2} seconds to retry...",
                  retryCount, job.status, RETRY_INTERVAL);
              Thread.Sleep(RETRY_INTERVAL * 1000);
              retryCount++;
            }
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to fetch simple mutate job with " +
              "id = {0}.", e);
        }
      }

      if (job.status == BasicJobStatus.COMPLETED) {
        // Handle cases where the job completed.

        // Create the job selector.
        BulkMutateJobSelector selector = new BulkMutateJobSelector();
        selector.jobIds = new long[] {job.id};

        // Get the job results.
        JobResult jobResult = mutateJobService.getResult(selector);
        if (jobResult != null) {
          SimpleMutateResult results = (SimpleMutateResult) jobResult.Item;
          if (results != null) {
            // Display the results.
            if (results.results != null) {
              for (int i = 0; i < results.results.Length; i++) {
                Operand operand = results.results[i];
                Console.WriteLine("Operation {0} - {1}", i, (operand.Item is PlaceHolder) ?
                    "FAILED" : "SUCCEEDED");
              }
            }

            // Display the errors.
            if (results.errors != null) {
              foreach (ApiError apiError in results.errors) {
                Match match = Regex.Match(apiError.fieldPath, INDEX_REGEX, RegexOptions.IgnoreCase);
                string index = (match.Success)? match.Groups[1].Value : "???";
                Console.WriteLine("Operation index {0} failed due to reason: '{1}', " +
                    "trigger: '{2}'", index, apiError.errorString, apiError.trigger);
              }
            }
          }
        }
        Console.WriteLine("Job completed successfully!");
      } else if (job.status == BasicJobStatus.FAILED) {
        // Handle the cases where job failed.
        Console.WriteLine("Job failed with reason: " + job.failureReason);
      } else if (job.status == BasicJobStatus.PROCESSING || job.status == BasicJobStatus.PENDING) {
        // Handle the cases where job didn't complete after wait period.
        Console.WriteLine("Job did not complete in {0} secconds.", RETRY_INTERVAL * RETRIES_COUNT);
      }
    }