Export (0) Print
Expand All

Update Keywords in C#

The following example shows how to get specific keywords and update some elements 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 that 
// this example uses for the Campaign Management service reference. 

using UpdateKeywords.BingAds.CampaignManagement;


namespace UpdateKeywords
{
    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 ad group that owns the keywords to be updated.

        private static long m_adGroupId = <adgroupidgoeshere>;

        // List of keywords to update.

        private static long[] m_keywordIds = new long[] { <keywordidgoeshere>, <keywordidgoeshere> };


        static void Main(string[] args)
        {
            Keyword[] keywords = null;

            try
            {
                service = new CampaignManagementServiceClient();

                Console.WriteLine("Keywords before update...\n");
                keywords = GetKeywords(m_accountId, m_adGroupId, m_keywordIds);

                UpdateKeywords(m_accountId, m_adGroupId, keywords);

                Console.WriteLine("Keywords after update...\n");
                keywords = GetKeywords(m_accountId, m_adGroupId, m_keywordIds);

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

        // Update keywords. You cannot change a keyword's match type.
        // If you no longer want to bid on a keyword/match type, you must delete
        // the keyword/match type and then add the new keyword/match type.

        // The only elements that you can update are the parameter
        // elements (i.e. Param2) and the keyword/match type's bid value.
        // You can set the bid value to a non-zero bid value or null.
        // Setting the bid value to null, indicates that you want to use the 
        // ad group's match type bid value.

        // If you do not want to update the bid value, set all 
        // match-type bid elements to null (i.e. ExactMatchBid = null).

        static void UpdateKeywords(long accountId, long adGroupId, Keyword[] keywords)
        {
            UpdateKeywordsRequest request = new UpdateKeywordsRequest();
            UpdateKeywordsResponse response = null;
            List<Keyword> updatedKeywords = new List<Keyword>();
            string bidType = null;
            double bid = 0.0;

            // Update the keywords. Change Param2 to "20% off" and 
            // increase the bid by 15%.

            // Using a List<> in case a bad keyword ID was passed to 
            // Get, in which case, the keyword item in the list will be null.

            foreach (Keyword keyword in keywords)
            {
                if (null != keyword)
                {
                    Keyword updatedKeyword = new Keyword();
                    updatedKeyword.Id = keyword.Id;
                    updatedKeyword.Param2 = "20% off";

                    bidType = GetBidType(keyword, out bid);

                    if (0.0 != bid) // Don't update bid if null; continue to 
                    {               // use ad group's default bid.
                        SetKeywordBid(updatedKeyword, bidType, bid * 1.15);
                    }

                    updatedKeywords.Add(updatedKeyword);
                }
            }

            // 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.Keywords = updatedKeywords.ToArray();

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

                Console.WriteLine("UpdateKeywords 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("UpdateKeywords failed with the following faults (no keywords were updated):\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 1201: //  CampaignServiceInvalidAdGroupId
                            Console.WriteLine("The specified ad group ID is not valid.");
                            break;

                        case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                            Console.WriteLine("You must specify the account ID in the CustomerAccountId header element.");
                            break;

                        case 1505: //  CampaignServiceKeywordsArrayShouldNotBeNullOrEmpty
                            Console.WriteLine("The array of keywords cannot be null or empty.");
                            break;

                        case 1506: // CampaignServiceKeywordsArrayExceedsLimit
                            Console.WriteLine("The list of keywords 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;
                    }
                }

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {
                        case 1001: // CampaignServiceCannotChangeStatusOnUpdate
                            Console.WriteLine("Failed to update keyword \"{0}\". The keyword's status is read-only and must be null.\n",
                                request.Keywords[error.Index].Text);
                            break;

                        case 1500: // CampaignServiceNullKeyword
                            Console.WriteLine("The list of keywords contains a null Keyword object in position {0}.\n",
                                error.Index);
                            break;

                        case 1501: // CampaignServiceInvalidKeywordId
                            Console.WriteLine("Failed to update keyword \"{0}\". The keyword's ID is not valid.\n",
                                request.Keywords[error.Index].Text);
                            break;

                        case 1504: // CampaignServiceCannotChangeTextOnUpdate
                            Console.WriteLine("Failed to update keyword \"{0}\". The keyword's text is read-only and must be null.\n",
                                request.Keywords[error.Index].Text);
                            break;

                        case 1515: // CampaignServiceBidAmountsLessThanFloorPrice
                            Console.WriteLine("Failed to update keyword \"{0}\". The keyword's bid value is less than the minimum bid value allowed.\n",
                                request.Keywords[error.Index].Text);
                            break;

                        case 1516: // CampaignServiceBidAmountsGreaterThanCeilingPrice
                            Console.WriteLine("Failed to update keyword \"{0}\". The keyword's bid value exceeds the maximum bid value allowed.\n",
                                request.Keywords[error.Index].Text);
                            break;

                        case 1532: // CampaignServiceInvalidKeywordEditorialStatus
                            Console.WriteLine("Failed to update keyword \"{0}\". The keyword's editorial status is read-only and must be null.\n",
                                request.Keywords[error.Index].Text);
                            break;

                        case 1541: // CampaignServiceMultipleKeywordBidTypesNotAllowed
                            Console.WriteLine("The keyword \"{0}\" cannot specify more than one match-type bid.\n",
                                request.Keywords[error.Index].Text);
                            break;

                        case 1544: // CampaignServiceKeywordZeroBidAmountNotAllowed
                            Console.WriteLine("Failed to update keyword \"{0}\". The bid value cannot be set to zero.\n",
                                request.Keywords[error.Index].Text);
                            break;

                        case 1545: // CampaignServiceKeywordMatchTypeChangeNotAllowedInUpdate
                            Console.WriteLine("Failed to update keyword \"{0}\". You cannot change the keyword's match type by specifying a bid value for a different match type.\n",
                                request.Keywords[error.Index].Text);
                            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;
                    }
                }

                foreach (EditorialError error in fault.Detail.EditorialErrors)
                {
                    switch (error.Code)
                    {

                        default:
                            Console.WriteLine("Unable to add keyword #{0} for editorial reasons.", error.Index);
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}",
                                error.ErrorCode, error.Code, error.Message);
                            Console.WriteLine("Appealable: {0}\nDisapproved text: {1}\nCountry: {2}\n",
                                error.Appealable, error.DisapprovedText, error.PublisherCountry);
                            break;
                    }
                }

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

