public DownloadCampaignsByCampaignIdsResponse TryDownloadCampaignsByCampaignIds(
     ApiAuthentication auth,
     CampaignScope[] campaigns,
     long accountId,
     long?customerId,
     DataScope dataScope,
     BulkDownloadEntity entities,
     CompressionType compressionType   = CompressionType.Zip,
     DownloadFileType downloadFileType = DownloadFileType.Tsv,
     string formatVersion       = "4.0",
     DateTime?lastSyncTimeInUTC = null,
     DateTime?start             = null,
     DateTime?end = null)
 {
     return(MethodHelper.TryGet(DownloadCampaignsByCampaignIds, this,
                                auth,
                                campaigns,
                                accountId,
                                customerId,
                                dataScope,
                                entities,
                                compressionType,
                                downloadFileType,
                                formatVersion,
                                lastSyncTimeInUTC,
                                start,
                                end));
 }
        public async Task <DownloadCampaignsByCampaignIdsResponse> DownloadCampaignsByCampaignIdsAsync(
            ApiAuthentication auth,
            CampaignScope[] campaigns,
            long accountId,
            long?customerId,
            DataScope dataScope,
            BulkDownloadEntity entities,
            CompressionType compressionType   = CompressionType.Zip,
            DownloadFileType downloadFileType = DownloadFileType.Tsv,
            string formatVersion       = "4.0",
            DateTime?lastSyncTimeInUTC = null,
            DateTime?start             = null,
            DateTime?end = null)
        {
            var request = new DownloadCampaignsByCampaignIdsRequest
            {
                CustomerId                = string.Format("{0}", customerId),
                CustomerAccountId         = string.Format("{0}", accountId),
                Campaigns                 = campaigns,
                CompressionType           = compressionType,
                DataScope                 = dataScope,
                DownloadFileType          = downloadFileType,
                Entities                  = entities,
                FormatVersion             = formatVersion,
                LastSyncTimeInUTC         = lastSyncTimeInUTC,
                PerformanceStatsDateRange = BuildDateRange(start, end)
            };

            try
            {
                SetAuthHelper.SetAuth(auth, request);

                return(await Check().DownloadCampaignsByCampaignIdsAsync(request));
            }
            catch (Exception ex)
            {
                Log(new LogEventArgs(ServiceType.Bulk, "DownloadCampaignsByCampaignIdsAsync", ex.Message, new { Request = request }, ex));
            }

            return(null);
        }
Esempio n. 3
0
        // GetDownloadRequestId helper method calls the DownloadCampaignsByAccountIds service operation
        // to request the download identifier.
        private async Task <string> GetDownloadRequestId(long accountId, DataScope dataScope, BulkDownloadEntity entities,
                                                         string formatVersion, DateTime?lastSyncTime, PerformanceStatsDateRange dateRange)
        {
            var request = new DownloadCampaignsByAccountIdsRequest
            {
                AccountIds = new List <long> {
                    accountId
                },
                DataScope                 = dataScope,
                DownloadFileType          = FileFormat,
                Entities                  = entities,
                FormatVersion             = formatVersion,
                LastSyncTimeInUTC         = lastSyncTime,
                PerformanceStatsDateRange = dateRange
            };

            return((await Service.CallAsync(
                        (s, r) => s.DownloadCampaignsByAccountIdsAsync(r), request)).DownloadRequestId);
        }
