/// <summary> /// Checks a list of keywords for policy violations, and add the errors to /// a list of traffic estimates. /// </summary> /// <param name="user">The 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> /// 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> /// Creates the default partition. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">The ad group ID.</param> private void CreateDefaultPartitionTree(AdWordsUser user, long adGroupId) { using (AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService( AdWordsService.v201802.AdGroupCriterionService)) { // Build a new ProductPartitionTree using an empty set of criteria. ProductPartitionTree partitionTree = ProductPartitionTree.CreateAdGroupTree(adGroupId, new List <AdGroupCriterion>()); partitionTree.Root.AsBiddableUnit().CpcBid = 1000000; 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> /// 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.v201806 .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> /// 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.v201806 .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> /// 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.v201806.AdGroupCriterionService); adGroupCriterionService.mutate(new AdGroupCriterionOperation[] { removeOp }); } Assert.DoesNotThrow(delegate() { tree = ProductPartitionTree.DownloadAdGroupTree(user, ADGROUP_ID); }); }
/// <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.v201705.AdGroupCriterionService)) { // Create a webpage criterion for special offers for mars cruise. WebpageParameter param = new WebpageParameter(); param.criterionName = "Special offers for mars"; WebpageCondition urlCondition = new WebpageCondition(); urlCondition.operand = WebpageConditionOperand.URL; urlCondition.argument = "/marscruise/special"; WebpageCondition titleCondition = new WebpageCondition(); titleCondition.operand = WebpageConditionOperand.PAGE_TITLE; titleCondition.argument = "Special Offer"; param.conditions = new WebpageCondition[] { urlCondition, titleCondition }; Webpage webpage = new Webpage(); webpage.parameter = param; // Create biddable ad group criterion. BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion(); biddableAdGroupCriterion.adGroupId = adGroupId; biddableAdGroupCriterion.criterion = webpage; biddableAdGroupCriterion.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(); operation.@operator = Operator.ADD; operation.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); } } }
/// <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); } } }
/// <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> /// Executes the tree operations. /// </summary> /// <returns>The synced product partition tree.</returns> private ProductPartitionTree ExecuteTreeOperations() { AdGroupCriterionOperation[] operations = tree.GetMutateOperations(); AdGroupCriterionService service = (AdGroupCriterionService)user.GetService( AdWordsService.v201806.AdGroupCriterionService); service.mutate(operations); return(ProductPartitionTree.DownloadAdGroupTree(user, ADGROUP_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) { 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> /// Creates a product partition tree. /// </summary> /// <param name="user">The AdWords user for which the product partition is created.</param> /// <param name="adGroupId">Ad group ID.</param> /// <returns>The product partition.</returns> private static ProductPartitionTree CreateProductPartition(AdWordsUser user, long adGroupId) { using (AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService(AdWordsService.v201809 .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 to include it. rootNode.AddChild( ProductDimensions.CreateCanonicalCondition(ProductCanonicalConditionCondition .NEW)); // Add a unit node for condition = USED to include it. rootNode.AddChild( ProductDimensions.CreateCanonicalCondition(ProductCanonicalConditionCondition .USED)); // Exclude everything else. rootNode.AddChild(ProductDimensions.CreateCanonicalCondition()).AsExcludedUnit(); // 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); return(partitionTree); } }
public void TestDownloadAdGroupTree() { ProductPartitionTree partitionTree = shoppingTestUtils.CreateTestTreeForAddition(ADGROUP_ID); AdGroupCriterionOperation[] operations = partitionTree.GetMutateOperations(); AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService( AdWordsService.v201607.AdGroupCriterionService); AdGroupCriterionReturnValue value = adGroupCriterionService.mutate(operations); ProductPartitionTree newPartitionTree = ProductPartitionTree.DownloadAdGroupTree(user, ADGROUP_ID); CompareTree(newPartitionTree.Root, partitionTree.Root); }
/// <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> /// 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> /// 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> /// 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) { using (AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService( AdWordsService.v201802.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> /// 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.v201702.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 to which criteria are /// added.</param> public void Run(AdWordsUser user, long adGroupId) { using (AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService(AdWordsService.v201809 .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 id = 10 }; BiddableAdGroupCriterion genderBiddableAdGroupCriterion = new BiddableAdGroupCriterion { adGroupId = adGroupId, 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 id = 503001 }; NegativeAdGroupCriterion ageRangeNegativeAdGroupCriterion = new NegativeAdGroupCriterion { adGroupId = adGroupId, criterion = ageRangeNegative }; // Create operations. AdGroupCriterionOperation genderBiddableAdGroupCriterionOperation = new AdGroupCriterionOperation { operand = genderBiddableAdGroupCriterion, @operator = Operator.ADD }; AdGroupCriterionOperation ageRangeNegativeAdGroupCriterionOperation = new AdGroupCriterionOperation { operand = ageRangeNegativeAdGroupCriterion, @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="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.v201506.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); } }
/// <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.v201402.AdGroupCriterionService); List <AdGroupCriterionOperation> operations = new List <AdGroupCriterionOperation>(); for (int i = 0; i < NUM_ITEMS; i++) { // Create the keyword. Keyword keyword = new Keyword(); keyword.text = "mars cruise"; 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.destinationUrl = "http://example.com/mars/cruise/" + i; // 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 ex) { throw new System.ApplicationException("Failed to create keywords.", ex); } }
/// <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.v201502.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> /// 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.v201607.ExperimentService); // Get the AdGroupService. AdGroupService adGroupService = (AdGroupService)user.GetService(AdWordsService.v201607.AdGroupService); // Get the AdGroupCriterionService. AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService(AdWordsService.v201607.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">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.v201506.AdGroupCriterionService); ProductPartitionHelper helper = new ProductPartitionHelper(adGroupId); // The most trivial partition tree has only a unit node as the root: // helper.createUnit(null, null, 100000); ProductPartition root = helper.CreateSubdivision(null, null); ProductCanonicalCondition newCondition = new ProductCanonicalCondition(); newCondition.condition = ProductCanonicalConditionCondition.NEW; ProductPartition newPartition = helper.CreateUnit(root, newCondition, 200000, false); ProductCanonicalCondition usedCondition = new ProductCanonicalCondition(); usedCondition.condition = ProductCanonicalConditionCondition.USED; ProductPartition usedPartition = helper.CreateUnit(root, usedCondition, 100000, false); ProductPartition otherCondition = helper.CreateSubdivision(root, new ProductCanonicalCondition()); ProductBrand coolBrand = new ProductBrand(); coolBrand.value = "CoolBrand"; helper.CreateUnit(otherCondition, coolBrand, 900000, false); ProductBrand cheapBrand = new ProductBrand(); cheapBrand.value = "CheapBrand"; helper.CreateUnit(otherCondition, cheapBrand, 10000, false); ProductPartition otherBrand = helper.CreateSubdivision(otherCondition, new ProductBrand()); // The value for the bidding category is a fixed ID for the 'Luggage & Bags' // category. You can retrieve IDs for categories from the ConstantDataService. // See the 'GetProductCategoryTaxonomy' example for more details. ProductBiddingCategory luggageAndBags = new ProductBiddingCategory(); luggageAndBags.type = ProductDimensionType.BIDDING_CATEGORY_L1; luggageAndBags.value = -5914235892932915235; helper.CreateUnit(otherBrand, luggageAndBags, 750000, false); ProductBiddingCategory everythingElse = new ProductBiddingCategory(); everythingElse.type = ProductDimensionType.BIDDING_CATEGORY_L1; helper.CreateUnit(otherBrand, everythingElse, 110000, false); try { // Make the mutate request. AdGroupCriterionReturnValue retval = adGroupCriterionService.mutate(helper.Operations); Dictionary <long, List <ProductPartition> > children = new Dictionary <long, List <ProductPartition> >(); ProductPartition rootNode = null; // For each criterion, make an array containing each of its children // We always create the parent before the child, so we can rely on that here. foreach (AdGroupCriterion adGroupCriterion in retval.value) { ProductPartition newCriterion = (ProductPartition)adGroupCriterion.criterion; children[newCriterion.id] = new List <ProductPartition>(); if (newCriterion.parentCriterionIdSpecified) { children[newCriterion.parentCriterionId].Add(newCriterion); } else { rootNode = (ProductPartition)adGroupCriterion.criterion; } } // Show the tree StringWriter writer = new StringWriter(); DisplayTree(rootNode, children, 0, writer); Console.WriteLine(writer.ToString()); } catch (Exception ex) { throw new System.ApplicationException("Failed to set shopping product partition.", ex); } }
/// <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.v201607.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); } }
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); } }