Bing Ads API C#示例代码不起作用

时间:2013-01-14 17:07:08

标签: c# bing-api

我试过运行C#示例代码,但收到以下错误:

  

错误代码:InternalError< 0>
消息:内部错误有   发生了。
详情:[这是空白]

我也尝试在自己的代码中实现报告服务,但已收到

  

“对象引用未设置为对象的实例”错误   行:

response = reportingService.SubmitGenerateReport(request);

这是我的代码,删除了ids /密码/令牌:

using System;
using System.ServiceModel;
using System.Data;

// BingAds.CampaignManagement is the application-defined namespace of 
// the service reference used for this example. 

using collectBingAdsData.BingAds.Reporting;
using collectBingAdsData.BingAds.CampaignManagement;
using collectBingAdsData.BingAds.Bulk;

namespace collectBingAdsData
{
    class Program
    {
        private static CampaignManagementServiceClient campaignManagementService = null;
        private static ReportingServiceClient reportingService = null;
        private static BulkServiceClient bulkService = null;

        private static DataTable BingSemData;

        // Specify your credentials.

        private static string m_password = "password";
        private static string m_username = "username";
        private static string m_token = "token";

        // Specify the advertiser's account ID and customer ID.

        private static long customerID = 123123;
        private static long[] accountIDs = { 123123 };
        private static long[] campaignIDs = { 123123 };

        private static string m_downloadPath = @"c:\reports\keywordperf.zip";

        // Shows how to request a keyword performance report and download it
        // to the specified folder.
        //
        // args[0] - Report ID. To download an existing report request instead 
        //           of requesting a new report, set args[0] to a report ID.

        static void Main(string[] args)
        {
            getAccountsByCutomer(customerID);
            foreach (long accountID in accountIDs)
            {
                getCampaignsByAccount(accountID);
                foreach (long campaignID in campaignIDs)
                {
                    //getCampaignReport(accountID, campaignID);
                    getKeywordReport(accountID, campaignID);
                }
            }
        }

        private static void getKeywordReport(long accountID, long campaignID)
        {
            KeywordPerformanceReportRequest request = new KeywordPerformanceReportRequest();

            request = buildKeywordPerformanceRequest(accountID, campaignID);

            string BingData = RequestReport(request);
        }

        private static void getCampaignReport(long accountID, long campaignID)
        {
            CampaignPerformanceReportRequest request = new CampaignPerformanceReportRequest();

            request = buildCampaignPerformanceRequest(accountID, campaignID);

            string BingData = RequestReport(request);



        }

        // Request the report. Use the ID that the request returns to
        // check for the completion of the report.

