必应广告API C#示例代码无法运行

3

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

错误代码:InternalError <0>
信息:发生了内部错误。
详细信息:[此处为空白]

我还尝试在自己的代码中实现报告服务,但是在以下行出现了“对象引用未设置为对象实例”的错误:

"Object reference not set to an instance of an object" error on this line:

response = reportingService.SubmitGenerateReport(request);

这是我的代码,已删除id/密码/令牌:

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不正确,感谢大家的帮助。


我对这段代码一无所知,但从经验来看,如果您无法运行示例程序,则项目设置很可能存在问题。例如缺少导入或其他问题。 - Jesse Jashinsky
你是正确的,这是一个错误的广告系列ID。 - Greg Burris
2个回答

1

你的代码会告诉你为什么会出现这个错误;

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

您正在尝试访问一个 null 值的 SubmitGenerateReport 方法。这是不可行的。您应该首先对其进行初始化。


我同意你的观点,但有两个问题:1. 我尝试过初始化它,但是得到了相同的错误;2. 这就是微软在示例代码中的写法:http://msdn.microsoft.com/en-US/library/bb671680.aspx - Greg Burris
@GregBurris 我认为这个例子使用了报告服务或其他什么东西。也许你需要在Visual Studio中增加一些设置选项。 - Soner Gönül
你是正确的,它使用了微软服务。可以在 Visual Studio 中使用“服务引用”将其添加到此地址:https://adcenterapi.microsoft.com/Api/Advertiser/v8/Reporting/ReportingService.svc?wsdl - Greg Burris
感谢Soner的帮助,传递的竞选活动id是不正确的。哎呀! - Greg Burris

0

传入了错误的数据。我希望错误信息能够更加详细,而不仅仅是“内部错误”。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接