Export (0) Print
Expand All

Product Ads in C#

The following example shows how to add a product extension and associate it with a campaign, add product criterion to an ad group, get and update the criterion, and add promotional text to product ads.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

// BingAds.CampaignManagement is the application-defined namespace of 
// the service reference used for this example. 

using ProductAds.BingAds.CampaignManagement;

namespace ProductAds
{
    class Program
    {
        private static CampaignManagementServiceClient service = null;

        // Specify your credentials.

        private static string m_password = "<passwordgoeshere>";
        private static string m_username = "<usernamegoeshere>";
        private static string m_token = "<devtokengoeshere>";

        // Specify the advertiser's account.

        private static long m_accountId = <accountidgoeshere>;
        private static long m_customerId = <customeridgoeshere>;

        // Specify the campaign and ad group to add the product criterions to.

        private static long m_campaignId = <campaignidgoeshere>;
        private static long m_adGroupId = <adgroupidgoeshere>;


        static void Main(string[] args)
        {
            long[] adExtensionIds = null;
            long[] productAdIds = null;
            long[] criterionIds = null;
            AdGroupCriterion[] criterions = null;

            try
            {
                service = new CampaignManagementServiceClient();

                // Create the product extension and associate it with a campaign.

                adExtensionIds = AddProductExtensions(m_customerId, m_accountId);
                AssociateExtensionsWithCampaign(m_accountId, m_campaignId, adExtensionIds[0]);

                // Create a product criterion for the ad group.

                criterionIds = AddProductCriterions(m_accountId, m_adGroupId);
                criterions = GetAdGroupCriterions(m_accountId, criterionIds);
                PrintAdGroupCriterions(criterionIds, criterions);

                // Provide the promotional text that gets added to product ads.

                productAdIds = AddPromotionalText(m_accountId, m_adGroupId);

                // Update the product criterion.

                criterions = GetAdGroupCriterions(m_accountId, m_adGroupId);
                UpdateProductCriterion(m_accountId, criterions);
                criterions = GetAdGroupCriterions(m_accountId, m_adGroupId);
                PrintAdGroupCriterions(criterionIds, criterions);

                service.Close();
                service = null;
            }
            catch (CommunicationException e)
            {
                Console.WriteLine(e.Message);

                if (null != e.InnerException)
                {
                    Console.WriteLine("\n" + e.InnerException.Message);
                }
            }
            catch (TimeoutException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (Exception e)
            {
                // Ignore fault exceptions that we already caught.

                if (e.InnerException is FaultException)
                {
                    ;
                }
                else
                {
                    Console.WriteLine(e.Message);
                }
            }
            finally
            {
                if (service != null)
                {
                    service.Abort();
                }
            }
        }

        // Adds a product ad extension to the account's ad extension library.
        // The extension is used to associate a campaign with the customer's
        // Bing Merchant Center (BMC) store. 

        static long[] AddProductExtensions(long customerId, long accountId)
        {
            AddAdExtensionsRequest request = new AddAdExtensionsRequest();
            AddAdExtensionsResponse response = null;
            long[] ids = null;

            // Specify the extensions.

            AdExtension2[] extensions = new AdExtension2[] {
                new ProductAdExtension {
                    Name = "Basketball Shoes",
                    StoreId = <storeidgoeshere>,  // Customer's BMC store ID
                    StoreName = null, // Read-only, must be null

                    // Optional filter that identifies the products in the store
                    // to advertise. The product is selected if it meets the conditions 
                    // in collection 1 OR the conditions in collection 2, and so on.
                    // If null (no conditions are specified), Bing
                    // can create product ads for all products in the store.
                    // If the product criterion specifies a filter, the product
                    // must also meet the conditions of the criterion filter.

                    ProductSelection = new ProductConditionCollection[] {
                        new ProductConditionCollection {
                            Conditions = new ProductCondition[] {
                                new ProductCondition {
                                    Operand = "ProductType",
                                    Attribute = "Apparel > Shoes > Basketball > Mens"
                                },
                                new ProductCondition {
                                    Operand = "Brand",
                                    Attribute = "Speedy Speedsters"
                                }
                            }
                        },
                        new ProductConditionCollection {
                            Conditions = new ProductCondition[] {
                                new ProductCondition {
                                    Operand = "ProductType",
                                    Attribute = "Apparel > Shoes > Basketball > Boys"
                                },
                                new ProductCondition {
                                    Operand = "Brand",
                                    Attribute = "Speedy Speedsters"
                                }
                            }
                        }
                    }
                }
            };

            // Set the header information.

            request.CustomerId = customerId.ToString(); 
            request.CustomerAccountId = accountId.ToString();
            request.DeveloperToken = m_token;
            request.UserName = m_username;
            request.Password = m_password;

            // Set the request information.

            request.AccountId = accountId;
            request.AdExtensions = extensions;

            try
            {
                response = service.AddAdExtensions(request);

                ids = new long[response.AdExtensionIdentities.Length];

                for (int i = 0; i < response.AdExtensionIdentities.Length; i++)
                {
                    ids[i] = response.AdExtensionIdentities[i].Id;
                }
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("AddAdExtensions failed with the following faults:\n");

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    if (105 == error.Code) //  InvalidCredentials
                    {
                        Console.WriteLine("The specified credentials are not valid " +
                            "or the account is inactive.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                            error.ErrorCode, error.Code, error.Message, error.Detail);
                    }
                }

                throw new Exception("", fault);
            }
            catch (FaultException<ApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("AddAdExtensions failed with the following faults:\n");

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    switch (error.Code)
                    {
                        case 106: //  UserIsNotAuthorized
                            Console.WriteLine("The user is not authorized to call this operation.");
                            break;

                        case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                            Console.WriteLine("The CustomerAccountId header element " +
                                "cannot be null or empty.");
                            break;

                        case 3862: // CampaignServiceLocationAdExtensionsEntityLimitExceeded
                            Console.WriteLine("The number of location ad extensions in the " +
                                "ad extensions list exceeds the maximum allowed.\n");
                            break;

                        default:
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                // This list of errors codes is just a sampling of the possible errors that 
                // AddAdExtensions can throw.

                // Note that the Details element of BatchErrors contains the zero-based
                // index of the product collection that caused the error.

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {

                        case 3863: // CampaignServiceProductAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To add product extensions, the customer " +
                                "must be a member of the Product Ad pilot program.\n");
                            break;

                        case 3864: // CampaignServiceProductAdExtensionTooManyProductConditionCollections
                            Console.WriteLine("Failed to add product extension #{0}. The " +
                                "list of product condition collections is too long.\n",
                                error.Index);
                            break;

                        case 3865: // CampaignServiceProductAdExtensionTooManyConditions
                            Console.WriteLine("Failed to add product extension #{0}. Product " +
                                "condition collection #{1} contains too many conditions.\n",
                                error.Index,
                                error.Details);
                            break;

                        case 3866: // CampaignServiceProductAdExtensionInvalidStoreId
                            Console.WriteLine("Failed to add product extension #{0}. The store " +
                                "ID is not valid.\n",
                                error.Index);
                            break;

                        case 3867: // CampaignServiceProductAdExtensionProductConditionsArrayIsNullOrEmpty
                            Console.WriteLine("Failed to add product extension #{0}. Product " +
                                "condition collection #{1} cannot be null or empty.\n",
                                error.Index,
                                error.Details);
                            break;

                        case 3869: // CampaignServiceProductAdExtensionOperandIsInvalid
                            Console.WriteLine("Failed to add product extension #{0}. One of the " +
                                "operands in product condition collection #{1} is not valid.\n",
                                error.Index,
                                error.Details);
                            break;

                        case 3870: // CampaignServiceProductAdExtensionAttributeIsInvalid
                            Console.WriteLine("Failed to add product extension #{0}. One of the " +
                                "attributes in product condition collection #{1} is not valid.\n",
                                error.Index,
                                error.Details);
                            break;

                        case 4116: // CampaignServiceProductConditionAttributeNullOrEmpty
                            Console.WriteLine("Failed to add product extension #{0}. The attributes " +
                                "in product condition collection #{1} cannot be null or empty.\n",
                                error.Index,
                                error.Details);
                            break;

                        default:
                            Console.WriteLine("Unable to add extension #{0}", error.Index);
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                throw new Exception("", fault);
            }

            return ids;
        }

        // Associates the product extension with a campaign. A campaign can be associated 
        // with only one product extension. 

        static void AssociateExtensionsWithCampaign(long accountId, long campaignId, long extensionId)
        {
            SetAdExtensionsToCampaignsRequest request = new SetAdExtensionsToCampaignsRequest();
            SetAdExtensionsToCampaignsResponse response = null;
            AdExtensionIdToCampaignIdAssociation[] associations = null;

            associations = new[] {
                new AdExtensionIdToCampaignIdAssociation {
                    AdExtensionId = extensionId,
                    CampaignId = campaignId
                }
            };

            // Set the header information.

            request.CustomerAccountId = accountId.ToString();
            request.DeveloperToken = m_token;
            request.UserName = m_username;
            request.Password = m_password;

            // Set the request information.

            request.AccountId = accountId;
            request.AdExtensionIdToCampaignIdAssociations = associations;

            try
            {
                response = service.SetAdExtensionsToCampaigns(request);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("SetAdExtensionsToCampaigns failed with the following faults:\n");

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    if (105 == error.Code) //  InvalidCredentials
                    {
                        Console.WriteLine("The specified credentials are not valid or " +
                            "the account is inactive.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                            error.ErrorCode, error.Code, error.Message, error.Detail);
                    }
                }

                throw new Exception("", fault);
            }
            catch (FaultException<ApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("SetAdExtensionsToCampaigns failed with the following faults:\n");

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    switch (error.Code)
                    {
                        case 106: //  UserIsNotAuthorized
                            Console.WriteLine("The user is not authorized to call " +
                                "this operation.");
                            break;

                        case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                            Console.WriteLine("The CustomerAccountId header element " +
                                "cannot be null or empty.");
                            break;

                        case 1102: //  CampaignServiceInvalidAccountId
                            Console.WriteLine("The account ID is not valid.");
                            break;

                        case 3810: //  CampaignServiceAdExtensionIdToCampaignIdAssociationArrayShouldNotBeN
                            Console.WriteLine("The list of ad extension to campaign " +
                                "associations cannot be null or empty.");
                            break;

                        default:
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {
                        case 1100: //  CampaignServiceInvalidCampaignId
                            Console.WriteLine("The campaign ID specified in ad extension " +
                                "to campaign association #{0} is not valid.",
                                error.Index);
                            break;

                        case 1397: //  CampaignServiceEditorialGenericError
                            Console.WriteLine("The ad extension specified in ad extension " +
                                "to campaign association #{0} failed editorial review. " +
                                "The term that failed review is \"{1}\".",
                                error.Index,
                                error.Details);
                            break;

                        case 3812: //  CampaignServiceInvalidAdExtensionId
                            Console.WriteLine("The ad extension ID specified in ad " +
                                "extension to campaign association #{0} is not valid.",
                                error.Index);
                            break;

                        case 3818: //  CampaignServiceCannotAssignMoreThanOneAdExtensionTypeToAnEntity
                            Console.WriteLine("The campaign specified in ad extension to " +
                                "campaign association #{0} can contain only one extension of " +
                                "the specified type.",
                                error.Index);
                            break;

                        case 3825: //  CampaignServiceDuplicateInAdExtensionIdToCampaignIdAssociations
                            Console.WriteLine("The list of ad extension to campaign " +
                                "associations contains a duplicate ad extension ID " +
                                "for the same campaign. Association #{0} contains the duplicate.",
                                error.Index);
                            break;

                        case 3863: // CampaignServiceProductAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To call this operation, the customer " +
                                "must be a member of the Product Ad pilot program.\n");
                            break;

                        default:
                            Console.WriteLine("Error code: {0} ({1})\nIndex: {2}\nMessage: {3}\nDetail: {4}\n",
                                error.ErrorCode, error.Code, error.Index, error.Message, error.Details);
                            break;
                    }
                }

                throw new Exception("", fault);
            }
        }

        // Adds a ProductAd to the specified ad group. Do not confuse a ProductAd object with
        // a product ad that the delivery engine generates. A ProductAd is optional.
        // Its purpose is to provide promotional text that the delivery engine adds to 
        // the product ads that it generates and to provide a way to get performance-based 
        // reporting (clicks and impressions) for the product ads. 

        static long[] AddPromotionalText(long accountId, long adGroupId)
        {
            AddAdsRequest request = new AddAdsRequest();
            AddAdsResponse response = null;

            // Specify the promotional text to add to the ad group. If your only
            // purpose for adding ProductAd objects is to get reporting, set
            // PromotionalText to null or an empty string.

            Ad[] ads = new[] {
                new ProductAd {
                    PromotionalText = "Free shipping on $99 purchases."
                }
            };

            // Set the header information.

            request.CustomerAccountId = accountId.ToString();
            request.DeveloperToken = m_token;
            request.UserName = m_username;
            request.Password = m_password;

            // Set the request information.

            request.AdGroupId = adGroupId;
            request.Ads = ads;

            try
            {
                response = service.AddAds(request);

                Console.WriteLine("Added product ads with the following IDs.");

                foreach (long id in response.AdIds)
                {
                    Console.WriteLine(id);
                }

                Console.WriteLine();
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("AddAds failed with the following faults:\n");

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    if (105 == error.Code) //  InvalidCredentials
                    {
                        Console.WriteLine("The specified credentials are not valid or the account is inactive.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                            error.ErrorCode, error.Code, error.Message, error.Detail);
                    }
                }

                throw new Exception("", fault);
            }
            catch (FaultException<EditorialApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("AddAds failed with the following faults:\n");

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    switch (error.Code)
                    {
                        case 106: //  UserIsNotAuthorized
                            Console.WriteLine("The user is not authorized to call this operation.");
                            break;

                        case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                            Console.WriteLine("The CustomerAccountId header element cannot be null or empty.");
                            break;

                        default:
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {
                        case 1313: // CampaignServiceDuplicateAd
                            Console.WriteLine("Product ad #{0} is a duplicate of another product ad in the list.\n",
                                error.Index);
                            break;

                        case 1366: // CampaignServiceAdTypeInvalidForCustomer
                            Console.WriteLine("To add product ads, the customer " +
                                "must be a member of the Product Ad pilot program.\n");
                            break;

                        case 1398: // CampaignServiceProductAdPromotionalTextTooLong
                            Console.WriteLine("The promotional text of ad #{0} is too long.\n",
                                error.Index);
                            break;

                        default:
                            Console.WriteLine("Unable to add ad #{0}", error.Index);
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                foreach (EditorialError error in fault.Detail.EditorialErrors)
                {
                    switch (error.Code)
                    {
                        default:
                            Console.WriteLine("Unable to add ad #{0}", error.Index);
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}",
                                error.ErrorCode, error.Code, error.Message);
                            Console.WriteLine("Disapproved test: {0}\nAppealable: ({1})\nPublisher country: {2}",
                                error.DisapprovedText, error.Appealable, error.PublisherCountry);
                            break;
                    }
                }

                throw new Exception("", fault);
            }

            return response.AdIds;
        }

        // Add the product criterions to the ad group. A criterion specifies a
        // bid value and optional product conditions filter. 

        static long[] AddProductCriterions(long accountId, long adGroupId)
        {
            AddAdGroupCriterionsRequest request = new AddAdGroupCriterionsRequest();
            AddAdGroupCriterionsResponse response = null;

            // Specify the product criterions. The product ad gets served if the product
            // matches the criterion's filter AND the product ad extension filter.

            AdGroupCriterion[] criteria = new AdGroupCriterion[] {
                new BiddableAdGroupCriterion {
                    AdGroupId = adGroupId,
                    DestinationUrl = null,  // Overrides the product store's destination URL
                    Param1 = null,          // Substitution strings for DestinationUrl
                    Param2 = null,
                    Param3 = null,
                    CriterionBid = new FixedBid { 
                        Bid = new Bid{
                            Amount = 1.05
                        }
                    },
                    Criterion = new Product {
                        Conditions = new ProductCondition [] {
                            new ProductCondition {
                                Operand = "SKU",
                                Attribute = "11EEE"
                            }
                        }
                    }
                },
                new BiddableAdGroupCriterion {
                    AdGroupId = adGroupId,
                    CriterionBid = new FixedBid { 
                        Bid = new Bid{
                            Amount = null  // Default to the ad group's exact-match bid value
                        }
                    },
                    Criterion = new Product {
                        Conditions = new ProductCondition [] {
                            new ProductCondition {
                                Operand = "SKU",
                                Attribute = "12EEE"
                            }
                        }
                    }
                }
            };

            // Set the header information.

            request.CustomerAccountId = accountId.ToString();
            request.DeveloperToken = m_token;
            request.UserName = m_username;
            request.Password = m_password;

            // Set the request information.

            request.AccountId = accountId;
            request.AdGroupCriterions = criteria;

            try
            {
                response = service.AddAdGroupCriterions(request);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("AddAdGroupCriterions failed with the following faults:\n");

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    if (105 == error.Code) //  InvalidCredentials
                    {
                        Console.WriteLine("The specified credentials are not valid or the " +
                            "account is inactive.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                            error.ErrorCode, error.Code, error.Message, error.Detail);
                    }
                }

                throw new Exception("", fault);
            }
            catch (FaultException<ApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("AddAdGroupCriterions failed with the following faults:\n");

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    switch (error.Code)
                    {
                        case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                            Console.WriteLine("The CustomerAccountId header element cannot " +
                                "be null or empty.");
                            break;

                        case 3863: // CampaignServiceProductAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To add ad group criterions, the customer " +
                                "must be a member of the Product Ad pilot program.\n");
                            break;

                        case 4104: // CampaignServiceAdGroupCriterionsNullOrEmpty
                            Console.WriteLine("To list of ad group criterions cannot be null or empty.\n");
                            break;

                        default:
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {
                        case 1515: // CampaignServiceBidAmountsLessThanFloorPrice
                            Console.WriteLine("The bid value of ad group criterion #{0} is " +
                                "less than the minimum allowed bid value.\n",
                                error.Index);
                            break;

                        case 1516: // CampaignServiceBidAmountsGreaterThanCeilingPrice
                            Console.WriteLine("The bid value of ad group criterion #{0} exceeds " +
                                "the maximum allowed bid value.\n",
                                error.Index);
                            break;

                        case 3869: // CampaignServiceProductAdExtensionOperandIsInvalid
                            Console.WriteLine("Product operand #{0} of ad group criterion #{1} " +
                                "is not valid.\n",
                                error.Details,
                                error.Index);
                            break;

                        case 3870: // CampaignServiceProductAdExtensionAttributeIsInvalid
                            Console.WriteLine("Product attribute #{0} of ad group criterion #{1} " +
                                "is not valid.\n",
                                error.Details,
                                error.Index);
                            break;

                        case 3872: // CampaignServiceProductConditionDuplicateOperand
                            Console.WriteLine("Ad group criterion #{1} contains duplicate product operands. " +
                                "Product operand #{0} is a duplicate.\n",
                                error.Details,
                                error.Index);
                            break;

                        case 4108: // CampaignServiceAdGroupCriterionInvalidBidType
                            Console.WriteLine("The bid of ad group criterion #{0} is null or " +
                                "is of the wrong type.\n",
                                error.Index);
                            break;

                        case 4109: // CampaignServiceAdGroupCriterionInvalidBidValue
                            Console.WriteLine("The bid value of ad group criterion #{0} is not valid.\n",
                                error.Index);
                            break;

                        case 4113: // CampaignServiceProductAdGroupCriterionTooManyConditions
                            Console.WriteLine("The list of product conditions of ad group " +
                                "criterion #{0} is too long.\n",
                                error.Index);
                            break;

                        default:
                            Console.WriteLine("Unable to add ad group criterion #{0}", error.Index);
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                throw new Exception("", fault);
            }

            return response.AdGroupCriterionIds;
        }

        // Gets the specified list of ad group criterions.

        static AdGroupCriterion[] GetAdGroupCriterions(long accountId, long[] adGroupCriterionIds)
        {
            GetAdGroupCriterionsByIdsRequest request = new GetAdGroupCriterionsByIdsRequest();
            GetAdGroupCriterionsByIdsResponse response = null;

            // Set the header information.

            request.CustomerAccountId = accountId.ToString();
            request.DeveloperToken = m_token;
            request.UserName = m_username;
            request.Password = m_password;

            // Set the request information.

            request.AccountId = accountId;
            request.AdGroupCriterionIds = adGroupCriterionIds;

            try
            {
                response = service.GetAdGroupCriterionsByIds(request);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("GetAdGroupCriterionsByIds failed with the following faults:\n");

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    if (105 == error.Code) //  InvalidCredentials
                    {
                        Console.WriteLine("The specified credentials are not valid or " +
                            "the account is inactive.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                            error.ErrorCode, error.Code, error.Message, error.Detail);
                    }
                }

                throw new Exception("", fault);
            }
            catch (FaultException<ApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("GetAdGroupCriterionsByIds failed with the following faults:\n");

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    switch (error.Code)
                    {
                        case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                            Console.WriteLine("The CustomerAccountId header element cannot be null or empty.");
                            break;

                        case 4101: //  CampaignServiceAdGroupCriterionIdArrayNullOrEmpty
                            Console.WriteLine("The list of ad group criterion IDs cannot be null or empty.");
                            break;

                        default:
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {
                        default:
                            Console.WriteLine("Error code: {0} ({1})\nIndex: {2}Message: {3}\nDetail: {4}\n",
                                error.ErrorCode, error.Code, error.Index, error.Message, error.Details);
                            break;
                    }
                }

                throw new Exception("", fault);
            }

            return response.AdGroupCriterions;
        }

        // Gets all criterion of the specified type from the ad group.

        static AdGroupCriterion[] GetAdGroupCriterions(long accountId, long adGroupId)
        {
            GetAdGroupCriterionsByAdGroupIdRequest request = new GetAdGroupCriterionsByAdGroupIdRequest();
            GetAdGroupCriterionsByAdGroupIdResponse response = null;

            // Set the header information.

            request.CustomerAccountId = accountId.ToString();
            request.DeveloperToken = m_token;
            request.UserName = m_username;
            request.Password = m_password;

            // Set the request information.

            request.AccountId = accountId;
            request.AdGroupId = adGroupId;
            request.CriterionTypeFilter = CriterionType.Product;

            try
            {
                response = service.GetAdGroupCriterionsByAdGroupId(request);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("GetAdGroupCriterionsByAdGroupId failed with the following faults:\n");

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    if (105 == error.Code) //  InvalidCredentials
                    {
                        Console.WriteLine("The specified credentials are not valid or the account is inactive.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                            error.ErrorCode, error.Code, error.Message, error.Detail);
                    }
                }

                throw new Exception("", fault);
            }
            catch (FaultException<ApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("GetAdGroupCriterionsByAdGroupId failed with the following faults:\n");

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    switch (error.Code)
                    {
                        case 106: //  UserIsNotAuthorized
                            Console.WriteLine("The user is not authorized to call this operation.");
                            break;

                        case 1102: //  CampaignServiceInvalidAccountId
                            Console.WriteLine("The account ID is not valid.");
                            break;

                        case 1201: //  CampaignServiceInvalidAdGroupId
                            Console.WriteLine("The ad group ID is not valid.");
                            break;

                        case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                            Console.WriteLine("The CustomerAccountId header element cannot be null or empty.");
                            break;

                        case 4115: //  CampaignServiceInvalidAdGroupCriterionCriterionTypeFilter
                            Console.WriteLine("The criterion type filter cannot be null.");
                            break;

                        default:
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {
                        default:
                            Console.WriteLine("Error code: {0} ({1})\nIndex: {2}\nMessage: {3}\nDetail: {4}\n",
                                error.ErrorCode, error.Code, error.Index, error.Message, error.Details);
                            break;
                    }
                }

                throw new Exception("", fault);
            }

            return response.AdGroupCriterions;
        }

        // Updates the criterions in the ad group. Any field not set
        // to null is updated.

        private static void UpdateProductCriterion(long accountId, AdGroupCriterion[] criterions)
        {
            UpdateAdGroupCriterionsRequest request = new UpdateAdGroupCriterionsRequest();
            UpdateAdGroupCriterionsResponse response = null;
            List<AdGroupCriterion> updatedCriterions = new List<AdGroupCriterion>();

            foreach (AdGroupCriterion criterion in criterions)
            {
                if (criterion is BiddableAdGroupCriterion)
                {
                    if (((BiddableAdGroupCriterion)criterion).CriterionBid is FixedBid)
                    {

                        // Increase the bid by 20 percent if the criterion's bid amount
                        // is not set to null (a null bid amount indicates that the 
                        // criterion uses the ad group's exact-match bid value).

                        if (null != ((FixedBid)((BiddableAdGroupCriterion)criterion).CriterionBid).Bid.Amount)
                        {
                            BiddableAdGroupCriterion update = new BiddableAdGroupCriterion();
                            update.Id = criterion.Id;                  // Required
                            update.AdGroupId = criterion.AdGroupId;    // Required

                            // Update status if you want to Pause, Resume, or Delete the criterion.

                            update.Status = AdGroupCriterionStatus.Deleted; // null;  // AdGroupCriterionStatus.Paused;

                            ((BiddableAdGroupCriterion)update).CriterionBid = new FixedBid
                            {
                                Bid = new Bid {
                                    Amount = ((FixedBid)((BiddableAdGroupCriterion)criterion).CriterionBid).Bid.Amount * 1.20
                                }
                            };

                            ((BiddableAdGroupCriterion)update).DestinationUrl = null;
                            ((BiddableAdGroupCriterion)update).Param1 = null;
                            ((BiddableAdGroupCriterion)update).Param2 = null;
                            ((BiddableAdGroupCriterion)update).Param3 = null;

                            // If you don't want to update the criterion, set Criterion to null.
                            // To remove all conditions, set Conditions to an empty list. For example,
                            //     update.Criterion = new Product {
                            //         Conditions = new ProductCondition[] {}
                            //     }

                            update.Criterion = null;

                            updatedCriterions.Add(update);
                        }
                    }
                }
            }

            if (0 == updatedCriterions.Count)
            {
                return; // Nothing to update
            }

            // Set the header information.

            request.CustomerAccountId = accountId.ToString();
            request.DeveloperToken = m_token;
            request.UserName = m_username;
            request.Password = m_password;

            // Set the request information.

            request.AccountId = accountId;
            request.AdGroupCriterions = updatedCriterions.ToArray();

            try
            {
                response = service.UpdateAdGroupCriterions(request);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("UpdateAdGroupCriterions failed with the following faults:\n");

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    if (105 == error.Code) //  InvalidCredentials
                    {
                        Console.WriteLine("The specified credentials are not valid or " +
                            "the account is inactive.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                            error.ErrorCode, error.Code, error.Message, error.Detail);
                    }
                }

                throw new Exception("", fault);
            }
            catch (FaultException<ApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("UpdateAdGroupCriterions failed with the following faults:\n");

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    switch (error.Code)
                    {
                        case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                            Console.WriteLine("The CustomerAccountId header element cannot be null or empty.");
                            break;

                        case 3863: // CampaignServiceProductAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To add ad group criterions, the customer " +
                                "must be a member of the Product Ad pilot program.\n");
                            break;

                        case 4104: // CampaignServiceAdGroupCriterionsNullOrEmpty
                            Console.WriteLine("To list of ad group criterions cannot be null or empty.\n");
                            break;

                        default:
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {
                        case 1515: // CampaignServiceBidAmountsLessThanFloorPrice
                            Console.WriteLine("The bid value of ad group criterion #{0} is " +
                                "less than the minimum allowed bid value.\n",
                                error.Index);
                            break;

                        case 1516: // CampaignServiceBidAmountsGreaterThanCeilingPrice
                            Console.WriteLine("The bid value of ad group criterion #{0} " +
                                "exceeds the maximum allowed bid value.\n",
                                error.Index);
                            break;

                        case 3869: // CampaignServiceProductAdExtensionOperandIsInvalid
                            Console.WriteLine("Product operand #{0} of ad group criterion " +
                                "#{1} is not valid.\n",
                                error.Details,
                                error.Index);
                            break;

                        case 3870: // CampaignServiceProductAdExtensionAttributeIsInvalid
                            Console.WriteLine("Product attribute #{0} of ad group criterion " +
                                "#{1} is not valid.\n",
                                error.Details,
                                error.Index);
                            break;

                        case 3872: // CampaignServiceProductConditionDuplicateOperand
                            Console.WriteLine("Ad group criterion #{1} contains duplicate product operands. " +
                                "Product operand #{0} is a duplicate.\n",
                                error.Details,
                                error.Index);
                            break;

                        case 4108: // CampaignServiceAdGroupCriterionInvalidBidType
                            Console.WriteLine("The bid of ad group criterion #{0} is null " +
                                "or is of the wrong type.\n",
                                error.Index);
                            break;

                        case 4109: // CampaignServiceAdGroupCriterionInvalidBidValue
                            Console.WriteLine("The bid value of ad group criterion " +
                                "#{0} is not valid.\n",
                                error.Index);
                            break;

                        case 4113: // CampaignServiceProductAdGroupCriterionTooManyConditions
                            Console.WriteLine("The list of product conditions of ad group " +
                                "criterion #{0} is too long.\n",
                                error.Index);
                            break;

                        default:
                            Console.WriteLine("Unable to add ad group criterion #{0}", error.Index);
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                throw new Exception("", fault);
            }
        }

        // Prints the details of the criterion.

        private static void PrintAdGroupCriterions(long[] criterionIds, AdGroupCriterion[] criterions)
        {
            int i = 0;

            foreach (AdGroupCriterion adGroupCriterion in criterions)
            {
                if (null != adGroupCriterion)
                {
                    if (adGroupCriterion is BiddableAdGroupCriterion)
                    {
                        BiddableAdGroupCriterion biddableCriterion = (BiddableAdGroupCriterion)adGroupCriterion;

                        Console.WriteLine("Biddable criterion ID: " + biddableCriterion.Id);

                        if (biddableCriterion.CriterionBid is FixedBid)
                        {
                            if (null == ((FixedBid)biddableCriterion.CriterionBid).Bid.Amount)
                            {
                                Console.WriteLine("  Bid amount: Uses the ad group's exact-match bid value");
                            }
                            else
                            {
                                Console.WriteLine("  Bid amount: {0:C}", ((FixedBid)biddableCriterion.CriterionBid).Bid.Amount);
                            }
                        }

                        Console.WriteLine("  Destination URL: " + biddableCriterion.DestinationUrl);
                        Console.WriteLine("  Param1: " + biddableCriterion.Param1);
                        Console.WriteLine("  Param2: " + biddableCriterion.Param2);
                        Console.WriteLine("  Param3: " + biddableCriterion.Param3);
                        Console.WriteLine("  Status: " + biddableCriterion.Status);
                        Console.WriteLine("  Editorial status: " + biddableCriterion.EditorialStatus);

                        if (biddableCriterion.Criterion is Product)
                        {
                            Console.Write("  Product conditions: ");

                            int length = ((Product)biddableCriterion.Criterion).Conditions.Length;

                            if (length > 0)
                            {
                                for (int j = 0; j < length; j++)
                                {
                                    Console.Write("{0}={1}{2}", ((Product)biddableCriterion.Criterion).Conditions[j].Operand,
                                        ((Product)biddableCriterion.Criterion).Conditions[j].Attribute,
                                        (j + 1 < length) ? " AND " : "\n\n");
                                }
                            }
                            else
                            {
                                Console.WriteLine("No product filter applied.\n");
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Ad group criterion {0} was not found.\n", criterionIds[i]);
                }

                i++;
            }
        }
    }
}


Community Additions

Show:
© 2014 Microsoft