        static string RequestReport(ReportRequest report)
        {
            SubmitGenerateReportRequest request = new SubmitGenerateReportRequest();
            SubmitGenerateReportResponse response = new SubmitGenerateReportResponse();

            try
            {
                // Set the header information.

                request.DeveloperToken = m_token;
                request.UserName = m_username;
                request.Password = m_password;

                // Set the request information.

                request.ReportRequest = report;

                response = reportingService.SubmitGenerateReport(request);
            }
            catch (FaultException<collectBingAdsData.BingAds.Reporting.AdApiFaultDetail> fault)
            {
                // Log this fault.

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

                foreach (collectBingAdsData.BingAds.Reporting.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<collectBingAdsData.BingAds.Reporting.ApiFaultDetail> fault)
            {
                // Log this fault.

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

                foreach (collectBingAdsData.BingAds.Reporting.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 2004: // ReportingServiceNoCompleteDataAvaliable
                            Console.WriteLine("The report cannot request complete data because " +
                                "complete data is not available based on the specified " +
                                "aggregation, scope, and time period values.");
                            break;

                        case 2007: // ReportingServiceInvalidReportAggregation
                            Console.WriteLine("The requested aggregation is not valid for the " +
                                "specified reporting period.");
                            break;

                        case 2008: // ReportingServiceInvalidReportTimeSelection
                            Console.WriteLine("The report time period is not valid.");
                            break;

                        case 2009: // ReportingServiceInvalidCustomDateRangeStart
                            Console.WriteLine("The start date of the custom date range specified " +
                                "in the report time period is not valid.");
                            break;

                        case 2010: // ReportingServiceInvalidCustomDateRangeEnd
                            Console.WriteLine("The end date of the custom date range specified " +
                                "in the report time period is not valid.");
                            break;

                        case 2011: // ReportingServiceEndDateBeforeStartDate
                            Console.WriteLine("The end date of the custom date range specified " +
                                "in the report time period cannot be earlier than the start date.");
                            break;

                        case 2015: // ReportingServiceRequiredColumnsNotSelected
                            Console.WriteLine("The report request does not include all of the " +
                                "required columns.");
                            break;

                        case 2016: // ReportingServiceDuplicateColumns
                            Console.WriteLine("The list or report columns contains duplicate " +
                                "columns. Please ensure that there is only one {0} column.",
                                error.Details);
                            break;

                        case 2017: // ReportingServiceNoMeasureSelected
                            Console.WriteLine("The list or report columns must include one or " +
                                "more KPI columns such as Clicks and Impressions.");
                            break;

                        case 2028: // ReportingServiceInvalidAccountThruAdGroupReportScope
                            Console.WriteLine("The report scope cannot be null or empty.");
                            break;

                        case 2034: // ReportingServiceInvalidTimePeriodColumnForSummaryReport
                            Console.WriteLine("When the report aggregation type is summary, " +
                                "you cannot include TimePeriod as a report column.");
                            break;

                        default:
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                foreach (collectBingAdsData.BingAds.Reporting.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.ReportRequestId;
        }

        private static CampaignPerformanceReportRequest buildCampaignPerformanceRequest(long accountID, long campaignID)
        {
            CampaignPerformanceReportRequest request = new CampaignPerformanceReportRequest();
            request.Aggregation = ReportAggregation.Daily;

            request.Columns = new[] { 
                CampaignPerformanceReportColumn.AccountName, 
                CampaignPerformanceReportColumn.Impressions, 
                CampaignPerformanceReportColumn.Clicks, 
                CampaignPerformanceReportColumn.Conversions, 
                CampaignPerformanceReportColumn.ConversionRate
            };

            request.Format = ReportFormat.Csv;

            request.Scope = new AccountThroughCampaignReportScope()
            {
                AccountIds = accountIDs,
                Campaigns = new[] {
                    new CampaignReportScope {
                        CampaignId = campaignID,
                        ParentAccountId = accountID

                    }
                }
            };

            request.Time = new ReportTime()
            {
                PredefinedTime = ReportTimePeriod.Yesterday
            };
            return request;
        }

        private static KeywordPerformanceReportRequest buildKeywordPerformanceRequest(long accountID, long campaignID)
        {
            KeywordPerformanceReportRequest report = new KeywordPerformanceReportRequest();

            report.Format = ReportFormat.Xml;
            report.ReportName = "My Keyword Performance Report";
            report.ReturnOnlyCompleteData = true;
            report.Aggregation = ReportAggregation.Daily;

            report.Scope = new AccountThroughAdGroupReportScope()
            {
                AccountIds = null,
                AdGroups = null,
                Campaigns = new[] {
                    new CampaignReportScope {
                        CampaignId = accountID,
                        ParentAccountId = campaignID
                    }
                }
            };

            report.Time = new ReportTime()
            {
                //CustomDateRangeStart = new Date()
                //{
                //    Month = 2,
                //    Day = 1,
                //    Year = 2012
                //},
                //CustomDateRangeEnd = new Date()
                //{
                //    Month = 2,
                //    Day = 15,
                //    Year = 2012
                //},
                PredefinedTime = ReportTimePeriod.Yesterday
            };

            report.Filter = new KeywordPerformanceReportFilter()
            {
                DeviceType = DeviceTypeReportFilter.Computer |
                    DeviceTypeReportFilter.SmartPhone
            };

            report.Columns = new[] {
                    KeywordPerformanceReportColumn.TimePeriod,
                    KeywordPerformanceReportColumn.AccountId,
                    KeywordPerformanceReportColumn.CampaignId,
                    KeywordPerformanceReportColumn.Keyword,
                    KeywordPerformanceReportColumn.KeywordId,
                    KeywordPerformanceReportColumn.DeviceType,
                    KeywordPerformanceReportColumn.BidMatchType,
                    KeywordPerformanceReportColumn.Clicks,
                    KeywordPerformanceReportColumn.Impressions,
                    KeywordPerformanceReportColumn.Ctr,
                    KeywordPerformanceReportColumn.AverageCpc,
                    KeywordPerformanceReportColumn.Spend,
                    KeywordPerformanceReportColumn.QualityScore
                };

            return report;
        }

        private static void getCampaignsByAccount(long accountID)
        {
        }

        private static void getAccountsByCutomer(long customerID)
        {
        }
    }
}

我被困在如何从API获取报告,任何帮助将不胜感激。

更新:听起来很傻,但传入的广告系列ID不正确,感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您的代码会告诉您出现此错误的原因;

private static ReportingServiceClient reportingService = null;
response = reportingService.SubmitGenerateReport(request);

您正在尝试访问SubmitGenerateReport值的null方法。你不能这样做。你应该先把它初始化。

答案 1 :(得分:0)

传入错误的数据。我希望错误信息更具描述性,而不仅仅是内部错误。