Export (0) Print
Expand All

Get Keyword Suggestions in C#

The following example shows how to get keyword suggestions that could perform better than the specified keywords using the Ad Intelligence SuggestKeywordsFromExistingKeywords 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.AdIntelligence is the application-defined namespace that 
// this example uses for the Ad Intelligence service reference. 

using GetKeywordsFromKeywords.BingAds.AdIntelligence;

namespace GetKeywordsFromKeywords
{
    class Program
    {
        private static AdIntelligenceServiceClient 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>;


        static void Main()
        {
            KeywordSuggestion[] suggestedKeywords = null;

            try
            {
                service = new AdIntelligenceServiceClient();

                suggestedKeywords = GetSuggestedKeywords(m_accountId);

                if (suggestedKeywords != null) 
                {
                    foreach (KeywordSuggestion keyword in suggestedKeywords)
                    {
                        // If the request keyword is not valid, the corresponding item
                        // in the response is null.
 
                        if (null != keyword)
                        {
                            Console.WriteLine(keyword.Keyword);

                            if (null == keyword.SuggestionsAndConfidence)
                            {
                                Console.WriteLine("  There are no suggestions for the keyword.");
                            }
                            else
                            {
                                foreach (KeywordAndConfidence suggestion in keyword.SuggestionsAndConfidence)
                                {
                                    Console.WriteLine("  {0} ({1:n0}% confidence) ", suggestion.SuggestedKeyword, suggestion.ConfidenceScore * 100);
                                }
                            }

                            Console.WriteLine();
                        }
                    }
                }

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


        // Get the suggested keywords for each keyword specified in the request. The suggestion
        // type specifies the type of provider to use to generate the suggestions. For information
        // about the language and country combinations that each provider supports, see the documentation
        // on MSDN.

        static KeywordSuggestion[] GetSuggestedKeywords(long accountId)
        {
            SuggestKeywordsFromExistingKeywordsRequest request = new SuggestKeywordsFromExistingKeywordsRequest();
            SuggestKeywordsFromExistingKeywordsResponse 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.Keywords = new[] { "flower delivery" };
            request.Language = "English";
            request.PublisherCountries = new[] { "US", "CA" };
            request.MaxSuggestionsPerKeyword = 10;
            request.SuggestionType = 2; // Return keywords from other ad groups that include the specified keyword.

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

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

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

                Console.WriteLine("SuggestKeywordsFromExistingKeywords 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 1505: // CampaignServiceKeywordsArrayShouldNotBeNullOrEmpty
                            Console.WriteLine("The list of keywords cannot be null or empty.");
                            break;

                        case 3407: // CampaignServiceInvalidMaxSuggestionsPerKeyword
                            Console.WriteLine("The specified maximum number of suggestions to return per keyword is not valid.");
                            break;

                        case 3408: // CampaignServiceLanguageAndCountryNotSupported
                            Console.WriteLine("One or more of the specified publisher countries is not allowed for the specified language.");
                            break;

                        case 3412: // CampaignServiceInvalidLanguage
                            Console.WriteLine("The specified language is not valid.");
                            break;

                        case 3413: // CampaignServiceInvalidPublisherCountry
                            Console.WriteLine("One or more of the specified publisher countries is not valid.");
                            break;

                        case 3420: // CampaignServiceInvalidSuggestionType
                            Console.WriteLine("The specified suggestion type is not valid.");
                            break;

                        case 3421: // CampaignServiceUnSupportedCountryForSuggestionType
                            Console.WriteLine("One or more of the specified publisher countries is not allowed for the specified suggestion type.");
                            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)
                {
                    Console.WriteLine("Error code: {0} ({1})\nIndex: {2}\nMessage: {3}\nDetail: {4}\n",
                        error.ErrorCode, error.Code, error.Index, error.Message, error.Details);
                }
            }

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

Community Additions

Show:
© 2014 Microsoft