Пример #1
0
        /// <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 updated.</param>
        public void Run(AdWordsUser user, long adGroupId, long placementId)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(AdWordsService.v201506.AdGroupCriterionService);

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

            criterion.id = placementId;

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

            biddableAdGroupCriterion.adGroupId = adGroupId;
            biddableAdGroupCriterion.criterion = criterion;

            // Create the bids.
            BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
            CpmBid cpmBid = new CpmBid();

            cpmBid.bid             = new Money();
            cpmBid.bid.microAmount = 1000000;
            biddingConfig.bids     = new Bids[] { cpmBid };

            biddableAdGroupCriterion.biddingStrategyConfiguration = biddingConfig;

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

            operation.@operator = Operator.SET;
            operation.operand   = biddableAdGroupCriterion;

            try {
                // Update the placement.
                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 CpmBid)
                        {
                            bidAmount = (bids as CpmBid).bid.microAmount;
                            break;
                        }
                    }
                    Console.WriteLine("Placement with ad group id = '{0}', id = '{1}' was updated with " +
                                      "bid amount = '{2}' micros.", adGroupCriterion.adGroupId,
                                      adGroupCriterion.criterion.id, bidAmount);
                }
                else
                {
                    Console.WriteLine("No placement was updated.");
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to update placement.", ex);
            }
        }
Пример #2
0
        /// <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)) {
                // Set partial failure mode for the service.
                adGroupCriterionService.RequestHeader.partialFailure = true;

                try {
                    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);
                    }

                    // 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 = apiError.GetOperationIndex();
                            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);
                }
            }
        }
Пример #3
0
        /// <summary>
        /// Checks a list of keywords for policy violations, and add the errors to
        /// a list of traffic estimates.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="trafficEstimates">The list of keywords and their traffic
        /// estimates.</param>
        /// <param name="adGroupId">The ad group ID.</param>
        /// <remarks>Users can use the policy violation details to decide whether
        /// to pick a keyword and submit an exemption request, or skip the
        /// violating keyword and scout for other keywords that are policy
        /// compliant.</remarks>
        private void CheckPolicyViolations(AdWordsUser user, List <TrafficEstimate> trafficEstimates,
                                           long adGroupId)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(
                    AdWordsService.v201603.AdGroupCriterionService);

            adGroupCriterionService.RequestHeader.validateOnly = true;

            for (int i = 0; i < trafficEstimates.Count; i += Settings.AGCS_KEYWORDS_LIST_SIZE)
            {
                List <AdGroupCriterionOperation> operations = new List <AdGroupCriterionOperation>();

                for (int j = i; j < i + Settings.AGCS_KEYWORDS_LIST_SIZE &&
                     j < trafficEstimates.Count; j++)
                {
                    AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
                    {
                        @operator = Operator.ADD,
                        operand   = new BiddableAdGroupCriterion()
                        {
                            adGroupId = adGroupId,
                            criterion = new Keyword()
                            {
                                text      = trafficEstimates[i].Keyword.KeywordText,
                                matchType = trafficEstimates[i].MatchType,
                            },
                            userStatus = UserStatus.ENABLED
                        }
                    };

                    operations.Add(operation);
                }

                try {
                    AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(
                        operations.ToArray());
                } catch (AdWordsApiException e) {
                    ApiException innerException = e.ApiException as ApiException;
                    if (innerException == null)
                    {
                        throw new Exception("Failed to retrieve ApiError. See inner exception for more " +
                                            "details.", e);
                    }

                    // Examine each ApiError received from the server.
                    foreach (ApiError apiError in innerException.errors)
                    {
                        int index = ErrorUtilities.GetOperationIndex(apiError.fieldPath);
                        if (index == -1)
                        {
                            // This API error is not associated with an operand, so we cannot
                            // recover from this error by removing one or more operations.
                            // Rethrow the exception for manual inspection.
                            throw;
                        }

                        // Handle policy violation errors.
                        if (apiError is PolicyViolationError)
                        {
                            PolicyViolationError policyError = (PolicyViolationError)apiError;
                            trafficEstimates[i + index].Errors.Add(policyError);
                        }
                    }
                }
            }
            return;
        }
        /// <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)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(AdWordsService.v201705.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);
            }
        }
