Shopping Campaign Samples

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 Shopping campaign for Showcase ads

// 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 Google.Api.Ads.Common.Util;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
    /// <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)
        {
            using (CampaignService campaignService =
                (CampaignService) user.GetService(AdWordsService.v201809.CampaignService))
            {
                // Create the 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
                    {
                        // Note: Showcase ads require that the campaign has a ManualCpc
                        // 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];
            }
        }

        /// <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)
        {
            using (AdGroupService adGroupService =
                (AdGroupService) user.GetService(AdWordsService.v201809.AdGroupService))
            {
                // Create ad group.
                AdGroup adGroup = new AdGroup
                {
                    campaignId = campaign.id,
                    name = "Ad Group #" + ExampleUtilities.GetRandomString(),

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

                // Required: Set the ad group's bidding strategy configuration.
                BiddingStrategyConfiguration biddingConfiguration = new BiddingStrategyConfiguration
                {
                    // Optional: Set the bids.
                    bids = new Bids[]
                    {
                        new CpcBid()
                        {
                            bid = new Money()
                            {
                                microAmount = 100000
                            }
                        }
                    }
                };

                adGroup.biddingStrategyConfiguration = biddingConfiguration;

                // Create the 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 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)
        {
            using (AdGroupAdService adGroupAdService =
                (AdGroupAdService) user.GetService(AdWordsService.v201809.AdGroupAdService))
            {
                // Create the Showcase ad.
                ShowcaseAd showcaseAd = new ShowcaseAd
                {
                    // Required: set the ad's name, final URLs and display URL.
                    name = "Showcase ad " + ExampleUtilities.GetShortRandomString(),
                    finalUrls = new string[]
                    {
                        "http://example.com/showcase"
                    },
                    displayUrl = "example.com"
                };

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

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

                // Create ad group ad.
                AdGroupAd adGroupAd = new AdGroupAd
                {
                    adGroupId = adGroup.id,
                    ad = showcaseAd
                };

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

        /// <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)
        {
            using (MediaService mediaService =
                (MediaService) user.GetService(AdWordsService.v201809.MediaService))
            {
                // Create the image.
                Image image = new Image
                {
                    data = MediaUtilities.GetAssetDataFromUrl(url, user.Config),
                    type = MediaMediaType.IMAGE
                };

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

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

Send feedback about...

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