Shopping Campaign Samples

The code samples below provide examples for managing Shopping campaigns using the AdWords API. Client Library.

Add product partition tree

// Copyright 2017, Google Inc. All Rights Reserved.
//
// 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.v201705;
using Google.Api.Ads.AdWords.v201705;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201705 {

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

Add product scope

// Copyright 2017, Google Inc. All Rights Reserved.
//
// 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.v201705;

using System;
using System.Collections.Generic;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201705 {

  /// <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) {
      // Get the CampaignCriterionService.
      CampaignCriterionService campaignCriterionService =
          (CampaignCriterionService) user.GetService(
              AdWordsService.v201705.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();
      nexusBrand.value = "Nexus";

      ProductCanonicalCondition newProducts = new ProductCanonicalCondition();
      newProducts.condition = ProductCanonicalConditionCondition.NEW;

      ProductCustomAttribute customAttribute = new ProductCustomAttribute();
      customAttribute.type = ProductDimensionType.CUSTOM_ATTRIBUTE_0;
      customAttribute.value = "my attribute value";

      ProductOfferId bookOffer = new ProductOfferId();
      bookOffer.value = "book1";

      ProductType mediaProducts = new ProductType();
      mediaProducts.type = ProductDimensionType.PRODUCT_TYPE_L1;
      mediaProducts.value = "Media";

      ProductType bookProducts = new ProductType();
      bookProducts.type = ProductDimensionType.PRODUCT_TYPE_L2;
      bookProducts.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();
      luggageBiddingCategory.type = ProductDimensionType.BIDDING_CATEGORY_L1;
      luggageBiddingCategory.value = -5914235892932915235;

      productScope.dimensions = new ProductDimension[] {nexusBrand, newProducts, bookOffer,
          mediaProducts, luggageBiddingCategory};

      CampaignCriterion campaignCriterion = new CampaignCriterion();
      campaignCriterion.campaignId = campaignId;
      campaignCriterion.criterion = productScope;

      // Create operation.
      CampaignCriterionOperation operation = new CampaignCriterionOperation();
      operation.operand = campaignCriterion;
      operation.@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 Shopping campaign

// Copyright 2017, Google Inc. All Rights Reserved.
//
// 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.v201705;
using Google.Api.Ads.AdWords.v201705;

using System;
using System.Collections.Generic;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201705 {

  /// <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) {
      // Get the required services.
      CampaignService campaignService = (CampaignService) user.GetService(
          AdWordsService.v201705.CampaignService);
      AdGroupService adGroupService = (AdGroupService) user.GetService(
          AdWordsService.v201705.AdGroupService);
      AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService(
          AdWordsService.v201705.AdGroupAdService);

      try {
        Campaign campaign = CreateCampaign(budgetId, merchantId, campaignService);
        Console.WriteLine("Campaign with name '{0}' and ID '{1}' was added.", campaign.name,
              campaign.id);

        AdGroup adGroup = CreateAdGroup(adGroupService, campaign);
        Console.WriteLine("Ad group with name '{0}' and ID '{1}' was added.", adGroup.name,
              adGroup.id);

        AdGroupAd adGroupAd = CreateProductAd(adGroupAdService, adGroup);
        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>
    void CreateDefaultPartitionTree(AdWordsUser user, long adGroupId) {
      // Get the AdGroupCriterionService.
      AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(
              AdWordsService.v201705.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="adGroupAdService">The AdGroupAdService instance.</param>
    /// <param name="adGroup">The ad group.</param>
    /// <returns>The Product Ad.</returns>
    private static AdGroupAd CreateProductAd(AdGroupAdService adGroupAdService, AdGroup adGroup) {
      // Create product ad.
      ProductAd productAd = new ProductAd();

      // Create ad group ad.
      AdGroupAd adGroupAd = new AdGroupAd();
      adGroupAd.adGroupId = adGroup.id;
      adGroupAd.ad = productAd;

      // Create operation.
      AdGroupAdOperation operation = new AdGroupAdOperation();
      operation.operand = adGroupAd;
      operation.@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="adGroupService">The AdGroupService instance.</param>
    /// <param name="campaign">The Shopping campaign.</param>
    /// <returns>The ad group.</returns>
    private static AdGroup CreateAdGroup(AdGroupService adGroupService, Campaign campaign) {
      // Create ad group.
      AdGroup adGroup = new AdGroup();
      adGroup.campaignId = campaign.id;
      adGroup.name = "Ad Group #" + ExampleUtilities.GetRandomString();

      // Create operation.
      AdGroupOperation operation = new AdGroupOperation();
      operation.operand = adGroup;
      operation.@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="budgetId">The budget id.</param>
    /// <param name="merchantId">The Merchant Center id.</param>
    /// <param name="campaignService">The CampaignService instance.</param>
    /// <returns>The Shopping campaign.</returns>
    private static Campaign CreateCampaign(long budgetId, long merchantId,
        CampaignService campaignService) {
      // Create campaign.
      Campaign campaign = new Campaign();
      campaign.name = "Shopping campaign #" + ExampleUtilities.GetRandomString();

      // The advertisingChannelType is what makes this a Shopping campaign.
      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.
      campaign.status = CampaignStatus.PAUSED;

      // Set shared budget (required).
      campaign.budget = new Budget();
      campaign.budget.budgetId = budgetId;

      // Set bidding strategy (required).
      BiddingStrategyConfiguration biddingStrategyConfiguration =
          new BiddingStrategyConfiguration();
      biddingStrategyConfiguration.biddingStrategyType = BiddingStrategyType.MANUAL_CPC;

      campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;

      // All Shopping campaigns need a ShoppingSetting.
      ShoppingSetting shoppingSetting = new ShoppingSetting();
      shoppingSetting.salesCountry = "US";
      shoppingSetting.campaignPriority = 0;
      shoppingSetting.merchantId = merchantId;

      // Set to "true" to enable Local Inventory Ads in your campaign.
      shoppingSetting.enableLocal = true;
      campaign.settings = new Setting[] { shoppingSetting };

      // Create operation.
      CampaignOperation campaignOperation = new CampaignOperation();
      campaignOperation.operand = campaign;
      campaignOperation.@operator = Operator.ADD;

      // Make the mutate request.
      CampaignReturnValue retval = campaignService.mutate(
          new CampaignOperation[] { campaignOperation });

      return retval.value[0];
    }
  }
}

Add campaign for Showcase Shopping ads

// Copyright 2017, Google Inc. All Rights Reserved.
//
// 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.v201705;
using Google.Api.Ads.AdWords.v201705;
using Google.Api.Ads.Common.Util;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201705 {

  /// <summary>
  /// This code example adds a Shopping campaign for Showcase ads.
  /// </summary>
  public class AddShoppingCampaignForShowcaseAds : ExampleBase {

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example adds a Shopping campaign for Showcase ads.";
      }
    }

    /// <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) {
      AddShoppingCampaignForShowcaseAds codeExample = new AddShoppingCampaignForShowcaseAds();
      Console.WriteLine(codeExample.Description);
      try {
        long budgetId = long.Parse("INSERT_BUDGET_ID_HERE");
        long merchantId = long.Parse("INSERT_MERCHANT_ID_HERE");
        codeExample.Run(new AdWordsUser(), budgetId, merchantId);
      } 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>
    public void Run(AdWordsUser user, long budgetId, long merchantId) {
      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);
        Console.WriteLine("Ad group with name '{0}' and ID '{1}' was added.", adGroup.name,
            adGroup.id);

        AdGroupAd adGroupAd = CreateShowcaseAd(user, adGroup);
        Console.WriteLine("Showcase ad with ID '{0}' was added.", adGroupAd.ad.id);

        ProductPartitionTree partitionTree = CreateProductPartition(user, adGroup.id);
        Console.WriteLine("Final tree: {0}", partitionTree);
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to create shopping campaign for " +
            "showcase ads.", e);
      }
    }

    /// <summary>
    /// Creates the Shopping campaign.
    /// </summary>
    /// <param name="user">The AdWords user for which the campaign is created.</param>
    /// <param name="budgetId">The budget ID.</param>
    /// <param name="merchantId">The Merchant Center ID.</param>
    /// <returns>The newly created Shopping campaign.</returns>
    private static Campaign CreateCampaign(AdWordsUser user, long budgetId, long merchantId) {
      CampaignService campaignService = (CampaignService) user.GetService(
          AdWordsService.v201705.CampaignService);
      // Create the campaign.
      Campaign campaign = new Campaign();
      campaign.name = "Shopping campaign #" + ExampleUtilities.GetRandomString();

      // The advertisingChannelType is what makes this a Shopping campaign.
      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.
      campaign.status = CampaignStatus.PAUSED;

      // Set shared budget (required).
      campaign.budget = new Budget();
      campaign.budget.budgetId = budgetId;

      // Set bidding strategy (required).
      BiddingStrategyConfiguration biddingStrategyConfiguration =
          new BiddingStrategyConfiguration();

      // Showcase ads require either ManualCpc or EnhancedCpc.
      biddingStrategyConfiguration.biddingStrategyType = BiddingStrategyType.MANUAL_CPC;

      campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;

      // All Shopping campaigns need a ShoppingSetting.
      ShoppingSetting shoppingSetting = new ShoppingSetting();
      shoppingSetting.salesCountry = "US";
      shoppingSetting.campaignPriority = 0;
      shoppingSetting.merchantId = merchantId;

      // Set to "true" to enable Local Inventory Ads in your campaign.
      shoppingSetting.enableLocal = true;
      campaign.settings = new Setting[] { shoppingSetting };

      // Create operation.
      CampaignOperation campaignOperation = new CampaignOperation();
      campaignOperation.operand = campaign;
      campaignOperation.@operator = Operator.ADD;

      // Make the mutate request.
      CampaignReturnValue retval = campaignService.mutate(
          new CampaignOperation[] { campaignOperation });

      return retval.value[0];
    }

    /// <summary>
    /// Creates the ad group in a Shopping campaign.
    /// </summary>
    /// <param name="user">The AdWords user for which the ad group is created.</param>
    /// <param name="campaign">The Shopping campaign.</param>
    /// <returns>The newly created ad group.</returns>
    private static AdGroup CreateAdGroup(AdWordsUser user, Campaign campaign) {
      AdGroupService adGroupService = (AdGroupService) user.GetService(
        AdWordsService.v201705.AdGroupService);
      // Create ad group.
      AdGroup adGroup = new AdGroup();
      adGroup.campaignId = campaign.id;
      adGroup.name = "Ad Group #" + ExampleUtilities.GetRandomString();

      // Required: Set the ad group type to SHOPPING_SHOWCASE_ADS.
      adGroup.adGroupType = AdGroupType.SHOPPING_SHOWCASE_ADS;

      // Required: Set the ad group's bidding strategy configuration.
      BiddingStrategyConfiguration biddingConfiguration = new BiddingStrategyConfiguration();

      // Optional: Set the bids.
      biddingConfiguration.bids = new Bids[] {
        new CpcBid() {
          bid = new Money() {
            microAmount = 100000
          }
        }
      };

      adGroup.biddingStrategyConfiguration = biddingConfiguration;

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

      // Make the mutate request.
      AdGroupReturnValue retval = adGroupService.mutate(new AdGroupOperation[] { operation });
      return retval.value[0];
    }

    /// <summary>
    /// Creates the Showcase ad.
    /// </summary>
    /// <param name="user">The AdWords user for which the ad is created.</param>
    /// <param name="adGroup">The ad group in which the ad is created.</param>
    /// <returns>The newly created Showcase ad.</returns>
    private static AdGroupAd CreateShowcaseAd(AdWordsUser user, AdGroup adGroup) {
      AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService(
        AdWordsService.v201705.AdGroupAdService);
      // Create the Showcase ad.
      ShowcaseAd showcaseAd = new ShowcaseAd();

      // Required: set the ad's name, final URLs and display URL.
      showcaseAd.name = "Showcase ad " + ExampleUtilities.GetShortRandomString();
      showcaseAd.finalUrls = new string[] { "http://example.com/showcase" };
      showcaseAd.displayUrl = "example.com";

      // Required: Set the ad's expanded image.
      Image expandedImage = new Image();
      expandedImage.mediaId = UploadImage(user, "https://goo.gl/IfVlpF");
      showcaseAd.expandedImage = expandedImage;

      // Optional: Set the collapsed image.
      Image collapsedImage = new Image();
      collapsedImage.mediaId = UploadImage(user, "https://goo.gl/NqTxAE");
      showcaseAd.collapsedImage = collapsedImage;

      // Create ad group ad.
      AdGroupAd adGroupAd = new AdGroupAd();
      adGroupAd.adGroupId = adGroup.id;
      adGroupAd.ad = showcaseAd;

      // Create operation.
      AdGroupAdOperation operation = new AdGroupAdOperation();
      operation.operand = adGroupAd;
      operation.@operator = Operator.ADD;

      // Make the mutate request.
      AdGroupAdReturnValue retval = adGroupAdService.mutate(
        new AdGroupAdOperation[] { operation });

      return retval.value[0];
    }

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

    /// <summary>
    /// Uploads an image.
    /// </summary>
    /// <param name="user">The AdWords user for which the image is uploaded.</param>
    /// <param name="url">The image URL.</param>
    /// <returns>The uploaded image.</returns>
    private static long UploadImage(AdWordsUser user, string url) {
      MediaService mediaService = (MediaService) user.GetService(
        AdWordsService.v201705.MediaService);

      // Create the image.
      Image image = new Image();
      image.data = MediaUtilities.GetAssetDataFromUrl(url);
      image.type = MediaMediaType.IMAGE;

      // Upload the image.
      Media[] result = mediaService.upload(new Media[] { image });
      return result[0].mediaId;
    }
  }
}

Get product category taxonomy

// Copyright 2017, Google Inc. All Rights Reserved.
//
// 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.v201705;

using System;
using System.Collections.Generic;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201705 {

  /// <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>
    class ProductCategory {
      /// <summary>
      /// The product category id.
      /// </summary>
      long id;

      /// <summary>
      /// The product category name.
      /// </summary>
      string name;

      /// <summary>
      /// The product category children.
      /// </summary>
      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) {
      // Get the ConstantDataService.
      ConstantDataService constantDataService = (ConstantDataService) user.GetService(
          AdWordsService.v201705.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>
    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));
      }
    }
  }
}

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.