        // Update the keyword's bid. Determine which bid to set based 
        // on the specified match type.

        private static void SetKeywordBid(Keyword keyword, string bidType, double bid)
        {
            if ("Exact" == bidType)
            {
                keyword.ExactMatchBid = new Bid { Amount = bid };
            }
            else if ("Phrase" == bidType)
            {
                keyword.PhraseMatchBid = new Bid { Amount = bid };
            }
            else if ("Broad" == bidType)
            {
                keyword.BroadMatchBid = new Bid { Amount = bid };
            }
            else
            {
                keyword.ContentMatchBid = new Bid { Amount = bid };
            }
        }


        // Get keywords to update. 

        static Keyword[] GetKeywords(long accountId, long adGroupId, long[] keywordIds)
        {
            GetKeywordsByIdsRequest request = new GetKeywordsByIdsRequest();
            GetKeywordsByIdsResponse response = null;
            double bid = 0.0;

            // 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.KeywordIds = keywordIds;

            try
            {
                response = service.GetKeywordsByIds(request);

                for (int i = 0; i < response.Keywords.Length; i++)
                {
                    Keyword keyword = response.Keywords[i];

                    if (null != keyword)
                    {
                        Console.WriteLine("Keyword: " + keyword.Text);
                        Console.WriteLine("Id: " + keyword.Id);
                        Console.WriteLine("Match type: " + GetBidType(keyword, out bid));

                        // GetBidType sets the bid to 0.0 if the match type's
                        // bid amount is set to null, which indicates that the 
                        // match type uses the ad group's default bid value.

                        if (bid > 0.0)
                        {
                            Console.WriteLine("Bid: {0:C} ", bid);
                        }
                        else
                        {
                            Console.WriteLine("Bid: Ad group default bid");
                        }

                        Console.WriteLine("Param2: " + keyword.Param2);
                        Console.WriteLine();
                    }
                    else
                    {
                        Console.WriteLine("Keyword {0} is not valid.\n", keywordIds[i]);
                    }
                }
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("GetKeywordsByIds 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("GetKeywordsByIds 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 1201: //  CampaignServiceInvalidAdGroupId
                            Console.WriteLine("The specified ad group ID is not valid.");
                            break;

                        case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                            Console.WriteLine("You must specify the account ID in the CustomerAccountId header element.");
                            break;

                        case 1529: //  CampaignServiceKeywordIdsArrayShouldNotBeNullOrEmpty
                            Console.WriteLine("The list of keyword 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 1502: //  CampaignServiceDuplicateInKeywordIds
                            Console.WriteLine("The keyword IDs list contains duplicate IDs. Keyword ID {0} in item #{1} of the list is a duplicate.",
                                keywordIds[error.Index],
                                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.Keywords;
        }

        // A keyword object can specify only one match-type bid value.
        // Figure out which bid is set and return the match type and 
        // bid value. 

        // If the bid Amount is null, that indicates that the ad group's 
        // bid value is used. To catch this case in the calling method, 
        // we're setting the bid to 0.0 (which is not a valid bid value).

        private static string GetBidType(Keyword keyword, out double bid)
        {
            string bidType = null;

            if (null != keyword.ExactMatchBid)
            {
                bidType = "Exact";
                bid = (double)((null == keyword.ExactMatchBid.Amount) ? 0.0 : keyword.ExactMatchBid.Amount);
            }
            else if (null != keyword.PhraseMatchBid)
            {
                bidType = "Phrase";
                bid = (double)((null == keyword.PhraseMatchBid.Amount) ? 0.0 : keyword.PhraseMatchBid.Amount);
            }
            else if (null != keyword.BroadMatchBid)
            {
                bidType = "Broad";
                bid = (double)((null == keyword.BroadMatchBid.Amount) ? 0.0 : keyword.BroadMatchBid.Amount);
            }
            else
            {
                bidType = "Content";
                bid = (double)((null == keyword.ContentMatchBid.Amount) ? 0.0 : keyword.ContentMatchBid.Amount);
            }

            return bidType;
        }
    }
}


Community Additions

Show:
© 2014 Microsoft