Export (0) Print
Expand All

Negative Keywords in C#

This example shows how to set and get an ad group’s negative keywords 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 NegativeKeywords.BingAds.CampaignManagement;


namespace NegativeKeywords
{
    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[] negativeKeywords = { "[Girl Ski Gloves]", "[Boy Ski Gloves]", "[Children Ski Gloves]", "Baseball", "Golf" };

            try
            {
                service = new CampaignManagementServiceClient();

                SetNegativeKeywords(m_accountId, m_campaignId, m_adGroupId, negativeKeywords);
                Console.WriteLine("Added negative keywords to ad group {0}.", m_adGroupId);

                negativeKeywords = GetNegativeKeywords(m_accountId, m_campaignId, m_adGroupId);
                Console.WriteLine("Ad group {0} contains {1} negative keywords.", m_adGroupId, negativeKeywords.Length);

                negativeKeywords = new string[] { }; // Remove keywords
                SetNegativeKeywords(m_accountId, m_campaignId, m_adGroupId, negativeKeywords);
                Console.WriteLine("Removed negative keywords from ad group {0}.", m_adGroupId);

                negativeKeywords = GetNegativeKeywords(m_accountId, m_campaignId, m_adGroupId);
                Console.WriteLine("Ad group {0} contains {1} negative keywords.", m_adGroupId, negativeKeywords.Length);

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


        // Sets the list of negative keywords for the specified ad group. 

        static void SetNegativeKeywords(long accountId, long campaignId, long adGroupId, string[] negativeKeywords)
        {
            SetNegativeKeywordsToAdGroupsRequest request = new SetNegativeKeywordsToAdGroupsRequest();
            SetNegativeKeywordsToAdGroupsResponse 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.AdGroupNegativeKeywords = new[] {
                new AdGroupNegativeKeywords {
                    AdGroupId = adGroupId,
                    NegativeKeywords = negativeKeywords
                }
            };

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

                Console.WriteLine("SetNegativeKeywordsToAdGroups 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);
                }

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

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

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

                        case 1100: // CampaignServiceInvalidCampaignId
                            Console.WriteLine("The campaign ID is not valid.");
                            break;

                        case 1218: // CampaignServiceAdGroupIdsArrayShouldNotBeNullOrEmpty
                            Console.WriteLine("The list of AdGroupNegativeKeywords objects 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 1005: // CampaignServiceInvalidNegativeKeyword
                            Console.WriteLine("One or more of the negative keywords for ad group {0} are not valid.\n" +
                                "For example, a keyword could be too long or contain characters that are not allowed.", 
                                adGroupId);
                            break;

                        case 1032: // CampaignServiceNegativeKeywordsLimitExceeded
                            Console.WriteLine("The list of negative keywords exceeds the maximum allowed.");
                            break;

                        case 1034: // CampaignServiceNegativeKeywordsNotPassed
                            Console.WriteLine("The list of negative keywords cannot be null. To remove negative\n" +
                                "keywords from an ad group, pass an empty list.");
                            break;

                        case 1201: // CampaignServiceInvalidAdGroupId
                            Console.WriteLine("Ad group {0} does not belong to campaign {1}.", adGroupId, campaignId);
                            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);
            }
        }

        // Gets the ad group's list of negative keywords. 

        static string[] GetNegativeKeywords(long accountId, long campaignId, long adGroupId)
        {
            GetNegativeKeywordsByAdGroupIdsRequest request = new GetNegativeKeywordsByAdGroupIdsRequest();
            GetNegativeKeywordsByAdGroupIdsResponse 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.GetNegativeKeywordsByAdGroupIds(request);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("GetNegativeKeywordsByAdGroupIds 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);
                }

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

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

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

                        case 1100: // CampaignServiceInvalidCampaignId
                            Console.WriteLine("The campaign ID is not valid.");
                            break;

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

                        case 1219: // CampaignServiceAdGroupIdsArrayExceedsLimit
                            Console.WriteLine("The list of ad group IDs contains too many IDs.");
                            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 1203: // CampaignServiceDuplicateInAdGroupIds
                            Console.WriteLine("The list of ad group IDs cannot contain duplicate IDs. " +
                                "ID {0} is a duplicate.", 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.AdGroupNegativeKeywords[0].NegativeKeywords;
        }
    }
}


Community Additions

Show:
© 2014 Microsoft