Пример #5
0
        /// <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.v201409.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 ex) {
                Console.WriteLine("Failed to create placements.", ex);
            }
        }
Пример #6
0
        public static AdGroupCriterionReturnValue AddKeyWordsToAdGroup(AdWordsUser user, long adGroupId, string keyWords)
        {
            using (AdGroupCriterionService adGroupCriterionService =
                       (AdGroupCriterionService)user.GetService(
                           AdWordsService.v201710.AdGroupCriterionService))
            {
                AdGroupCriterionReturnValue      retVal     = new AdGroupCriterionReturnValue();
                List <AdGroupCriterionOperation> operations = new List <AdGroupCriterionOperation>();

                string[] keyWordsArray = keyWords.Split(',');

                foreach (string keywordText in keyWordsArray)
                {
                    // 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.ENABLED;

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

                    operations.Add(operation);
                }
                try
                {
                    // Create the keywords.
                    retVal = adGroupCriterionService.mutate(
                        operations.ToArray());
                }
                catch (AdWordsApiException e)
                {
                    ApiException innerException = e.ApiException as ApiException;
                    if (innerException == null)
                    {
                        throw new Exception("Failed to retrieve ApiError. See inner exception for more " +
                                            "details.", e);
                    }

                    // Examine each ApiError received from the server.
                    foreach (ApiError apiError in innerException.errors)
                    {
                        int index = apiError.GetOperationIndex();
                        if (index == -1)
                        {
                            // This API error is not associated with an operand, so we cannot
                            // recover from this error by removing one or more operations.
                            // Rethrow the exception for manual inspection.
                            throw;
                        }

                        // Handle policy violation errors.
                        if (apiError is PolicyViolationError)
                        {
                            PolicyViolationError policyError = (PolicyViolationError)apiError;

                            if (policyError.isExemptable)
                            {
                                // If the policy violation error is exemptable, add an exemption
                                // request.
                                List <ExemptionRequest> exemptionRequests = new List <ExemptionRequest>();
                            }
                            else
                            {
                                // Policy violation error is not exemptable, remove this
                                // operation from the list of operations.
                            }
                        }
                        else
                        {
                            // This is not a policy violation error, remove this operation
                            // from the list of operations.
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to create keywords.", e);
                }
                return(retVal);
            }
        }
        /// <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.v201603.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>
        /// 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.v201402.ExperimentService);

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

            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(AdWordsService.v201402.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.ACTIVE;

            // 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 ex) {
                throw new System.ApplicationException("Failed to add experiment.", ex);
            }
        }
Пример #9
0
        /// <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);
            }
        }
Пример #10
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(AdWordsService.v201406.AdGroupCriterionService);

            // Create a selector.
            Selector selector = new Selector();

            selector.fields = new string[] { "Id", "AdGroupId", "KeywordText" };

            // Select only keywords.
            Predicate predicate = new Predicate();

            predicate.field     = "CriteriaType";
            predicate.@operator = PredicateOperator.EQUALS;
            predicate.values    = new string[] { "KEYWORD" };
            selector.predicates = new Predicate[] { predicate };

            // Set the selector paging.
            selector.paging = new Paging();

            int offset   = 0;
            int pageSize = 500;

            AdGroupCriterionPage page = new AdGroupCriterionPage();

            try {
                do
                {
                    selector.paging.startIndex    = offset;
                    selector.paging.numberResults = pageSize;

                    // Get the keywords.
                    page = adGroupCriterionService.get(selector);

                    // Display the results.
                    if (page != null && page.entries != null)
                    {
                        int i = offset;

                        foreach (AdGroupCriterion adGroupCriterion in page.entries)
                        {
                            bool isNegative = (adGroupCriterion is NegativeAdGroupCriterion);

                            // If you are retrieving multiple type of criteria, then you may
                            // need to check for
                            //
                            // if (adGroupCriterion is Keyword) { ... }
                            //
                            // to identify the criterion type.
                            Keyword keyword = (Keyword)adGroupCriterion.criterion;
                            if (isNegative)
                            {
                                Console.WriteLine("{0}) Negative keyword with ad group ID = '{1}', keyword ID " +
                                                  "= '{2}', and text = '{3}' was found.", i + 1, adGroupCriterion.adGroupId,
                                                  keyword.id, keyword.text);
                            }
                            else
                            {
                                Console.WriteLine("{0}) Keyword with ad group ID = '{1}', keyword ID = '{2}', " +
                                                  "text = '{3}' and matchType = '{4} was found.", i + 1,
                                                  adGroupCriterion.adGroupId, keyword.id, keyword.text, keyword.matchType);
                            }
                            i++;
                        }
                    }
                    offset += pageSize;
                } while (offset < page.totalNumEntries);
                Console.WriteLine("Number of keywords found: {0}", page.totalNumEntries);
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to retrieve keywords.", ex);
            }
        }
Пример #11
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(
                    AdWordsService.v201509.AdGroupCriterionService);

            // Create a selector.
            Selector selector = new Selector()
            {
                fields = new string[] {
                    Criterion.Fields.Id, AdGroupCriterion.Fields.AdGroupId, Placement.Fields.PlacementUrl
                },
                predicates = new Predicate[] {
                    // Select only placements.
                    Predicate.Equals(Criterion.Fields.CriteriaType, "PLACEMENT")
                },
                paging = Paging.Default
            };

            AdGroupCriterionPage page = new AdGroupCriterionPage();

            try {
                do
                {
                    // Get the keywords.
                    page = adGroupCriterionService.get(selector);

                    // Display the results.
                    if (page != null && page.entries != null)
                    {
                        int i = selector.paging.startIndex;

                        foreach (AdGroupCriterion adGroupCriterion in page.entries)
                        {
                            bool isNegative = (adGroupCriterion is NegativeAdGroupCriterion);

                            // If you are retrieving multiple type of criteria, then you may
                            // need to check for
                            //
                            // if (adGroupCriterion is Placement) { ... }
                            //
                            // to identify the criterion type.
                            Placement placement = (Placement)adGroupCriterion.criterion;
                            if (isNegative)
                            {
                                Console.WriteLine("{0}) Negative placement with ad group ID = '{1}', placement " +
                                                  "ID = '{2}', and url = '{3}' was found.", i + 1, adGroupCriterion.adGroupId,
                                                  placement.id, placement.url);
                            }
                            else
                            {
                                Console.WriteLine("{0}) Placement with ad group ID = '{1}', placement ID = " +
                                                  "'{2}' and url = '{3}' was found.", i + 1, adGroupCriterion.adGroupId,
                                                  placement.id, placement.url);
                            }
                            i++;
                        }
                    }
                    selector.paging.IncreaseOffset();
                } while (selector.paging.startIndex < page.totalNumEntries);
                Console.WriteLine("Number of placements found: {0}", page.totalNumEntries);
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to retrieve placements.", e);
            }
        }
