Advertisement
Guest User

Untitled

a guest
May 27th, 2015
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.75 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.IO;
  4. using System.Net;
  5. using System.ServiceModel;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Microsoft.BingAds.Reporting;
  9. using Microsoft.BingAds;
  10.  
  11. namespace BingAdsExamplesConsole
  12. {
  13. /// <summary>
  14. /// This example demonstrates how to request and retrieve a keyword performance report.
  15. /// </summary>
  16. public class KeywordPerformance
  17. {
  18. public static ServiceClient<IReportingService> Service;
  19.  
  20. // Specify the file to download the report to. The file is
  21. // compressed so use the .zip file extension.
  22.  
  23. private const string DownloadPath = @"c:\reports\keywordperf.zip";
  24.  
  25.  
  26. public string Description
  27. {
  28. get { return "Reporting | Keyword Performance"; }
  29. }
  30.  
  31. /// <summary>
  32. /// The entry point for the console application.
  33. /// </summary>
  34. /// <param name="args">Arguments are not required for this example.</param>
  35. public static void Main(string[] args)
  36. {
  37. var example = new KeywordPerformance();
  38. Console.WriteLine(example.Description);
  39. try
  40. {
  41.  
  42. // The OAuthHelper class is available for download with the BingAdsExamples solution.
  43.  
  44.  
  45. var authentication = new PasswordAuthentication(
  46. "4wp.reports@gmail.com",
  47. "xpwfN6qA");
  48.  
  49.  
  50. var authorizationData = new AuthorizationData
  51. {
  52. Authentication = authentication,
  53. CustomerId = 11060275,
  54. AccountId = 1588282,
  55. DeveloperToken = "010373853U891838"
  56. };
  57.  
  58. example.RunAsync(authorizationData).Wait();
  59. }
  60. catch (Exception ex)
  61. {
  62. Console.WriteLine(ex.Message);
  63.  
  64. }
  65. }
  66.  
  67. /// <summary>
  68. /// Write to the console by default.
  69. /// </summary>
  70. /// <param name="msg">The message to send as output.</param>
  71. private void OutputStatusMessage(String msg)
  72. {
  73. Console.WriteLine(msg);
  74. }
  75.  
  76. public async Task RunAsync(AuthorizationData authorizationData)
  77. {
  78. try
  79. {
  80. Service = new ServiceClient<IReportingService>(authorizationData);
  81.  
  82. // Build a keyword performance report request, including Format, ReportName, Aggregation,
  83. // Scope, Time, Filter, and Columns.
  84.  
  85. var report = new KeywordPerformanceReportRequest
  86. {
  87. Format = ReportFormat.Tsv,
  88. ReportName = "My Keyword Performance Report",
  89. ReturnOnlyCompleteData = false,
  90. Aggregation = ReportAggregation.Daily,
  91.  
  92. Scope = new AccountThroughAdGroupReportScope
  93. {
  94. AccountIds = new[] { authorizationData.AccountId },
  95. AdGroups = null,
  96. Campaigns = null
  97. },
  98.  
  99. Time = new ReportTime
  100. {
  101. // You may either use a custom date range or predefined time.
  102.  
  103. //CustomDateRangeStart = new Date
  104. // {
  105. // Month = DateTime.Now.Month,
  106. // Day = DateTime.Now.Day,
  107. // Year = DateTime.Now.Year - 1
  108. // },
  109. //CustomDateRangeEnd = new Date
  110. // {
  111. // Month = DateTime.Now.Month,
  112. // Day = DateTime.Now.Day,
  113. // Year = DateTime.Now.Year
  114. // },
  115.  
  116. PredefinedTime = ReportTimePeriod.Yesterday
  117. },
  118.  
  119. // If you specify a filter, results may differ from data you see in the Bing Ads web application
  120. Filter = new KeywordPerformanceReportFilter
  121. {
  122. DeviceType = DeviceTypeReportFilter.Computer |
  123. DeviceTypeReportFilter.SmartPhone
  124. },
  125.  
  126. // Specify the attribute and data report columns.
  127. Columns = new[]
  128. {
  129. KeywordPerformanceReportColumn.TimePeriod,
  130. KeywordPerformanceReportColumn.AccountId,
  131. KeywordPerformanceReportColumn.CampaignId,
  132. KeywordPerformanceReportColumn.Keyword,
  133. KeywordPerformanceReportColumn.KeywordId,
  134. KeywordPerformanceReportColumn.DeviceType,
  135. KeywordPerformanceReportColumn.BidMatchType,
  136. KeywordPerformanceReportColumn.Clicks,
  137. KeywordPerformanceReportColumn.Impressions,
  138. KeywordPerformanceReportColumn.Ctr,
  139. KeywordPerformanceReportColumn.AverageCpc,
  140. KeywordPerformanceReportColumn.Spend,
  141. KeywordPerformanceReportColumn.QualityScore
  142. },
  143.  
  144. // You may optionally sort by any KeywordPerformanceReportColumn, and optionally
  145. // specify the maximum number of rows to return in the sorted report.
  146. Sort = new[]
  147. {
  148. new KeywordPerformanceReportSort
  149. {
  150. SortColumn = KeywordPerformanceReportColumn.Clicks,
  151. SortOrder = SortOrder.Ascending
  152. }
  153. },
  154.  
  155. MaxRows = 10,
  156. };
  157.  
  158. // SubmitGenerateReport helper method calls the corresponding Bing Ads service operation
  159. // to request the report identifier. The identifier is used to check report generation status
  160. // before downloading the report.
  161.  
  162. var reportRequestId = await SubmitGenerateReportAsync(report);
  163.  
  164. OutputStatusMessage("Report Request ID: " + reportRequestId);
  165.  
  166. var waitTime = new TimeSpan(0, 0, 30);
  167. ReportRequestStatus reportRequestStatus = null;
  168.  
  169. // This example polls every 30 seconds up to 5 minutes.
  170. // In production you may poll the status every 1 to 2 minutes for up to one hour.
  171. // If the call succeeds, stop polling. If the call or
  172. // download fails, the call throws a fault.
  173.  
  174. for (int i = 0; i < 10; i++)
  175. {
  176. OutputStatusMessage(String.Format("Will check if the report is ready in {0} seconds: ", waitTime.Seconds));
  177. Thread.Sleep(waitTime);
  178.  
  179. // PollGenerateReport helper method calls the corresponding Bing Ads service operation
  180. // to get the report request status.
  181. reportRequestStatus = await PollGenerateReportAsync(reportRequestId);
  182.  
  183. if (reportRequestStatus.Status == ReportRequestStatusType.Success ||
  184. reportRequestStatus.Status == ReportRequestStatusType.Error)
  185. {
  186. break;
  187. }
  188.  
  189. OutputStatusMessage("The report is not yet ready for download.");
  190. }
  191.  
  192. if (reportRequestStatus != null)
  193. {
  194. if (reportRequestStatus.Status == ReportRequestStatusType.Success)
  195. {
  196. var reportDownloadUrl = reportRequestStatus.ReportDownloadUrl;
  197. OutputStatusMessage(String.Format("Downloading from {0}.", reportDownloadUrl));
  198. OutputStatusMessage("\n");
  199. DownloadFile(reportDownloadUrl, DownloadPath);
  200. OutputStatusMessage(String.Format("The report was written to {0}.", DownloadPath));
  201. }
  202. else if (reportRequestStatus.Status == ReportRequestStatusType.Error)
  203. {
  204. OutputStatusMessage("The request failed. Try requesting the report " +
  205. "later.\nIf the request continues to fail, contact support.");
  206. }
  207. else // Pending
  208. {
  209. OutputStatusMessage(String.Format("The request is taking longer than expected.\n " +
  210. "Save the report ID ({0}) and try again later.", reportRequestId));
  211. }
  212. }
  213. }
  214. // Catch authentication exceptions
  215. catch (OAuthTokenRequestException ex)
  216. {
  217. OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
  218. }
  219. // Catch Reporting service exceptions
  220. catch (FaultException<Microsoft.BingAds.Reporting.AdApiFaultDetail> ex)
  221. {
  222. OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
  223. }
  224. catch (FaultException<Microsoft.BingAds.Reporting.ApiFaultDetail> ex)
  225. {
  226. OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
  227. OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
  228. }
  229. catch (WebException ex)
  230. {
  231. OutputStatusMessage(ex.Message);
  232.  
  233. if (ex.Response != null)
  234. OutputStatusMessage("HTTP status code: " + ((HttpWebResponse)ex.Response).StatusCode);
  235. }
  236. catch (IOException ex)
  237. {
  238. OutputStatusMessage(ex.Message);
  239. }
  240. catch (Exception ex)
  241. {
  242. OutputStatusMessage(ex.Message);
  243. }
  244. }
  245.  
  246. // Request the report and returns the ReportRequestId that can be used to check report
  247. // status and then used to download the report.
  248.  
  249. private async Task<string> SubmitGenerateReportAsync(ReportRequest report)
  250. {
  251. var request = new SubmitGenerateReportRequest
  252. {
  253. ReportRequest = report
  254. };
  255.  
  256. return (await Service.CallAsync((s, r) => s.SubmitGenerateReportAsync(r), request)).ReportRequestId;
  257. }
  258.  
  259. // Checks the status of a report request. Returns a data object that contains both
  260. // report status and download URL.
  261.  
  262. private async Task<ReportRequestStatus> PollGenerateReportAsync(string reportId)
  263. {
  264. var request = new PollGenerateReportRequest
  265. {
  266. ReportRequestId = reportId
  267. };
  268.  
  269. return (await Service.CallAsync((s, r) => s.PollGenerateReportAsync(r), request)).ReportRequestStatus;
  270. }
  271.  
  272. // Using the URL that the PollGenerateReport operation returned,
  273. // send an HTTP request to get the report and write it to the specified
  274. // ZIP file.
  275.  
  276. static void DownloadFile(string reportDownloadUrl, string downloadPath)
  277. {
  278. var request = (HttpWebRequest)WebRequest.Create(reportDownloadUrl);
  279. var response = (HttpWebResponse)request.GetResponse();
  280. var fileInfo = new FileInfo(downloadPath);
  281. Stream responseStream = null;
  282. BinaryWriter binaryWriter = null;
  283. BinaryReader binaryReader = null;
  284.  
  285. // If the folders in the specified path do not exist, create them.
  286.  
  287. if (fileInfo.Directory != null && !fileInfo.Directory.Exists)
  288. {
  289. fileInfo.Directory.Create();
  290. }
  291.  
  292. // Create the ZIP file.
  293.  
  294. var fileStream = new FileStream(fileInfo.FullName, FileMode.Create);
  295.  
  296. try
  297. {
  298. responseStream = response.GetResponseStream();
  299. binaryWriter = new BinaryWriter(fileStream);
  300. if (responseStream != null) binaryReader = new BinaryReader(responseStream);
  301.  
  302. const int bufferSize = 100 * 1024;
  303.  
  304. while (true)
  305. {
  306. // Read report data from download URL.
  307.  
  308. if (binaryReader != null)
  309. {
  310. byte[] buffer = binaryReader.ReadBytes(bufferSize);
  311.  
  312. // Write report data to file.
  313.  
  314. binaryWriter.Write(buffer);
  315.  
  316. // If the end of the report is reached, break out of the loop.
  317.  
  318. if (buffer.Length != bufferSize)
  319. {
  320. break;
  321. }
  322. }
  323. }
  324. }
  325. finally
  326. {
  327. fileStream.Close();
  328. if (responseStream != null) responseStream.Close();
  329. if (binaryReader != null) binaryReader.Close();
  330. if (binaryWriter != null) binaryWriter.Close();
  331. }
  332. }
  333. }
  334. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement