The code samples below provide examples for managing Shopping campaigns using the AdWords API. Client Library.
Build a product partition tree for an ad group
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.AdWords.Lib; using Google.Api.Ads.AdWords.Util.Shopping.v201809; using Google.Api.Ads.AdWords.v201809; using System; namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809 { /// <summary> /// This code example creates a ProductPartition tree. /// </summary> public class AddProductPartitionTree : ExampleBase { /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { AddProductPartitionTree codeExample = new AddProductPartitionTree(); Console.WriteLine(codeExample.Description); try { long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE"); codeExample.Run(new AdWordsUser(), adGroupId); } catch (Exception e) { Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(e)); } } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example creates a ProductPartition tree."; } } /// <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.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. 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); } } } } }
Set a product scope for a campaign
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.AdWords.Lib; using Google.Api.Ads.AdWords.v201809; using System; namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809 { /// <summary> /// This code example restricts the products that will be included in the /// campaign by setting a ProductScope. /// </summary> public class AddProductScope : ExampleBase { /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example restricts the products that will be included in the " + "campaign by setting a ProductScope."; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { AddProductScope codeExample = new AddProductScope(); Console.WriteLine(codeExample.Description); try { long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE"); codeExample.Run(new AdWordsUser(), campaignId); } catch (Exception e) { Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(e)); } } /// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">The campaign id to add product scope.</param> public void Run(AdWordsUser user, long campaignId) { using (CampaignCriterionService campaignCriterionService = (CampaignCriterionService) user.GetService(AdWordsService.v201809 .CampaignCriterionService)) { ProductScope productScope = new ProductScope(); // This set of dimensions is for demonstration purposes only. It would be // extremely unlikely that you want to include so many dimensions in your // product scope. ProductBrand nexusBrand = new ProductBrand { value = "Nexus" }; ProductCanonicalCondition newProducts = new ProductCanonicalCondition { condition = ProductCanonicalConditionCondition.NEW }; ProductCustomAttribute customAttribute = new ProductCustomAttribute { type = ProductDimensionType.CUSTOM_ATTRIBUTE_0, value = "my attribute value" }; ProductOfferId bookOffer = new ProductOfferId { value = "book1" }; ProductType mediaProducts = new ProductType { type = ProductDimensionType.PRODUCT_TYPE_L1, value = "Media" }; ProductType bookProducts = new ProductType { type = ProductDimensionType.PRODUCT_TYPE_L2, value = "Books" }; // 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 luggageBiddingCategory = new ProductBiddingCategory { type = ProductDimensionType.BIDDING_CATEGORY_L1, value = -5914235892932915235 }; productScope.dimensions = new ProductDimension[] { nexusBrand, newProducts, bookOffer, mediaProducts, luggageBiddingCategory }; CampaignCriterion campaignCriterion = new CampaignCriterion { campaignId = campaignId, criterion = productScope }; // Create operation. CampaignCriterionOperation operation = new CampaignCriterionOperation { operand = campaignCriterion, @operator = Operator.ADD }; try { // Make the mutate request. CampaignCriterionReturnValue result = campaignCriterionService.mutate( new CampaignCriterionOperation[] { operation }); Console.WriteLine("Created a ProductScope criterion with ID '{0}'", result.value[0].criterion.id); } catch (Exception e) { throw new System.ApplicationException("Failed to set shopping product scope.", e); } } } } }
Add a Shopping campaign
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.AdWords.Lib; using Google.Api.Ads.AdWords.Util.Shopping.v201809; using Google.Api.Ads.AdWords.v201809; using System; using System.Collections.Generic; namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809 { /// <summary> /// This code example adds a Shopping campaign. /// </summary> public class AddShoppingCampaign : ExampleBase { /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example adds a Shopping campaign."; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { AddShoppingCampaign codeExample = new AddShoppingCampaign(); Console.WriteLine(codeExample.Description); try { long budgetId = long.Parse("INSERT_BUDGET_ID_HERE"); long merchantId = long.Parse("INSERT_MERCHANT_ID_HERE"); bool createDefaultPartition = false; codeExample.Run(new AdWordsUser(), budgetId, merchantId, createDefaultPartition); } catch (Exception e) { Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(e)); } } /// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="budgetId">The budget id.</param> /// <param name="merchantId">The Merchant Center account ID.</param> /// <param name="createDefaultPartition">If set to true, a default /// partition will be created. If running the AddProductPartition.cs /// example right after this example, make sure this stays set to /// false.</param> public void Run(AdWordsUser user, long budgetId, long merchantId, bool createDefaultPartition) { try { Campaign campaign = CreateCampaign(user, budgetId, merchantId); Console.WriteLine("Campaign with name '{0}' and ID '{1}' was added.", campaign.name, campaign.id); AdGroup adGroup = CreateAdGroup(user, campaign.id); Console.WriteLine("Ad group with name '{0}' and ID '{1}' was added.", adGroup.name, adGroup.id); AdGroupAd adGroupAd = CreateProductAd(user, adGroup.id); Console.WriteLine("Product ad with ID {0}' was added.", adGroupAd.ad.id); if (createDefaultPartition) { CreateDefaultPartitionTree(user, adGroup.id); } } catch (Exception e) { throw new System.ApplicationException("Failed to create shopping campaign.", e); } } /// <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.v201809 .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 Product Ad. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">The ad group ID.</param> /// <returns>The Product Ad.</returns> private static AdGroupAd CreateProductAd(AdWordsUser user, long adGroupId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService(AdWordsService.v201809.AdGroupAdService)) { // Create product ad. ProductAd productAd = new ProductAd(); // Create ad group ad. AdGroupAd adGroupAd = new AdGroupAd { adGroupId = adGroupId, ad = productAd }; // Create operation. AdGroupAdOperation operation = new AdGroupAdOperation { operand = adGroupAd, @operator = Operator.ADD }; // Make the mutate request. AdGroupAdReturnValue retval = adGroupAdService.mutate(new AdGroupAdOperation[] { operation }); return retval.value[0]; } } /// <summary> /// Creates the ad group in a Shopping campaign. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">The campaign ID.</param> /// <returns>The ad group.</returns> private static AdGroup CreateAdGroup(AdWordsUser user, long campaignId) { using (AdGroupService adGroupService = (AdGroupService) user.GetService(AdWordsService.v201809.AdGroupService)) { // Create ad group. AdGroup adGroup = new AdGroup { campaignId = campaignId, name = "Ad Group #" + ExampleUtilities.GetRandomString() }; // Create operation. AdGroupOperation operation = new AdGroupOperation { operand = adGroup, @operator = Operator.ADD }; // Make the mutate request. AdGroupReturnValue retval = adGroupService.mutate(new AdGroupOperation[] { operation }); return retval.value[0]; } } /// <summary> /// Creates the shopping campaign. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="budgetId">The budget id.</param> /// <param name="merchantId">The Merchant Center id.</param> /// <returns>The Shopping campaign.</returns> private static Campaign CreateCampaign(AdWordsUser user, long budgetId, long merchantId) { using (CampaignService campaignService = (CampaignService) user.GetService(AdWordsService.v201809.CampaignService)) { // Create campaign. Campaign campaign = new Campaign { name = "Shopping campaign #" + ExampleUtilities.GetRandomString(), // The advertisingChannelType is what makes this a Shopping campaign. advertisingChannelType = AdvertisingChannelType.SHOPPING, // Recommendation: Set the campaign to PAUSED when creating it to prevent // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve. status = CampaignStatus.PAUSED, // Set shared budget (required). budget = new Budget { budgetId = budgetId } }; // Set bidding strategy (required). BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration { biddingStrategyType = BiddingStrategyType.MANUAL_CPC }; campaign.biddingStrategyConfiguration = biddingStrategyConfiguration; // All Shopping campaigns need a ShoppingSetting. ShoppingSetting shoppingSetting = new ShoppingSetting { salesCountry = "US", campaignPriority = 0, merchantId = merchantId, // Set to "true" to enable Local Inventory Ads in your campaign. enableLocal = true }; campaign.settings = new Setting[] { shoppingSetting }; // Create operation. CampaignOperation campaignOperation = new CampaignOperation { operand = campaign, @operator = Operator.ADD }; // Make the mutate request. CampaignReturnValue retval = campaignService.mutate(new CampaignOperation[] { campaignOperation }); return retval.value[0]; } } } }
Add a Smart Shopping campaign
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.AdWords.Lib; using Google.Api.Ads.AdWords.Util.Shopping.v201809; using Google.Api.Ads.AdWords.v201809; using System; using System.Collections.Generic; namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809 { /// <summary> /// This code example adds a Smart Shopping campaign with an ad group and ad group ad. /// </summary> public class AddSmartShoppingAd : ExampleBase { /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example adds a Smart Shopping campaign with an ad group and " + "ad group ad."; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { AddSmartShoppingAd codeExample = new AddSmartShoppingAd(); Console.WriteLine(codeExample.Description); try { long merchantId = long.Parse("INSERT_MERCHANT_ID_HERE"); bool createDefaultPartition = false; codeExample.Run(new AdWordsUser(), merchantId, createDefaultPartition); } catch (Exception e) { Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(e)); } } /// <summary> /// Runs the code example. /// </summary> /// <param name="user">The Google Ads user.</param> /// <param name="merchantId">The Merchant Center ID for the new campaign.</param> /// <param name="createDefaultPartition">If <c>true</c>, a default product partition for /// all products will be created.</param> public void Run(AdWordsUser user, long merchantId, bool createDefaultPartition) { Budget budget = CreateBudget(user); Campaign campaign = CreateSmartShoppingCampaign(user, budget.budgetId, merchantId); AdGroup adGroup = CreateSmartShoppingAdGroup(user, campaign.id); CreateSmartShoppingAd(user, adGroup.id); if (createDefaultPartition) { CreateDefaultPartition(user, adGroup.id); } } /// <summary> /// Creates a non-shared budget for a Smart Shopping campaign. Smart Shopping campaigns /// support only non-shared budgets. /// </summary> /// <param name="user">The Google Ads user.</param> /// <returns>The newly created budget.</returns> private Budget CreateBudget(AdWordsUser user) { using (BudgetService budgetService = (BudgetService) user.GetService(AdWordsService.v201809.BudgetService)) { // Create a budget. Budget budget = new Budget() { name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(), amount = new Money() { // This budget equals 50.00 units of your account's currency, e.g., // 50 USD if your currency is USD. microAmount = 50_000_000L }, deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD, // Non-shared budgets are required for Smart Shopping campaigns. isExplicitlyShared = false }; // Create operation. BudgetOperation budgetOperation = new BudgetOperation() { operand = budget, @operator = Operator.ADD }; // Add the budget. Budget newBudget = budgetService.mutate( new BudgetOperation[] { budgetOperation }).value[0]; Console.WriteLine($"Budget with name '{newBudget.name}' and ID " + $"{newBudget.budgetId} was added."); return newBudget; } } /// <summary> /// Creates a Smart Shopping campaign. /// </summary> /// <param name="user">The Google Ads user.</param> /// <param name="budgetId">The budget ID.</param> /// <param name="merchantId">The merchant center account ID.</param> /// <returns>The newly created campaign.</returns> private Campaign CreateSmartShoppingCampaign(AdWordsUser user, long budgetId, long merchantId) { using (CampaignService campaignService = (CampaignService) user.GetService(AdWordsService.v201809.CampaignService)) { // Create a campaign with required and optional settings. Campaign campaign = new Campaign() { name = "Smart Shopping campaign #" + ExampleUtilities.GetRandomString(), // The advertisingChannelType is what makes this a Shopping campaign. advertisingChannelType = AdvertisingChannelType.SHOPPING, // Sets the advertisingChannelSubType to SHOPPING_GOAL_OPTIMIZED_ADS to // make this a Smart Shopping campaign. advertisingChannelSubType = AdvertisingChannelSubType.SHOPPING_GOAL_OPTIMIZED_ADS, // Recommendation: Set the campaign to PAUSED when creating it to stop // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve. status = CampaignStatus.PAUSED, // Set a budget. budget = new Budget() { budgetId = budgetId }, // Set bidding strategy. Only MAXIMIZE_CONVERSION_VALUE is supported. biddingStrategyConfiguration = new BiddingStrategyConfiguration() { biddingStrategyType = BiddingStrategyType.MAXIMIZE_CONVERSION_VALUE }, // All Shopping campaigns need a ShoppingSetting. settings = new Setting[] { new ShoppingSetting() { salesCountry = "US", merchantId = merchantId } } }; // Create operation. CampaignOperation campaignOperation = new CampaignOperation() { operand = campaign, @operator = Operator.ADD }; // Make the mutate request and retrieve the result. Campaign newCampaign = campaignService.mutate(new CampaignOperation[] { campaignOperation }).value[0]; // Display result. Console.WriteLine($"Smart Shopping campaign with name '{newCampaign.name}' and " + $"ID {newCampaign.id} was added."); return newCampaign; } } /// <summary> /// Creates a Smart Shopping ad group by setting the ad group type to /// SHOPPING_GOAL_OPTIMIZED_ADS. /// </summary> /// <param name="user">The Google Ads user.</param> /// <param name="campaignId">The campaign ID.</param> private AdGroup CreateSmartShoppingAdGroup(AdWordsUser user, long campaignId) { using (AdGroupService adGroupService = (AdGroupService) user.GetService(AdWordsService.v201809.AdGroupService)) { // Create ad group. AdGroup adGroup = new AdGroup() { campaignId = campaignId, name = "Smart Shopping ad group #" + ExampleUtilities.GetRandomString(), // Set the ad group type to SHOPPING_GOAL_OPTIMIZED_ADS. adGroupType = AdGroupType.SHOPPING_GOAL_OPTIMIZED_ADS }; // Create operation. AdGroupOperation adGroupOperation = new AdGroupOperation() { operand = adGroup, @operator = Operator.ADD }; // Make the mutate request. AdGroup newAdGroup = adGroupService.mutate(new AdGroupOperation[] { adGroupOperation }).value[0]; // Display result. Console.WriteLine($"Smart Shopping ad group with name '{adGroup.name}' and " + $"ID {adGroup.id} was added."); return newAdGroup; } } /// <summary> /// Creates the smart shopping ad. /// </summary> /// <param name="user">The Google Ads user.</param> /// <param name="adGroupId">The ad group ID.</param> private void CreateSmartShoppingAd(AdWordsUser user, long adGroupId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService(AdWordsService.v201809.AdGroupAdService)) { // Create ad group ad. AdGroupAd adGroupAd = new AdGroupAd() { adGroupId = adGroupId, // Create a Smart Shopping ad (Goal-optimized Shopping ad). ad = new GoalOptimizedShoppingAd() { } }; // Create operation. AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation() { operand = adGroupAd, @operator = Operator.ADD }; // Make the mutate request. AdGroupAd newAdGroupAd = adGroupAdService.mutate( new AdGroupAdOperation[] { adGroupAdOperation }).value[0]; // Display result. Console.WriteLine($"Smart Shopping ad with ID {newAdGroupAd.ad.id} was added."); } } /// <summary> /// Creates the default partition. /// </summary> /// <param name="user">The user.</param> /// <param name="adGroupId">The ad group ID.</param> private void CreateDefaultPartition(AdWordsUser user, long adGroupId) { // Create an ad group criterion for 'All products' using the ProductPartitionTree // utility. ProductPartitionTree productPartitionTree = ProductPartitionTree.CreateAdGroupTree(adGroupId, new List<AdGroupCriterion>()); AdGroupCriterionOperation[] mutateOperations = productPartitionTree.GetMutateOperations(); using (AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService) user.GetService( AdWordsService.v201809.AdGroupCriterionService)) { AdGroupCriterionReturnValue adGroupCriterionResult = adGroupCriterionService.mutate(mutateOperations); // Display result. foreach (AdGroupCriterion adGroupCriterion in adGroupCriterionResult.value) { Console.WriteLine( $"Ad group criterion with ID {adGroupCriterion.criterion.id} in ad " + $"group with ID {adGroupCriterion.adGroupId} was added."); } } } } }
Get the set of product bidding categories
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.AdWords.Lib; using Google.Api.Ads.AdWords.v201809; using System; using System.Collections.Generic; namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809 { /// <summary> /// This code example fetches the set of valid ProductBiddingCategories. /// </summary> public class GetProductCategoryTaxonomy : ExampleBase { /// <summary> /// Stores details about a product category and its hierarchy. /// </summary> private class ProductCategory { /// <summary> /// The product category id. /// </summary> private long id; /// <summary> /// The product category name. /// </summary> private string name; /// <summary> /// The product category children. /// </summary> private List<ProductCategory> children = new List<ProductCategory>(); /// <summary> /// Gets or sets the product category id. /// </summary> public long Id { get { return id; } set { id = value; } } /// <summary> /// Gets or sets the product category name. /// </summary> public string Name { get { return name; } set { name = value; } } /// <summary> /// Gets or sets the product category children. /// </summary> public List<ProductCategory> Children { get { return children; } } } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example fetches the set of valid ProductBiddingCategories."; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { GetProductCategoryTaxonomy codeExample = new GetProductCategoryTaxonomy(); Console.WriteLine(codeExample.Description); try { codeExample.Run(new AdWordsUser()); } catch (Exception e) { Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(e)); } } /// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { using (ConstantDataService constantDataService = (ConstantDataService) user.GetService(AdWordsService.v201809.ConstantDataService)) { Selector selector = new Selector() { predicates = new Predicate[] { Predicate.In(ProductBiddingCategoryData.Fields.Country, new string[] { "US" }) } }; try { ProductBiddingCategoryData[] results = constantDataService.getProductBiddingCategoryData(selector); Dictionary<long, ProductCategory> biddingCategories = new Dictionary<long, ProductCategory>(); List<ProductCategory> rootCategories = new List<ProductCategory>(); foreach (ProductBiddingCategoryData productBiddingCategory in results) { long id = productBiddingCategory.dimensionValue.value; long parentId = 0; string name = productBiddingCategory.displayValue[0].value; if (productBiddingCategory.parentDimensionValue != null) { parentId = productBiddingCategory.parentDimensionValue.value; } if (!biddingCategories.ContainsKey(id)) { biddingCategories.Add(id, new ProductCategory()); } ProductCategory category = biddingCategories[id]; if (parentId != 0) { if (!biddingCategories.ContainsKey(parentId)) { biddingCategories.Add(parentId, new ProductCategory()); } ProductCategory parent = biddingCategories[parentId]; parent.Children.Add(category); } else { rootCategories.Add(category); } category.Id = id; category.Name = name; } DisplayProductCategories(rootCategories, ""); } catch (Exception e) { throw new System.ApplicationException( "Failed to set shopping product category.", e); } } } /// <summary> /// Displays the product categories. /// </summary> /// <param name="categories">The product categories.</param> /// <param name="prefix">The prefix for display purposes.</param> private void DisplayProductCategories(List<ProductCategory> categories, string prefix) { foreach (ProductCategory category in categories) { Console.WriteLine("{0}{1} [{2}]", prefix, category.Name, category.Id); DisplayProductCategories(category.Children, string.Format("{0}{1} > ", prefix, category.Name)); } } } }