Export (0) Print
Expand All

Get Historical Performance in C#

The following example shows how to get the historical bid and traffic performance of one or more keywords used in search queries using the Ad Intelligence GetHistoricalKeywordPerformanceByDevice 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 GetPerformanceByDevice.BingAds.AdIntelligence;


namespace GetPerformanceByDevice
{
    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()
        {
            KeywordHistoricalPerformanceByDevice[] performances = null;

            try
            {
                service = new AdIntelligenceServiceClient();

                performances = GetPerformances(m_accountId);

                if (performances != null)
                {
                    foreach (KeywordHistoricalPerformanceByDevice performance in performances)
                    {
                        Console.Write("{0}", performance.Keyword);

                        if (null == performance.Device)
                        {
                            Console.WriteLine("\n  There is no historical performance data available for the keyword.\n");
                        }
                        else
                        {
                            Console.WriteLine(" ({0})", performance.Device);

                            foreach (KeywordKPI kpi in performance.KeywordKPIs)
                            {
                                Console.WriteLine("  " + kpi.MatchType);
                                Console.WriteLine("    Ad Position: " + kpi.AdPosition);
                                Console.WriteLine("    Average Bid: {0:c}", kpi.AverageBid);
                                Console.WriteLine("    Average CPC: {0:c}", kpi.AverageCPC);
                                Console.WriteLine("    Total Cost: {0:c}", kpi.TotalCost);
                                Console.WriteLine("    Clicks: {0:n0}", kpi.Clicks);
                                Console.WriteLine("    CTR: {0:n2}%", kpi.CTR);
                                Console.WriteLine("    Impressions: {0:n0}\n", kpi.Impressions);
                            }
                        }
                    }
                }

                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 historical performance of the specified keywords.
        // The performance is broken out by device type and match type.

        static KeywordHistoricalPerformanceByDevice[] GetPerformances(long accountId)
        {
            GetHistoricalKeywordPerformanceByDeviceRequest request = new GetHistoricalKeywordPerformanceByDeviceRequest();
            GetHistoricalKeywordPerformanceByDeviceResponse 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.Devices = new[] { "Smartphones", "Computers" };
            request.Keywords = new[] { "flower delivery" };
            request.Language = "English"; 
            request.MatchTypes = new[] { MatchType.Broad, MatchType.Phrase, MatchType.Exact };
            request.PublisherCountries = new[] { "US" };
            request.TargetAdPosition = AdPosition.MainLine3;
            request.TimeInterval = TimeInterval.Last7Days;

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

                Console.WriteLine("GetHistoricalKeywordPerformanceByDevice 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("GetHistoricalKeywordPerformanceByDevice 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 1257: // CampaignServiceMissingLanguage
                            Console.WriteLine("The language cannot be null or empty.");
                            break;

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

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

                        case 3409: // CampaignServiceInvalidMatchTypes
                            Console.WriteLine("The list of match types cannot be null or empty.");
                            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 3417: // CampaignServiceInvalidDevice
                            Console.WriteLine("One or more of the specified devices is not valid.");
                            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.KeywordHistoricalPerformances;
        }
    }
}

Community Additions

Show:
© 2014 Microsoft