Microsoft adCenter API Version 8(C#)

最近在Microsoft MSN CHINA实习,从事基于adCenter API的相关开发工作,做点笔记,以便查找。

首先介绍下Microsoft adCenter:

Microsoft adCenter是基于微软强大的技术实力开发的关键字广告营销平台,adCenter拥有独具优势的销售资源,能在微软所属搜索网络(如Bing必应搜索),内容网络(如MSN门户),及微软合作伙伴网络(如Yahoo搜索,Facebook等)上投放基于关键词的广告,助您触达全球广大的目标用户,实现精准高效的网络营销。

基于adcenter 提供的api,客户可以开发自己的管理系统来帮助提高业务效率和公司业绩。

adCenter APIS: The Microsoft adCenter API enables you to programmatically access Microsoft adCenter to create and manage advertising campaigns that are run over the Internet.

adCenter Web Service Addresses:

MSDN PAGE: http://msdn.microsoft.com/en-US/library/dd796925.aspx

Web Service

Address

Ad Intelligence

https://adcenterapi.microsoft.com/Api/Advertiser/v8/CampaignManagement/AdIntelligenceService.svc?wsdl

Administration

https://adcenterapi.microsoft.com/Api/Advertiser/v8/Administration/AdministrationService.svc?wsdl

Campaign Management

https://adcenterapi.microsoft.com/Api/Advertiser/v8/CampaignManagement/CampaignManagementService.svc?wsdl

Customer Billing

https://sharedservices.adcenterapi.microsoft.com/Api/Billing/v8/CustomerBillingService.svc?wsdl

Customer Management

https://sharedservices.adcenterapi.microsoft.com/Api/CustomerManagement/v8/CustomerManagementService.svc?wsdl

Notification

https://sharedservices.adcenterapi.microsoft.com/Api/Notification/v8/NotificationService.svc?wsdl

Optimizer

https://adcenterapi.microsoft.com/Api/Advertiser/v8/Optimizer/OptimizerService.svc?wsdl

Reporting

https://adcenterapi.microsoft.com/Api/Advertiser/v8/Reporting/ReportingService.svc?wsdl

要使用adcenter api,首先你要在项目中增加它的相应api的web service 引用。

EP:

在项目中增加对 adcenter api 中Reporting Service的引用。

项目->添加服务引用->地址中输入:https://adcenterapi.microsoft.com/Api/Advertiser/v8/Reporting/ReportingService.svc?wsdl->点击“前往”->

稍等片刻,就会显示出可以引用的webservice。填写一个命名空间名字,点击 确定 即可成功在项目中添加服务引用。

 

添加成功后,就可以使用相应的功能了。

Request and Download a Report

Page: http://msdn.microsoft.com/en-us/library/aa983033.aspx

Request a Report
  1. Determine the report that you want to request. For a list of reports that you can request, see Report Types.

  2. Create an instance of the report request object. Some of the elements of the report request are required and some are optional. Set the elements as appropriate for your application. The elements of the report request determine, among others, the scope of data to include in the report, the columns of data to include in the report, and whether to generate the report only if all the data is available.

    Note Note

    You must create an instance of one of the objects that derives from the ReportRequest data object; if you try to pass the ReportRequest object to theSubmitGenerateReport operation, the call will fail.

  3. Create an instance of the SubmitGenerateReportRequest object, and set the ReportRequest element to the report request that you selected in step 1.

  4. Call the SubmitGenerateReport operation to submit the request. The operation is an asynchronous operation that returns before the report is created. The operation returns a report request identifier that you use in the following steps to determine when the report completes.

  5. Create an instance of the PollGenerateReportRequest object and set the report request identifier to the identifier returned in the previous step.

  6. Call the PollGenerateReport operation in a loop while the status is Pending. The operation sets the status to Success when the request completes successfully; a status other than Pending or Success indicates that the report failed.

    The length of time that it takes a report request to complete depends on a number of variables, such as the type of report that you requested; the aggregation, scope, and time period values that you specified; the number of expected rows; and the number of requests already in the queue. Because of these variables, it is difficult to determine an appropriate polling interval for all cases. Because most reports should complete within minutes, polling at five to 15-minute intervals should be appropriate for most cases. If the overall polling period exceeds 60 minutes, consider saving the report identifier, exiting the loop, and trying again later.

  7. If the request completes successfully, use the URL in the ReportDownloadUrl element to download the file that contains the report. After getting the download URL, you have five minutes to download the report. If you do not download the report within five minutes of getting the URL, you must poll for a new URL to use to download the report. If you do not download the report within five days, you must request the report again.

  8. The report file is compressed; therefore, you must unzip it to read the report.

Reporting Examples

This topic has not yet been rated Rate this topic
 

The following examples show how to request and download reports by using various coding languages.

The following code example shows how to request and retrieve a keyword performance report by using C#.

public static void GetKeywordPerformanceReport(
    string username,
    string password,
    string appToken,
    string devToken,
    string customerId,
    long[] accountIds,
    string zipFileName)
{
    // Create and initialize the keyword performance report request 
    // object.
    KeywordPerformanceReportRequest request =
        new KeywordPerformanceReportRequest();

    // Specify the language for the report.
    request.Language = ReportLanguage.English;

    // Specify the format of the report.
    request.Format = ReportFormat.Xml;
    request.ReturnOnlyCompleteData = false;
    request.ReportName = "My Keyword Report";
    request.Aggregation = ReportAggregation.Monthly;

    // Specify the timeframe of the report.
#if(USE_PREDEFINED_TIME)
    request.Time = new ReportTime();
    request.Time.PredefinedTime = ReportTimePeriod.LastSixMonths;
    request.Time.CustomDates = null;
    request.Time.CustomDateRangeStart = null;
    request.Time.CustomDateRangeEnd = null;

#elif(USE_DATE_RANGE)
    // Create an instance of the ReportTime class to hold the report date 
    // information.
    request.Time = new ReportTime();

    // Set the start date for the report to one month before today.
    DateTime startDate = DateTime.Today.AddMonths(-1);
    request.Time.CustomDateRangeStart = new Date();
    request.Time.CustomDateRangeStart.Day = startDate.Day;
    request.Time.CustomDateRangeStart.Month = startDate.Month;
    request.Time.CustomDateRangeStart.Year = startDate.Year;

    // Set the end date to today.
    DateTime endDate = DateTime.Today;
    request.Time.CustomDateRangeEnd = new Date();
    request.Time.CustomDateRangeEnd.Day = endDate.Day;
    request.Time.CustomDateRangeEnd.Month = endDate.Month;
    request.Time.CustomDateRangeEnd.Year = endDate.Year;

#elif(USE_CUSTOM_DATES)
    // Create an instance of the ReportTime class to hold the report date
    // information.
    request.Time = new ReportTime();

    // Allocate an array of DateTime structures to hold the report dates.
    request.Time.CustomDates = new Date[2];

    // Create a date for 12/28/2005.
    DateTime tempDate = new DateTime(2005, 12, 28);
    request.Time.CustomDates[0] = new Date();
    request.Time.CustomDates[0].Day = tempDate.Day;
    request.Time.CustomDates[0].Month = tempDate.Month;
    request.Time.CustomDates[0].Year = tempDate.Year;

    // Create a date for one month before today.
    tempDate = DateTime.Today.AddMonths(-1);
    request.Time.CustomDates[1] = new Date();
    request.Time.CustomDates[1].Day = tempDate.Day;
    request.Time.CustomDates[1].Month = tempDate.Month;
    request.Time.CustomDates[1].Year = tempDate.Year;
#endif

    // Specify the columns that will be in the report.
    request.Columns = new KeywordPerformanceReportColumn[7];
    request.Columns[0] = KeywordPerformanceReportColumn.AccountName;
    request.Columns[1] = KeywordPerformanceReportColumn.CampaignName;
    request.Columns[2] = KeywordPerformanceReportColumn.Keyword;
    request.Columns[3] = KeywordPerformanceReportColumn.TimePeriod;
    request.Columns[4] = KeywordPerformanceReportColumn.Impressions;
    request.Columns[5] = KeywordPerformanceReportColumn.Conversions;
    request.Columns[6] = KeywordPerformanceReportColumn.AdId;

    // Specify the scope of the report. This example goes down 
    // only to the account level, but you can request a report for any 
    // number of accounts, ad groups, and campaigns.
    request.Scope = new AccountThroughAdGroupReportScope();
    request.Scope.AccountIds = accountIds;
    request.Scope.AdGroups = null;
    request.Scope.Campaigns = null;

    // Specify the filter for the report. This example requests 
    // only search ads that were displayed in the United States to be in 
    // the report.
    request.Filter = new KeywordPerformanceReportFilter();
    request.Filter.AdDistribution = AdDistributionReportFilter.Search;
    request.Filter.LanguageAndRegion =
        LanguageAndRegionReportFilter.UnitedStates;
    request.Filter.DeliveredMatchType = null;
    request.Filter.Keywords = null;

    // Create and initialize the ReportingServiceClient object.
    ReportingServiceClient service = new ReportingServiceClient();

    // Submit the report request.
    try
    {
        // Create and initialize the QueueReportRequest object.
        SubmitGenerateReportRequest submitRequest = 
            new SubmitGenerateReportRequest();
        submitRequest.ApplicationToken = appToken;
        submitRequest.DeveloperToken = devToken;
        submitRequest.UserName = username;
        submitRequest.Password = password;
        submitRequest.ReportRequest = request;

        // Submit the report request. This will throw an exception if 
        // an error occurs.
        SubmitGenerateReportResponse queueResponse;
        queueResponse = service.SubmitGenerateReport(submitRequest);

        // Poll to get the status of the report until it is complete.
        int waitMinutes = 15;
        int maxWaitMinutes = 120;
        DateTime startTime = DateTime.Now;
        int elapsedMinutes = 0;

        // Initialize the GetReportStatusResponse object to an error in 
        // case an error occurs. The error will be handled below.
        PollGenerateReportResponse pollResponse = null;
        do
        {
            // Wait the specified number of minutes before polling.
            System.Threading.Thread.Sleep(waitMinutes * 60 * 1000);
            elapsedMinutes = DateTime.Now.Subtract(startTime).Minutes;

            // Get the status of the report.
            pollResponse = CheckReportStatus(
                username, 
                password, 
                appToken, 
                devToken, 
                customerId, 
                service, 
                queueResponse.ReportRequestId);

            if (ReportRequestStatusType.Success ==
                pollResponse.ReportRequestStatus.Status)
            {
                // The report is ready.
                break;
            }
            else if (ReportRequestStatusType.Pending ==
                pollResponse.ReportRequestStatus.Status)
            {
                // The report is not ready yet.
                continue;
            }
            else
            {
                // An error occurred.
                break;
            }
        } while (elapsedMinutes < maxWaitMinutes);

        // If the report was created, download it.
        if ((null != pollResponse) &&
            (ReportRequestStatusType.Success ==
            pollResponse.ReportRequestStatus.Status))
        {
            // Download the file.
            DownloadReport(
                pollResponse.ReportRequestStatus.ReportDownloadUrl, 
                zipFileName);
        }

    }

    catch (FaultException<AdApiFaultDetail> fault)
    {
        AdApiFaultDetail faultDetail = fault.Detail;

        // Write the API errors.
        foreach (AdApiError opError in faultDetail.Errors)
        {
            Console.WriteLine(
                String.Format("Error {0}:", opError.Code));
            Console.WriteLine(
                String.Format("\tMessage: \"{0}\"", opError.Message));
        }

    }
    
    catch (FaultException<ApiFaultDetail> fault)
    {
        ApiFaultDetail faultDetail = fault.Detail;

        // Display service operation error information.
        foreach (OperationError opError in faultDetail.OperationErrors)
        {
            Console.Write("Operation error");
            Console.WriteLine(" '{0}' ({1}) encountered.",
                              opError.Message,
                              opError.Code);
        }

        // Display batch error information.
        foreach (BatchError batchError in faultDetail.BatchErrors)
        {
            Console.Write("Batch error");
            Console.Write(" '{0}' ({1}) encountered",
                           batchError.Message,
                           batchError.ErrorCode);
        }

    }

    // Capture exceptions on the client that are unrelated to
    // the adCenter API. An example would be an 
    // out-of-memory condition on the client.
    catch (Exception e)
    {
        Console.WriteLine("Error '{0}' encountered.",
            e.Message);
    }
    finally
    {
        // Make sure you close the service.
        service.Close();
    }
}

public static PollGenerateReportResponse CheckReportStatus(
    string username,
    string password,
    string appToken,
    string devToken,
    string customerId,
    ReportingServiceClient service,
    string reportId)
{
    PollGenerateReportRequest pollRequest =
        new PollGenerateReportRequest();
    pollRequest.ApplicationToken = null;
    pollRequest.DeveloperToken = devToken;
    pollRequest.UserName = username;
    pollRequest.Password = password;
    pollRequest.ReportRequestId = reportId;

    // Get the status of the report.
    return service.PollGenerateReport(pollRequest);
}

public static void DownloadReport(
    string downloadUrl,
    string zipFileName)
{
    // Open a connection to the URL where the report is available.
    HttpWebRequest webRequest =
        (HttpWebRequest)WebRequest.Create(downloadUrl);
    HttpWebResponse response =
        (HttpWebResponse)webRequest.GetResponse();
    Stream httpStream = response.GetResponseStream();

    // Open the report file.
    FileInfo zipFileInfo = new FileInfo(zipFileName);
    if (!zipFileInfo.Directory.Exists)
    {
        zipFileInfo.Directory.Create();
    }
    FileStream fileStream = new FileStream(
        zipFileInfo.FullName,
        FileMode.Create);
    BinaryWriter binaryWriter = new BinaryWriter(fileStream);
    BinaryReader binaryReader = new BinaryReader(httpStream);
    try
    {
        // Read the report and save it to the file.
        int bufferSize = 100000;
        while (true)
        {
            // Read report data from API.
            byte[] buffer = binaryReader.ReadBytes(bufferSize);

            // Write report data to file.
            binaryWriter.Write(buffer);

            // If the end of the report is reached, break out of the 
            // loop.
            if (buffer.Length != bufferSize)
            {
                break;
            }
        }
    }
    finally
    {
        // Clean up.
        binaryWriter.Close();
        binaryReader.Close();
        fileStream.Close();
        httpStream.Close();
    }
}

上面是官方给的例子。下面的是基于官方的修改的一个类。增加了一些功能,如下载进度,保存路径,日志记录等。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KeywordDataDownload.adCenter.ReportingService;
using System.ServiceModel;
using System.IO;
using System.Web;
using System.Net;
using System.Data;

namespace KeywordDataDownload
{
    /// <summary>
    /// 请求下载数据类 || Request & Download Data Class
    /// </summary>
    public class RequestAndDownloadReport
    {
        /// <summary>
        /// 是否是自定义下载日期,默认为false || True->自定义下载日期;False->系统预定义日期
        /// </summary>
        public static bool isCustom = false;
        /// <summary>
        /// 自定义日期开始时间,必须比结束日期小 || Custom Start Date
        /// </summary>
        public static DateTime startTime = new DateTime();
        /// <summary>
        /// 自定义日期结束时间,必须比开始日期大 || Custom End Date
        /// </summary>
        public static DateTime endTime = new DateTime();
        /// <summary>
        /// 下载的文件的大小 || Size of the file being downloaded
        /// </summary>
        public static long fileTotalLenght = 0;
        /// <summary>
        /// 完成下载的大小 || Size of compeleted part
        /// </summary>
        public static long fileCompeletedLenght = 0;

        /// <summary>
        /// 返回下载的zip文件全路径 || Return the full path of the downloaded zip file
        /// </summary>
        /// <param name="username">API UserName</param>
        /// <param name="password">API UserPassword</param>
        /// <param name="devToken">API UserDevToken</param>
        /// <param name="customerId">CustomerID</param>
        /// <param name="accountIds">要下载数据的AccountIDS</param>
        /// <returns></returns>
        public string ReuestAndDownloadReportFile(string username, string password, string devToken, string customerId,long[] accountIds)
        {
            string appToken = null;
            string zipFileName = "";
            zipFileName = Form1.exePath + @"\zipfile\" + username.ToString() + "\\" + accountIds[0].ToString() + "_Report.zip";

            zipFileName = GetKeywordPerformanceReport(username, password, appToken, devToken, customerId, accountIds, zipFileName);
            return zipFileName;
        }

        /// <summary>
        /// 返回下载的zip文件全路径 || Return the full path of the downloaded zip file
        /// </summary>
        /// <param name="username">API UserName</param>
        /// <param name="password">API UserPassword</param>
        /// <param name="appToken">API appToken,at this moment set null to it</param>
        /// <param name="devToken">API UserDevToken</param>
        /// <param name="customerId">CustomerID</param>
        /// <param name="accountIds">要下载数据的AccountIDS</param>
        /// <param name="zipFileName">保存的zip文件的全路径</param>
        /// <returns>zip文件全路径</returns>
        public string GetKeywordPerformanceReport(string username,string password,string appToken,string devToken,string customerId,long[] accountIds, string zipFileName)
        {
            // Create and initialize the keyword performance report request object.
            KeywordPerformanceReportRequest request = new KeywordPerformanceReportRequest();

            // Specify the language for the report.
            request.Language = ReportLanguage.English;

            // Specify the format of the report.
            request.Format = ReportFormat.Xml;
            request.ReturnOnlyCompleteData = false;
            request.ReportName = "My KeywordPerformance Report";
            request.Aggregation = ReportAggregation.Daily;

            // Specify the time Range of the report.

            if (isCustom == false)
            {
                request.Time = new ReportTime();
                request.Time.PredefinedTime = ReportTimePeriod.Yesterday;
                // request.Time.CustomDates = null;
                request.Time.CustomDateRangeStart = null;
                request.Time.CustomDateRangeEnd = null;
            }
            else
            {
                // Create an instance of the ReportTime class to hold the report date information.
                request.Time = new ReportTime();

                // Set the start date for the report to one month before today.
                request.Time.CustomDateRangeStart = new Date();
                request.Time.CustomDateRangeStart.Day = startTime.Day;
                request.Time.CustomDateRangeStart.Month = startTime.Month;
                request.Time.CustomDateRangeStart.Year = startTime.Year;

                // Set the end date to today.
                request.Time.CustomDateRangeEnd = new Date();
                request.Time.CustomDateRangeEnd.Day = endTime.Day;
                request.Time.CustomDateRangeEnd.Month = endTime.Month;
                request.Time.CustomDateRangeEnd.Year = endTime.Year;
            }

            // Specify the columns that will be in the report.
            request.Columns = new KeywordPerformanceReportColumn[29];
            request.Columns[0] = KeywordPerformanceReportColumn.AccountName;//
            request.Columns[1] = KeywordPerformanceReportColumn.CampaignName;//
            request.Columns[2] = KeywordPerformanceReportColumn.AdGroupName;
            request.Columns[3] = KeywordPerformanceReportColumn.AdDistribution;
            request.Columns[4] = KeywordPerformanceReportColumn.DeviceType;
            request.Columns[5] = KeywordPerformanceReportColumn.Keyword;//
            request.Columns[6] = KeywordPerformanceReportColumn.BidMatchType;
            request.Columns[7] = KeywordPerformanceReportColumn.CurrentMaxCpc;
            request.Columns[8] = KeywordPerformanceReportColumn.LanguageAndRegion;
            request.Columns[9] = KeywordPerformanceReportColumn.DestinationUrl;
            request.Columns[10] = KeywordPerformanceReportColumn.AccountNumber;
            request.Columns[11] = KeywordPerformanceReportColumn.AccountId;
            request.Columns[12] = KeywordPerformanceReportColumn.AdGroupId;
            request.Columns[13] = KeywordPerformanceReportColumn.CampaignId;
            request.Columns[14] = KeywordPerformanceReportColumn.CurrencyCode;
            request.Columns[15] = KeywordPerformanceReportColumn.AdType;
            request.Columns[16] = KeywordPerformanceReportColumn.PricingModel;
            request.Columns[17] = KeywordPerformanceReportColumn.QualityScore;
            request.Columns[18] = KeywordPerformanceReportColumn.KeywordRelevance;
            request.Columns[19] = KeywordPerformanceReportColumn.LandingPageRelevance;
            request.Columns[20] = KeywordPerformanceReportColumn.Conversions;//
            request.Columns[21] = KeywordPerformanceReportColumn.TimePeriod;//
            request.Columns[22] = KeywordPerformanceReportColumn.Impressions;//
            request.Columns[23] = KeywordPerformanceReportColumn.AdId;//
            request.Columns[24] = KeywordPerformanceReportColumn.Clicks;
            request.Columns[25] = KeywordPerformanceReportColumn.Ctr;
            request.Columns[26] = KeywordPerformanceReportColumn.AverageCpc;
            request.Columns[27] = KeywordPerformanceReportColumn.Spend;
            request.Columns[28] = KeywordPerformanceReportColumn.AveragePosition;
            //request.Columns[29] = KeywordPerformanceReportColumn.KeywordId;

            // Specify the scope of the report.
            request.Scope = new AccountThroughAdGroupReportScope();
            request.Scope.AccountIds = accountIds;
            request.Scope.AdGroups = null;
            request.Scope.Campaigns = null;

            #region 不需要设置过滤规则
            // Specify the filter for the report. This example requests 
            // only search ads that were displayed in the United States to be in 
            // the report.
            //request.Filter = new KeywordPerformanceReportFilter();
            //request.Filter.AdDistribution = AdDistributionReportFilter.Search;
            //request.Filter.LanguageAndRegion =
            //    LanguageAndRegionReportFilter.UnitedStates;
            //request.Filter.DeliveredMatchType = null;
            //request.Filter.Keywords = null;
            #endregion

            // Create and initialize the ReportingServiceClient object.
            ReportingServiceClient service = new ReportingServiceClient();

            // Submit the report request.
            try
            {
                // Create and initialize the QueueReportRequest object.
                SubmitGenerateReportRequest submitRequest = new SubmitGenerateReportRequest();
                submitRequest.ApplicationToken = appToken;
                submitRequest.DeveloperToken = devToken;
                submitRequest.UserName = username;
                submitRequest.Password = password;
                submitRequest.ReportRequest = request;

                // Submit the report request. This will throw an exception if an error occurs.
                //SubmitGenerateReportResponse queueResponse;
                string ReportRequId;

                string s = service.SubmitGenerateReport(submitRequest.ApplicationToken,
                    submitRequest.CustomerAccountId, submitRequest.CustomerId, submitRequest.DeveloperToken,
                    submitRequest.Password, submitRequest.UserName, request, out ReportRequId);

                zipFileName = zipFileName.Replace(".zip", "_" + ReportRequId + ".zip");

                // Poll to get the status of the report until it is complete.
                //int waitMinutes = 1;
                int maxWaitMinutes = 120;
                DateTime start_Time = DateTime.Now;
                int elapsedMinutes = 0;

                // Initialize the GetReportStatusResponse object to an error in 
                // case an error occurs. The error will be handled below.
                ReportRequestStatus pollResponse = null;
                do
                {
                    // Wait the specified number of minutes before polling.
                    //System.Threading.Thread.Sleep(waitMinutes * 60 * 1000);
                    elapsedMinutes = DateTime.Now.Subtract(start_Time).Minutes;

                    // Get the status of the report.
                    pollResponse = CheckReportStatus(username, password, appToken, devToken, customerId, service, ReportRequId);

                    if (ReportRequestStatusType.Success == pollResponse.Status)
                    {
                        // The report is ready.
                        break;
                    }
                    else
                    {
                        if (ReportRequestStatusType.Pending == pollResponse.Status)
                        {
                            // The report is not ready yet.
                            continue;
                        }
                        else
                        {
                            // An error occurred.
                            break;
                        }
                    }
                } while (elapsedMinutes < maxWaitMinutes);

                // If the report was created, download it.
                if ((null != pollResponse) && (ReportRequestStatusType.Success == pollResponse.Status))
                {
                    // Download the file.
                    DownloadReport(pollResponse.ReportDownloadUrl, zipFileName);
                }

            }

            catch (FaultException<AdApiFaultDetail> fault)
            {
                AdApiFaultDetail faultDetail = fault.Detail;

                // Write the API errors.
                foreach (AdApiError opError in faultDetail.Errors)
                {
                    Form1.logString = Form1.rtDateTimeToString() + String.Format("Error {0}:", opError.Code) + "\r\n\r\n" + String.Format("\tMessage: \"{0}\"", opError.Message);
                    Form1.logString += "\r\n\r\n";
                    Form1.myLogWriter.WriteLine(Form1.logString);
                    service.Close();
                    return "-1";
                }

            }

            catch (FaultException<ApiFaultDetail> fault)
            {
                ApiFaultDetail faultDetail = fault.Detail;

                // Display service operation error information.
                foreach (OperationError opError in faultDetail.OperationErrors)
                {
                    Form1.logString = Form1.rtDateTimeToString() + string.Format(" '{0}' ({1}) encountered.", opError.Message, opError.Code);
                    Form1.logString += "\r\n\r\n";
                    Form1.myLogWriter.WriteLine(Form1.logString);
                    service.Close();
                    return "-1";
                }

                // Display batch error information.
                foreach (BatchError batchError in faultDetail.BatchErrors)
                {
                    Form1.logString = Form1.rtDateTimeToString() + string.Format(" '{0}' ({1}) encountered", batchError.Message, batchError.ErrorCode);
                    Form1.logString += "\r\n\r\n";
                    Form1.myLogWriter.WriteLine(Form1.logString);
                    service.Close();
                    return "-1";
                }

            }

            // Capture exceptions on the client that are unrelated to the adCenter API. An example would be an out-of-memory condition on the client.
            catch (Exception e)
            {
                Form1.logString = Form1.rtDateTimeToString() + string.Format("Error '{0}' encountered.", e.Message);
                Form1.logString += "\r\n\r\n";
                Form1.myLogWriter.WriteLine(Form1.logString);
                service.Close();
                return "-1";
            }
            finally
            {
                // Make sure you close the service.
                service.Close();
            }
            return zipFileName;
        }

        /// <summary>
        /// 检查报告准备状况 || check the status of the report you are going to download
        /// </summary>
        /// <param name="username">API USERNAME</param>
        /// <param name="password">API USERPASSWORD</param>
        /// <param name="appToken">appToken</param>
        /// <param name="devToken">devToken</param>
        /// <param name="customerId">CustomerID</param>
        /// <param name="service">service</param>
        /// <param name="reportId">reportId</param>
        /// <returns>返回报告的准备情况</returns>
        public  ReportRequestStatus CheckReportStatus(string username,string password,string appToken,string devToken,string customerId,ReportingServiceClient service,string reportId)
        {
            PollGenerateReportRequest pollRequest = new PollGenerateReportRequest();

            pollRequest.ApplicationToken = null;
            pollRequest.DeveloperToken = devToken;
            pollRequest.UserName = username;
            pollRequest.Password = password;
            pollRequest.ReportRequestId = reportId;

            // Get the status of the report.
            ReportRequestStatus strReportRequestStatus;
            string s = service.PollGenerateReport(pollRequest.ApplicationToken, pollRequest.CustomerAccountId, 
                pollRequest.CustomerId, pollRequest.DeveloperToken, pollRequest.Password, pollRequest.UserName, reportId, out strReportRequestStatus);
            return strReportRequestStatus;
        }


        /// <summary>
        /// 下载报告到本地 || download the report file
        /// </summary>
        /// <param name="downloadUrl">下载报告的Url</param>
        /// <param name="zipFileName">保存路径</param>
        public  void DownloadReport(string downloadUrl, string zipFileName)
        {
            // Open a connection to the URL where the report is available.
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(downloadUrl);
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            Stream httpStream = response.GetResponseStream();
            fileTotalLenght = response.ContentLength;
            fileCompeletedLenght = 0;

            // Open the report file.
            FileInfo zipFileInfo = new FileInfo(zipFileName);
            if (!zipFileInfo.Directory.Exists)
            {
                zipFileInfo.Directory.Create();
            }
            if (File.Exists(zipFileName))
            {
                File.Delete(zipFileName);
            }
            FileStream fileStream = new FileStream(zipFileInfo.FullName,FileMode.Create);
            BinaryWriter binaryWriter = new BinaryWriter(fileStream);
            BinaryReader binaryReader = new BinaryReader(httpStream);
            try
            {
                // Read the report and save it to the file.
                //int bufferSize = 100000;
                int bufferSize = 1024;
                while (true)
                {
                    // Read report data from API.
                    byte[] buffer = binaryReader.ReadBytes(bufferSize);

                    // Write report data to file.
                    binaryWriter.Write(buffer);

                    fileCompeletedLenght += buffer.Length;

                    // If the end of the report is reached, break out of the loop.
                    if (buffer.Length != bufferSize)
                    {
                        break;
                    }
                }
            }
            finally
            {
                // Clean up.
                binaryWriter.Close();
                binaryReader.Close();
                fileStream.Close();
                httpStream.Close();
            }
        }
    }
}

下载是在另外的线程中进行的,主线程中通过监视fileCompeletedLenght的值可以获得当前文件的下载进度。

使用adcenter api你需要有相应的权限,即申请devToken。

在程序的开发中,多线程的使用带来了很大的益处,因为下载和解析数据需要较长的时间,主线程可以用来向用户展示进度以获得更好的用户体验。

下载到的xml文件的格式如下:

Page: http://msdn.microsoft.com/en-US/library/cc540178.aspx

<?xml version="1.0" encoding="utf-8"?>
<Report xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns="http://adcenter.microsoft.com/advertiser/reporting/v5/XMLSchema"
        ReportName="SampleKeywordPerformanceReport"
        ReportTime="{From 03/01/2009 To 03/31/2009}"
        TimeZone="(GMT-08:00) Pacific Time (US &amp; Canada); Tijuana"
        ReportAggregation="Summary"
        LastCompletedAvailableHour="4/1/2009 4:00:00 AM"
        LastCompletedAvailableDay="4/1/2009 4:00:00 AM"
        PotentialIncompleteData="false">
  <AdPerformanceReportColumns>
    <Column name="AccountName" />
    <Column name="Keyword" />
    <Column name="GregorianDate" />
    <Column name="LanguageAndRegion" />
    <Column name="CampaignName" />
    <Column name="AdGroupName" />
    <Column name="CurrencyCode" />
    <Column name="AdDistribution" />
    <Column name="Impressions" />
    <Column name="Clicks" />
    <Column name="Ctr" />
    <Column name="AverageCpc" />
    <Column name="Spend" />
    <Column name="AveragePosition" />
    <Column name="Conversions" />
    <Column name="ConversionRate" />
    <Column name="CostPerConversion" />
  </AdPerformanceReportColumns>
  <Table>
    <Row>
      <AccountName value="Northwind Traders" />
      <Keyword value="dog toys" />
      <GregorianDate value="3/1/2009" />
      <LanguageAndRegion value="EnglishUnitedStates" />
      <CampaignName value="Northwind Products" />
      <AdGroupName value="Northwind Dog Toys Group" />
      <CurrencyCode value="USD" />
      <AdDistribution value="Search" />
      <Impressions value="11" />
      <Clicks value="0" />
      <Ctr value="0.0000" />
      <AverageCpc value=".00" />
      <Spend value=".00" />
      <AveragePosition value="7.91" />
      <Conversions value="0" />
      <ConversionRate value="" />
      <CostPerConversion value="" />
    </Row>
  </Table>
  <Copyright>©2009 Microsoft Corporation. All rights reserved. </Copyright>
</Report>

OK,今天就到这里。下次讲下zip文件在c#中的解压和xml文件的解析。

2012-04-13 Rex.Wang

转载于:https://www.cnblogs.com/wzh880801/archive/2012/04/13/2446572.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值