Пример #12
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">ID of the ad group from which keywords are
        /// retrieved.</param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            using (AdGroupCriterionService adGroupCriterionService =
                       (AdGroupCriterionService)user.GetService(AdWordsService.v201809
                                                                .AdGroupCriterionService))
            {
                // Create a selector.
                Selector selector = new Selector()
                {
                    fields = new string[]
                    {
                        Keyword.Fields.Id,
                        Keyword.Fields.KeywordMatchType,
                        Keyword.Fields.KeywordText,
                        Keyword.Fields.CriteriaType
                    },
                    predicates = new Predicate[]
                    {
                        // Select only keywords.
                        Predicate.In(Keyword.Fields.CriteriaType, new string[]
                        {
                            "KEYWORD"
                        }),

                        // Restrict search to an ad group.
                        Predicate.Equals(AdGroupCriterion.Fields.AdGroupId, adGroupId),
                    },
                    ordering = new OrderBy[]
                    {
                        OrderBy.Asc(Keyword.Fields.KeywordText)
                    },
                    paging = Paging.Default
                };

                AdGroupCriterionPage page = new AdGroupCriterionPage();

                try
                {
                    do
                    {
                        // Get the keywords.
                        page = adGroupCriterionService.get(selector);

                        // Display the results.
                        if (page != null && page.entries != null)
                        {
                            int i = selector.paging.startIndex;

                            foreach (AdGroupCriterion adGroupCriterion in page.entries)
                            {
                                Keyword keyword = (Keyword)adGroupCriterion.criterion;

                                Console.WriteLine(
                                    "{0}) Keyword with text '{1}', match type '{2}', criteria " +
                                    "type '{3}', and ID {4} was found.", i + 1, keyword.text,
                                    keyword.matchType, keyword.type, keyword.id);
                                i++;
                            }
                        }

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

                    Console.WriteLine("Number of keywords found: {0}", page.totalNumEntries);
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to retrieve keywords.", e);
                }
            }
        }
Пример #13
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(
                    AdWordsService.v201502.AdGroupCriterionService);

            // Create a selector.
            Selector selector = new Selector();

            selector.fields = new string[] { "Id", "AdGroupId", "PlacementUrl" };

            // Select only keywords.
            Predicate predicate = new Predicate();

            predicate.field     = "CriteriaType";
            predicate.@operator = PredicateOperator.EQUALS;
            predicate.values    = new string[] { "PLACEMENT" };
            selector.predicates = new Predicate[] { predicate };

            // Set the selector paging.
            selector.paging = new Paging();

            int offset   = 0;
            int pageSize = 500;

            AdGroupCriterionPage page = new AdGroupCriterionPage();

            try {
                do
                {
                    selector.paging.startIndex    = offset;
                    selector.paging.numberResults = pageSize;

                    // Get the keywords.
                    page = adGroupCriterionService.get(selector);

                    // Display the results.
                    if (page != null && page.entries != null)
                    {
                        int i = offset;

                        foreach (AdGroupCriterion adGroupCriterion in page.entries)
                        {
                            bool isNegative = (adGroupCriterion is NegativeAdGroupCriterion);

                            // If you are retrieving multiple type of criteria, then you may
                            // need to check for
                            //
                            // if (adGroupCriterion is Placement) { ... }
                            //
                            // to identify the criterion type.
                            Placement placement = (Placement)adGroupCriterion.criterion;
                            if (isNegative)
                            {
                                Console.WriteLine("{0}) Negative placement with ad group ID = '{1}', placement " +
                                                  "ID = '{2}', and url = '{3}' was found.", i, adGroupCriterion.adGroupId,
                                                  placement.id, placement.url);
                            }
                            else
                            {
                                Console.WriteLine("{0}) Placement with ad group ID = '{1}', placement ID = '{2}' " +
                                                  "and url = '{3}' was found.", i, adGroupCriterion.adGroupId,
                                                  placement.id, placement.url);
                            }
                            i++;
                        }
                    }
                    offset += pageSize;
                } while (offset < page.totalNumEntries);
                Console.WriteLine("Number of placements found: {0}", page.totalNumEntries);
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to retrieve placements.");
            }
        }
        /// <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.v201406.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);
            }
        }
