Export (0) Print
Expand All

Add Ad Groups in C#

The following example shows how to create ad groups within a campaign using the Campaign Management AddAdGroups service operation.

This example has been developed and run within the environment described in Getting Started Using C# and Visual Basic with Bing Ads Services.

System_CLiX_note Note

This example uses the UserName and Password elements for authentication. For Managing User Authentication with OAuth, replace the UserName and Password elements with the AuthenticationToken, which is your OAuth access token.

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

// BingAds.CampaignManagement is the application-defined namespace that 
// this example used when it added the Campaign Management service reference. 

using CreateAdGroups.BingAds.CampaignManagement;


namespace CreateAdGroups
{
    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 account that owns the campaign that the ad 
        // groups will be added to.

        private static long m_accountId = <AccountIDGoesHere>;

        // Specify the campaign that will own the ad groups.

        private static long m_campaignId = <CampaignIDGoesHere>;


        static void Main()
        {
            long[] adGroupIds = null;

            try
            {
                service = new CampaignManagementServiceClient();

                adGroupIds = CreateAdGroups(m_accountId, m_campaignId);

                if (adGroupIds != null)
                {
                    // Do something with the IDs.
                }

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

                if (null != e.InnerException)
                {
                    Console.WriteLine("\n" + e.InnerException.Message);
                }

                if (service != null)
                {
                    service.Abort();
                }
            }
            catch (TimeoutException e)
            {
                Console.WriteLine(e.Message);

                if (service != null)
                {
                    service.Abort();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);

                if (service != null)
                {
                    service.Abort();
                }
            }
        }


        // Add one or more ad groups to the specified campaign. 

        static long[] CreateAdGroups(long accountId, long campaignId)
        {
            AddAdGroupsRequest request = new AddAdGroupsRequest();
            AddAdGroupsResponse response = null;
            int i = 0;  // Index into ad groups.

            // Specify the ad groups and default bid values. Because broad
            // match bid is not specified, it defaults to the minimum bid
            // value for the currency, which in this example is .05 cents.

            // Because the status is set to Paused, you will need to call
            // the ResumeAdGroups operation after you add the keywords and ads
            // to the ad group.

            AdGroup[] adGroups = new[] {
                new AdGroup {
                    Name = "Women's Heated Ski Glove Sale",
                    AdDistribution = AdDistribution.Search,
                    BiddingModel = BiddingModel.Keyword,
                    PricingModel = PricingModel.Cpc,
                    EndDate = new Date {Month = 12, Day = 31, Year = DateTime.Now.Year},
                    ExactMatchBid = new Bid {Amount = 0.09},
                    PhraseMatchBid = new Bid {Amount = 0.07},
                    Status = AdGroupStatus.Paused,
                    Language = "English",
                }
            };

            // Set the request header information.

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

            // Set the request information.

            request.CampaignId = campaignId;
            request.AdGroups = adGroups;

            try
            {
                response = service.AddAdGroups(request);

                foreach (long id in response.AdGroupIds)
                {
                    Console.WriteLine("Added an ad group \"{0}\" with ID {1}.", 
                        adGroups[i++].Name, id);
                }
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

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

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                        error.ErrorCode, error.Code, error.Message, error.Detail);
                }

            }
            catch (FaultException<ApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("AddAdGroups failed with the following faults " +
                    "(no ad groups were added):\n");

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    if (1030 == error.Code) // CampaignServiceAccountIdHasToBeSpecified
                    {
                        Console.WriteLine("You must specify the account ID in the " +
                            "request header when calling this operation.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                            error.ErrorCode, error.Code, error.Message, error.Details);
                    }
                }

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {
                        case 1202: // CampaignServiceInvalidAdGroupName
                            Console.WriteLine("You must specify a valid ad group name " +
                                "for the ad group #{0}.\n",
                                error.Index + 1);
                            break;

                        case 1214: // CampaignServiceCannotCreateDuplicateAdGroup
                            Console.WriteLine("An ad group named \"{0}\" already exists. " +
                                "Please specify a new ad group name.\n",
                                adGroups[error.Index].Name);
                            break;

                        case 1224: // CampaignServiceAdGroupMissingAdMedium
                            Console.WriteLine("You must specify a valid distribution " +
                                "medium for the ad group \"{0}\".\n",
                                adGroups[error.Index].Name);
                            break;

                        case 1234: // CampaignServiceAdGroupPricingModelCpmRequiresContentMedium
                            Console.WriteLine("You can specify the CPM pricing model for the ad " +
                                "group \"{0}\" if the distribution medium is set only to Content.\n",
                                adGroups[error.Index].Name);
                            break;

                        case 1237: // CampaignServiceAdGroupPricingModelIsNull
                            Console.WriteLine("You must specify a valid pricing model for " +
                                "the ad group \"{0}\".\n",
                                adGroups[error.Index].Name);
                            break;

                        case 1240: // CampaignServiceTypeCanBeSitePlacementOnlyForContentAdGroups
                            Console.WriteLine("You can specify the site placement bidding " +
                                "model for the ad group \"{0}\" only if the distribution medium " +
                                "is set to Content.\n",
                                adGroups[error.Index].Name);
                            break;

                        case 1257: // CampaignServiceMissingLanguage
                            Console.WriteLine("You must specify the language used by the ads " +
                                "in the \"{0}\" ad group.\n",
                                adGroups[error.Index].Name);
                            break;

                        case 1515: // CampaignServiceBidAmountsLessThanFloorPrice
                            Console.WriteLine("The \"{0}\" ad group contains a bid value " +
                                "that is less than the minimum bid value allowed for the " +
                                "currency.\n",
                                adGroups[error.Index].Name);
                            break;

                        case 1516: // CampaignServiceBidAmountsGreaterThanCeilingPrice
                            Console.WriteLine("The \"{0}\" ad group contains a bid value that " +
                                "exceeds the maximum bid value allowed for the currency.\n",
                                adGroups[error.Index].Name);
                            break;

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

            }

            return (null == response) ? null : response.AdGroupIds;
        }
    }
}   

Community Additions

Show:
© 2014 Microsoft