Esempio n. 4
0
        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                Service = new ServiceClient <IBulkService>(authorizationData);

                // Use the bulk service to download a bulk file.
                #region Download

                const DataScope dataScope = DataScope.EntityData;

                const BulkDownloadEntity entities = BulkDownloadEntity.Ads |
                                                    BulkDownloadEntity.AdGroups |
                                                    BulkDownloadEntity.Campaigns |
                                                    BulkDownloadEntity.Keywords
                ;

                const string formatVersion = "3.0";

                object lastSyncTimeInUtc = GetLastSyncTime(ExtractedFilePath);

                // You may include a non-null date range if the lastSyncTime is null, and the data scope includes
                // either EntityPerformanceData, BidSuggestionsData, or QualityScoreData.

                /*
                 * var performanceStatsDateRange = new PerformanceStatsDateRange
                 *  {
                 *      CustomDateRangeEnd = new Date
                 *          {
                 *              Day = DateTime.Now.Day,
                 *              Month = DateTime.Now.Month,
                 *              Year = DateTime.Now.Year
                 *          },
                 *      CustomDateRangeStart = new Date
                 *          {
                 *              Day = DateTime.Now.Day,
                 *              Month = DateTime.Now.Month,
                 *              Year = DateTime.Now.Year - 1
                 *          }
                 *  };
                 */

                // GetDownloadRequestId helper method calls the corresponding Bing Ads service operation
                // to request the download identifier.
                string downloadRequestId = await GetDownloadRequestId(
                    authorizationData.AccountId,
                    dataScope,
                    entities,
                    formatVersion,
                    (DateTime?)lastSyncTimeInUtc,
                    null
                    );

                OutputStatusMessage(String.Format("Download Request Id: " + downloadRequestId));

                var waitTime        = new TimeSpan(0, 0, 5);
                var downloadSuccess = false;

                // This sample polls every 30 seconds up to 5 minutes.
                // In production you may poll the status every 1 to 2 minutes for up to one hour.
                // If the call succeeds, stop polling. If the call or
                // download fails, the call throws a fault.

                for (int i = 0; i < 10; i++)
                {
                    Thread.Sleep(waitTime);

                    // GetDownloadRequestStatus helper method calls the corresponding Bing Ads service operation
                    // to get the download status.
                    string downloadRequestStatus = await GetDownloadRequestStatus(downloadRequestId);

                    if ((downloadRequestStatus != null) && (downloadRequestStatus == "Completed"))
                    {
                        downloadSuccess = true;
                        break;
                    }
                }

                if (downloadSuccess)
                {
                    // GetDownloadUrl helper method calls the corresponding Bing Ads service operation
                    // to get the download Url.
                    string downloadUrl = await GetDownloadUrl(downloadRequestId);

                    OutputStatusMessage(String.Format("Downloading from {0}\n.", downloadUrl));
                    DownloadFile(downloadUrl, BulkFilePath);
                    OutputStatusMessage(String.Format("The download file was written to {0}.", BulkFilePath));
                }
                else // Pending
                {
                    OutputStatusMessage(String.Format("The request is taking longer than expected.\n" +
                                                      "Save the download request ID ({0}) and try again later.", downloadRequestId));
                }

                #endregion Download

                // You may unzip and update the downloaded bulk file or prepare a new file elsewhere.
                // Changes to the bulk file are not shown here.

                DecompressFile(BulkFilePath, ExtractedFilePath);
                CompressFile(ExtractedFilePath, BulkFilePath);


                // Use the bulk service to upload a bulk file.
                #region Upload

                const ResponseMode responseMode = ResponseMode.ErrorsAndResults;

                var uploadResponse = await GetBulkUploadUrl(responseMode, authorizationData.AccountId);

                string uploadRequestId = uploadResponse.RequestId;
                string uploadUrl       = uploadResponse.UploadUrl;

                OutputStatusMessage(String.Format("Uploading file from {0}.", BulkFilePath));
                OutputStatusMessage(String.Format("Upload Request Id: {0}", uploadRequestId));
                OutputStatusMessage(String.Format("Upload Url: {0}", uploadUrl));

                UploadFile(authorizationData, uploadUrl, BulkFilePath);

                var uploadSuccess = false;

                // This sample polls every 30 seconds up to 5 minutes.
                // In production you may poll the status every 1 to 2 minutes for up to one hour.
                // If the call succeeds, stop polling. If the call or
                // download fails, the call throws a fault.

                for (int i = 0; i < 10; i++)
                {
                    Thread.Sleep(waitTime);

                    // GetUploadRequestStatus helper method calls the corresponding Bing Ads service operation
                    // to get the upload status.
                    string uploadRequestStatus = await GetUploadRequestStatus(uploadRequestId);

                    if ((uploadRequestStatus != null) && ((uploadRequestStatus == "Completed") ||
                                                          (uploadRequestStatus == "CompletedWithErrors")))
                    {
                        uploadSuccess = true;
                        break;
                    }
                }

                if (uploadSuccess)
                {
                    // GetUploadResultFileUrl helper method calls the corresponding Bing Ads service operation
                    // to get the upload result file Url.
                    string uploadResultFileUrl = await GetUploadResultFileUrl(uploadRequestId);

                    DownloadFile(uploadResultFileUrl, UploadResultFilePath);
                    OutputStatusMessage(String.Format("The upload result file was written to {0}.", UploadResultFilePath));
                }
                else // Pending
                {
                    OutputStatusMessage(String.Format("The request is taking longer than expected.\n" +
                                                      "Save the upload ID ({0}) and try again later.", uploadRequestId));
                }

                #endregion Upload
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Bulk service exceptions
            catch (FaultException <Microsoft.BingAds.Bulk.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException <Microsoft.BingAds.Bulk.ApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (WebException ex)
            {
                OutputStatusMessage(ex.Message);

                if (ex.Response != null)
                {
                    OutputStatusMessage("HTTP status code: " + ((HttpWebResponse)ex.Response).StatusCode);
                }
            }
            catch (IOException ex)
            {
                OutputStatusMessage(ex.Message);
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
        // GetDownloadRequestId helper method calls the DownloadCampaignsByAccountIds service operation 
        // to request the download identifier.
        private async Task<string> GetDownloadRequestId(long accountId, DataScope dataScope, BulkDownloadEntity entities,
            string formatVersion, DateTime? lastSyncTime, PerformanceStatsDateRange dateRange)
        {
            var request = new DownloadCampaignsByAccountIdsRequest
            {
                AccountIds = new List<long> { accountId },
                DataScope = dataScope,
                DownloadFileType = FileFormat,
                Entities = entities,
                FormatVersion = formatVersion,
                LastSyncTimeInUTC = lastSyncTime,
                PerformanceStatsDateRange = dateRange
            };

            return (await Service.CallAsync(
                (s, r) => s.DownloadCampaignsByAccountIdsAsync(r), request)).DownloadRequestId;
        }