Пример #15
0
            /// <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.v201502.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>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">ID of the ad group from which keywords are
        /// retrieved.</param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(
                    AdWordsService.v201509.AdGroupCriterionService);

            // Create a selector.
            Selector selector = new Selector()
            {
                fields = new string[] {
                    Keyword.Fields.Id, Keyword.Fields.KeywordMatchType,
                    Keyword.Fields.KeywordText, Keyword.Fields.CriteriaType
                },
                predicates = new Predicate[] {
                    // Select only keywords.
                    Predicate.In(Keyword.Fields.CriteriaType, new string[] { "KEYWORD" }),

                    // Restrict search to an ad group.
                    Predicate.Equals(AdGroupCriterion.Fields.AdGroupId, adGroupId),
                },
                paging = Paging.Default
            };

            AdGroupCriterionPage page = new AdGroupCriterionPage();

            try {
                do
                {
                    // Get the keywords.
                    page = adGroupCriterionService.get(selector);

                    // Display the results.
                    if (page != null && page.entries != null)
                    {
                        int i = selector.paging.startIndex;

                        foreach (AdGroupCriterion adGroupCriterion in page.entries)
                        {
                            bool isNegative = (adGroupCriterion is NegativeAdGroupCriterion);

                            // If you are retrieving multiple type of criteria, then you may
                            // need to check for
                            //
                            // if (adGroupCriterion is Keyword) { ... }
                            //
                            // to identify the criterion type.
                            Keyword keyword     = (Keyword)adGroupCriterion.criterion;
                            string  keywordType = isNegative ? "Negative keyword" : "Keyword";

                            Console.WriteLine("{0}) {1} with text = '{2}', matchtype = '{3}', ID = '{4}' and " +
                                              "criteria type = '{5}' was found.", i + 1, keywordType, keyword.text,
                                              keyword.matchType, keyword.id, keyword.CriterionType);
                            i++;
                        }
                    }
                    selector.paging.IncreaseOffset();
                } while (selector.paging.startIndex < page.totalNumEntries);
                Console.WriteLine("Number of keywords found: {0}", page.totalNumEntries);
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to retrieve keywords.", e);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">The ad group to which product partition is
        /// added.</param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(
                    AdWordsService.v201705.AdGroupCriterionService);

            // Build a new ProductPartitionTree using the ad group's current set of criteria.
            ProductPartitionTree partitionTree =
                ProductPartitionTree.DownloadAdGroupTree(user, adGroupId);

            Console.WriteLine("Original tree: {0}", partitionTree);

            // Clear out any existing criteria.
            ProductPartitionNode rootNode = partitionTree.Root.RemoveAllChildren();

            // Make the root node a subdivision.
            rootNode = rootNode.AsSubdivision();

            // Add a unit node for condition = NEW.
            ProductPartitionNode newConditionNode = rootNode.AddChild(
                ProductDimensions.CreateCanonicalCondition(ProductCanonicalConditionCondition.NEW));

            newConditionNode.AsBiddableUnit().CpcBid = 200000;

            ProductPartitionNode usedConditionNode = rootNode.AddChild(
                ProductDimensions.CreateCanonicalCondition(ProductCanonicalConditionCondition.USED));

            usedConditionNode.AsBiddableUnit().CpcBid = 100000;

            // Add a subdivision node for condition = null (everything else).
            ProductPartitionNode otherConditionNode =
                rootNode.AddChild(ProductDimensions.CreateCanonicalCondition()).AsSubdivision();

            // Add a unit node under condition = null for brand = "CoolBrand".
            ProductPartitionNode coolBrandNode = otherConditionNode.AddChild(
                ProductDimensions.CreateBrand("CoolBrand"));

            coolBrandNode.AsBiddableUnit().CpcBid = 900000L;

            // Add a unit node under condition = null for brand = "CheapBrand".
            ProductPartitionNode cheapBrandNode = otherConditionNode.AddChild(
                ProductDimensions.CreateBrand("CheapBrand"));

            cheapBrandNode.AsBiddableUnit().CpcBid = 10000L;

            // Add a subdivision node under condition = null for brand = null (everything else).
            ProductPartitionNode otherBrandNode = otherConditionNode.AddChild(
                ProductDimensions.CreateBrand(null)).AsSubdivision();

            // Add unit nodes under condition = null/brand = null.
            // The value for each bidding category is a fixed ID for a specific
            // category. You can retrieve IDs for categories from the ConstantDataService.
            // See the 'GetProductCategoryTaxonomy' example for more details.

            // Add a unit node under condition = null/brand = null for product type
            // level 1 = 'Luggage & Bags'.
            ProductPartitionNode luggageAndBagNode = otherBrandNode.AddChild(
                ProductDimensions.CreateBiddingCategory(ProductDimensionType.BIDDING_CATEGORY_L1,
                                                        -5914235892932915235L));

            luggageAndBagNode.AsBiddableUnit().CpcBid = 750000L;

            // Add a unit node under condition = null/brand = null for product type
            // level 1 = null (everything else).
            ProductPartitionNode everythingElseNode = otherBrandNode.AddChild(
                ProductDimensions.CreateBiddingCategory(ProductDimensionType.BIDDING_CATEGORY_L1));

            everythingElseNode.AsBiddableUnit().CpcBid = 110000L;

            try {
                // Make the mutate request, using the operations returned by the ProductPartitionTree.
                AdGroupCriterionOperation[] mutateOperations = partitionTree.GetMutateOperations();

                if (mutateOperations.Length == 0)
                {
                    Console.WriteLine("Skipping the mutate call because the original tree and the current " +
                                      "tree are logically identical.");
                }
                else
                {
                    adGroupCriterionService.mutate(mutateOperations);
                }

                // The request was successful, so create a new ProductPartitionTree based on the updated
                // state of the ad group.
                partitionTree = ProductPartitionTree.DownloadAdGroupTree(user, adGroupId);

                Console.WriteLine("Final tree: {0}", partitionTree);
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to set shopping product partition.", e);
            }
        }
        /// <summary>
        /// Adds a web page criterion to target Dynamic Search Ads.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">The ad group ID.</param>
        /// <returns>The newly created web page criterion.</returns>
        private static BiddableAdGroupCriterion AddWebPageCriteria(AdWordsUser user, long adGroupId)
        {
            using (AdGroupCriterionService adGroupCriterionService =
                       (AdGroupCriterionService)user.GetService(
                           AdWordsService.v201802.AdGroupCriterionService)) {
                // Create a webpage criterion for special offers for mars cruise.
                WebpageParameter param = new WebpageParameter {
                    criterionName = "Special offers for mars"
                };

                WebpageCondition urlCondition = new WebpageCondition {
                    operand  = WebpageConditionOperand.URL,
                    argument = "/marscruise/special"
                };

                WebpageCondition titleCondition = new WebpageCondition {
                    operand  = WebpageConditionOperand.PAGE_TITLE,
                    argument = "Special Offer"
                };

                param.conditions = new WebpageCondition[] { urlCondition, titleCondition };

                Webpage webpage = new Webpage {
                    parameter = param
                };

                // Create biddable ad group criterion.
                BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion {
                    adGroupId  = adGroupId,
                    criterion  = webpage,
                    userStatus = UserStatus.PAUSED
                };

                // Optional: set a custom bid.
                BiddingStrategyConfiguration biddingStrategyConfiguration =
                    new BiddingStrategyConfiguration();
                CpcBid bid = new CpcBid()
                {
                    bid = new Money()
                    {
                        microAmount = 10000000L
                    }
                };
                biddingStrategyConfiguration.bids = new Bids[] { bid };
                biddableAdGroupCriterion.biddingStrategyConfiguration = biddingStrategyConfiguration;

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

                try {
                    AdGroupCriterionReturnValue result = adGroupCriterionService.mutate(
                        new AdGroupCriterionOperation[] { operation });

                    BiddableAdGroupCriterion newCriterion = (BiddableAdGroupCriterion)result.value[0];
                    Console.WriteLine("Webpage criterion with ID = '{0}' was added to ad group ID '{1}'.",
                                      newCriterion.criterion.id, newCriterion.adGroupId);
                    return(newCriterion);
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to create webpage criterion.", e);
                }
            }
        }