Ad Rotation in C#

The following example shows how to get and set the ad rotation of an ad group using the following Campaign Management service operations.

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 of 
// the service reference used for this example. 

using SetAdRotation.BingAds.CampaignManagement;

namespace SetAdRotation
{
    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 ID.

        private static long m_accountId = <accountidgoeshere>;

        // Specify the campaign and ad group IDs.

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

        static void Main(string[] args)
        {
            AdRotation[] adRotations = null;

            try
            {
                service = new CampaignManagementServiceClient();

                SetAdRotation(m_accountId, m_campaignId, m_adGroupId, AdRotationType.RotateAdsEvenly);

                adRotations = GetAdRotation(m_accountId, m_campaignId, m_adGroupId);

                foreach (AdRotation adRotation in adRotations)
                {
                    Console.WriteLine("Ad group {0} rotates {1}.",
                        m_adGroupId,
                        (AdRotationType.OptimizeForClicks == adRotation.Type) ? "best performing ads" : "ads evenly");
                }

                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)
            {
                // Ignore fault exceptions that we already caught.

                if (e.InnerException is FaultException)
                {
                    ;
                }
                else
                {
                    Console.WriteLine(e.Message);
                }


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

        // Set the type of ad rotation to use for the specified ad group.

        static void SetAdRotation(long accountId, long campaignId, long adGroupId, AdRotationType rotation)
        {
            SetAdRotationToAdGroupsRequest request = new SetAdRotationToAdGroupsRequest();
            SetAdRotationToAdGroupsResponse 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.CampaignId = campaignId;
            request.AdGroupAdRotations = new AdGroupAdRotation[] {
                new AdGroupAdRotation {
                    AdGroupId = adGroupId,
                    AdRotation = new AdRotation {
                        Type = rotation,
                        StartDate = null,  // The start and end dates must be null.
                        EndDate = null
                    }
                }
            };

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

                Console.WriteLine("SetAdRotationToAdGroups 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("SetAdRotationToAdGroups 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 1100: //  CampaignServiceInvalidCampaignId
                            Console.WriteLine("The campaign ID {0} is not valid.", campaignId);
                            break;

                        case 1201: //  CampaignServiceInvalidAdGroupId
                            Console.WriteLine("All AdGroupAdRotation objects must specify an ad group ID.");
                            break;

                        case 1261: //  CampaignServiceAdGroupAdRotationArrayShouldNotBeNullOrEmpty
                            Console.WriteLine("The list of AdGroupAdRotations cannot be null or emtpy.");
                            break;

                        case 1263: //  CampaignServiceCannotSetStartOrEndDateForAdRotation
                            Console.WriteLine("The start and end dates must 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)
                    {
                        case 1201: //  CampaignServiceInvalidAdGroupId
                            Console.WriteLine("The ad group ID {0} specified in AdGroupAdRotations[{1}] is not valid.",
                                request.AdGroupAdRotations[error.Index].AdGroupId,
                                error.Index);
                            break;

                        case 1214: //  CampaignServiceCannotCreateDuplicateAdGroup
                            Console.WriteLine("The list of AdGroupRotations must contain unique ad group IDs; " +
                                "ad group ID {0} specified in AdGroupAdRotations[{1}] already exists in the list.",
                                request.AdGroupAdRotations[error.Index].AdGroupId,
                                error.Index);
                            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);
            }
        }

        // Get the type of ad rotation used by the specified ad group.

        static AdRotation[] GetAdRotation(long accountId, long campaignId, long adGroupId)
        {
            GetAdRotationByAdGroupIdsRequest request = new GetAdRotationByAdGroupIdsRequest();
            GetAdRotationByAdGroupIdsResponse 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.CampaignId = campaignId;
            request.AdGroupIds = new long[] { adGroupId };

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

                Console.WriteLine("GetAdRotationByAdGroupIds 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("GetAdRotationByAdGroupIds 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 1218: //  CampaignServiceAdGroupIdsArrayShouldNotBeNullOrEmpty
                            Console.WriteLine("The list of ad group 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)
                    {
                        case 1201: //  CampaignServiceInvalidAdGroupId
                            Console.WriteLine("The ad group ID {0} is not valid.",
                                request.AdGroupIds[error.Index]);
                            break;

                        case 1203: //  CampaignServiceDuplicateInAdGroupIds
                            Console.WriteLine("The list of ad group IDs must be unique; " +
                                "ad group ID {0} already exists in the list.",
                                request.AdGroupIds[error.Index]);
                            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);
            }

            return response.AdRotationByAdGroupIds;
        }
    }
}

Community Additions

Show: