共用方式為


大量Service Manager

利用 大量服務 ,有效率地管理帳戶中所有行銷活動的廣告群組和廣告。 Bing Ads .NET、JAVA 和 Python SDK 提供類別,以加速下載和上傳大量記錄的生產力。 例如, BulkServiceManager 會將您的下載要求提交至 大量服務、輪詢服務直到完成,然後將檔案下載到本機目錄。 BulkServiceManager也會為您處理一般要求標頭欄位,允許為每個服務指定AuthorizationData物件中的AuthenticationCustomerIdAccountIdDeveloperToken屬性一次。 如需詳細資訊,請 參閱使用 AuthorizationData大量要求 程式碼範例。

注意事項

BulkServiceManager僅適用于 Bing Ads .NET、JAVA 和 Python SDK。 無論您是否使用 SDK,都可以直接使用 大量服務 。 如需詳細資訊,請 參閱大量下載和上傳

大量檔案讀取器和寫入器

您不需要實作自己的檔案剖析器,即可讀取和寫入大量檔案。 您可以使用 BulkFileReaderBulkFileWriter 物件來讀取和寫入 BulkEntity 衍生類別。

注意事項

當您上傳和下載實體而非檔案時, BulkServiceManager 會在背景中使用 BulkFileReaderBulkFileWriter 。 暫存檔會在背景中使用。 如需詳細資訊,請 參閱工作目錄和 BulkServiceManager

例如,假設您想要將下列 展開的文字廣告 記錄寫入大量檔案。

Type,Status,Id,Parent Id,Campaign,Ad Group,Client Id,Modified Time,Title,Text,Text Part 2,Display Url,Destination Url,Promotion,Device Preference,Ad Format Preference,Name,App Platform,App Id,Final Url,Mobile Final Url,Tracking Template,Custom Parameter,Title Part 1,Title Part 2,Title Part 3,Path 1,Path 2
Format Version,,,,,,,,,,,,,,,6.0,,,,,,,,,,,
Expanded Text Ad,Active,,-1111,ParentCampaignNameGoesHere,AdGroupNameGoesHere,ClientIdGoesHere,,,Find New Customers & Increase Sales!,Start Advertising on Contoso Today.,,,,,False,,,,https://www.contoso.com/womenshoesale,https://mobile.contoso.com/womenshoesale,,{_promoCode}=PROMO1; {_season}=summer,Contoso,Quick & Easy Setup,Seemless Integration,seattle,shoe sale

首先,建立 BulkExpandedTextAd 物件,如下列 大量和行銷活動管理實體對應所示。 然後,您可以使用 BulkFileWriter 將 BulkExpandedTextAd 寫入檔案,如下所示。

var bulkFileWriter = new BulkFileWriter(
    filePath: FileDirectory + UploadFileName
);
bulkFileWriter.WriteEntity(bulkExpandedTextAd);
bulkFileWriter.Dispose();
BulkFileWriter bulkFileWriter = new BulkFileWriter(
    new File(FileDirectory + UploadFileName)
);
bulkFileWriter.writeEntity(bulkExpandedTextAd);
bulkFileWriter.close();
bulk_file_writer=BulkFileWriter(
    file_path=FILE_DIRECTORY+UPLOAD_FILE_NAME
)
bulk_file_writer.write_entity(bulk_expanded_text_ad)
bulk_file_writer.close()

以下是使用 BulkFileReader 從本機目錄讀取大量上傳結果檔案的範例。 您可以使用 BulkFileReader 讀取大量檔案,不論是完整下載、部分下載或上傳結果。

var bulkFileReader = new BulkFileReader(
    filePath: bulkFilePath, // Path to the Bulk file
    resultFileType: ResultFileType.Upload, // FullDownload, PartialDownload, or Upload
    fileFormat: DownloadFileType.Csv // Csv or Tsv
);
var resultEntities = bulkFileReader.ReadEntities().ToList();
var expandedTextAdResults = resultEntities.OfType<BulkExpandedTextAd>().ToList();
OutputBulkExpandedTextAds(expandedTextAdResults);
bulkFileReader.Dispose();
BulkFileReader bulkFileReader = new BulkFileReader(
    bulkFilePath, // Path to the Bulk file
    ResultFileType.UPLOAD, // FULL_DOWNLOAD, PARTIAL_DOWNLOAD, or UPLOAD
    DownloadFileType.CSV  // Csv or Tsv
);
BulkEntityIterable resultEntities = bulkFileReader.getEntities();
for (BulkEntity entity : resultEntities) {
    if (entity instanceof BulkExpandedTextAd) {
        outputBulkBulkExpandedTextAds(Arrays.asList((BulkExpandedTextAd) entity));
    }
}
resultEntities.close();
bulkFileReader.close();
def read_entities_from_bulk_file(file_path, result_file_type, file_type):
    with BulkFileReader(file_path=file_path, result_file_type=result_file_type, file_type=file_type) as reader:
        for entity in reader:
            yield entity

def main():
    result_entities=[]
    entities_generator=read_entities_from_bulk_file(
        file_path=bulk_file_path, # Path to the Bulk file
        result_file_type=ResultFileType.upload, # full_download, partial_download, or upload
        file_type='Csv'  # Csv or Tsv
    )
    for entity in entities_generator:
        result_entities.append(entity)
    for entity in download_entities:
        if isinstance(entity, BulkExpandedTextAd):
            output_bulk_expanded_text_ads([entity])

大量和行銷活動管理實體對應

所有透過 BulkServiceManager、BulkFileReader、BulkFileWriter 讀取和寫入大量檔案的物件都衍生自 BulkEntity 基類,例如 BulkCampaign、BulkAdGroup 和 BulkExpandedTextAd。 可能的話,大量物件會利用行銷活動管理物件和值集,例如,下列 BulkExpandedTextAd 包含 Campaign Management API ExpandedTextAd 物件。

var uploadEntities = new List<BulkEntity>();

// Map properties in the Bulk file to the BulkExpandedTextAd
var bulkExpandedTextAd = new BulkExpandedTextAd
{
    // 'Parent Id' column header in the Bulk file
    AdGroupId = adGroupIdKey,
    // 'Ad Group' column header in the Bulk file
    AdGroupName = "AdGroupNameGoesHere",
    // 'Campaign' column header in the Bulk file
    CampaignName = "ParentCampaignNameGoesHere",
    // 'Client Id' column header in the Bulk file
    ClientId = "ClientIdGoesHere",

    // Map properties in the Bulk file to the 
    // ExpandedTextAd object of the Campaign Management service.
    ExpandedTextAd = new ExpandedTextAd
    {
        // 'Ad Format Preference' column header in the Bulk file
        AdFormatPreference = "All",
        // 'Mobile Final Url' column header in the Bulk file
        FinalMobileUrls = new[] {
            // Each Url is delimited by a semicolon (;) in the Bulk file
            "https://mobile.contoso.com/womenshoesale"
        },
        // 'Final Url' column header in the Bulk file
        FinalUrls = new[] {
            // Each Url is delimited by a semicolon (;) in the Bulk file
            "https://www.contoso.com/womenshoesale"
        },
        // 'Id' column header in the Bulk file
        Id = null,
        // 'Path 1' column header in the Bulk file
        Path1 = "seattle",
        // 'Path 2' column header in the Bulk file
        Path2 = "shoe sale",
        // 'Status' column header in the Bulk file
        Status = AdStatus.Active,
        // 'Text' column header in the Bulk file
        Text = "Find New Customers & Increase Sales!",
        // 'Text Part 2' column header in the Bulk file
        TextPart2 = "Start Advertising on Contoso Today.",
        // 'Title Part 1' column header in the Bulk file
        TitlePart1 = "Contoso",
        // 'Title Part 2' column header in the Bulk file
        TitlePart2 = "Quick & Easy Setup",
        // 'Title Part 3' column header in the Bulk file
        TitlePart3 = "Seemless Integration",
        // 'Tracking Template' column header in the Bulk file
        TrackingUrlTemplate = null,
        // 'Custom Parameter' column header in the Bulk file
        UrlCustomParameters = new CustomParameters
        {
            // Each custom parameter is delimited by a semicolon (;) in the Bulk file
            Parameters = new[] {
                new CustomParameter(){
                    Key = "promoCode",
                    Value = "PROMO1"
                },
                new CustomParameter(){
                    Key = "season",
                    Value = "summer"
                },
            }
        },
    },
};

uploadEntities.Add(bulkExpandedTextAd);

var entityUploadParameters = new EntityUploadParameters
{
    Entities = uploadEntities,
    ResponseMode = ResponseMode.ErrorsAndResults,
    ResultFileDirectory = FileDirectory,
    ResultFileName = DownloadFileName,
    OverwriteResultFile = true,
};

var uploadResultEntities = (await bulkServiceManager.UploadEntitiesAsync(entityUploadParameters)).ToList();
List<BulkEntity> uploadEntities = new ArrayList<BulkEntity>();

// Map properties in the Bulk file to the BulkExpandedTextAd
BulkExpandedTextAd bulkExpandedTextAd = new BulkExpandedTextAd();

// 'Parent Id' column header in the Bulk file
bulkExpandedTextAd.setAdGroupId(adGroupIdKey);
// 'Ad Group' column header in the Bulk file
bulkExpandedTextAd.setAdGroupName("AdGroupNameGoesHere");
// 'Campaign' column header in the Bulk file
bulkExpandedTextAd.setCampaignName("ParentCampaignNameGoesHere");
// 'Client Id' column header in the Bulk file
bulkExpandedTextAd.setClientId("ClientIdGoesHere");

// Map properties in the Bulk file to the 
// ExpandedTextAd object of the Campaign Management service.
ExpandedTextAd expandedTextAd = new ExpandedTextAd();
// 'Ad Format Preference' column header in the Bulk file
expandedTextAd.setAdFormatPreference("All");
// 'Mobile Final Url' column header in the Bulk file
// Each Url is delimited by a semicolon (;) in the Bulk file
ArrayOfstring mobileFinalUrls = new ArrayOfstring();            
mobileFinalUrls.getStrings().add("https://mobile.contoso.com/womenshoesale");
expandedTextAd.setFinalMobileUrls(mobileFinalUrls);
// 'Final Url' column header in the Bulk file
// Each Url is delimited by a semicolon (;) in the Bulk file
ArrayOfstring finalUrls = new ArrayOfstring();            
finalUrls.getStrings().add("https://www.contoso.com/womenshoesale");
expandedTextAd.setFinalUrls(finalUrls);
// 'Id' column header in the Bulk file
expandedTextAd.setId(null);
// 'Path 1' column header in the Bulk file
expandedTextAd.setPath1("seattle");
// 'Path 2' column header in the Bulk file
expandedTextAd.setPath2("shoe sale");
// 'Status' column header in the Bulk file
expandedTextAd.setStatus(AdStatus.ACTIVE);
// 'Text' column header in the Bulk file
expandedTextAd.setText("Find New Customers & Increase Sales!");
// 'Text Part 2' column header in the Bulk file
expandedTextAd.setTextPart2("Start Advertising on Contoso Today.");
// 'Title Part 1' column header in the Bulk file
expandedTextAd.setTitlePart1("Contoso");
// 'Title Part 2' column header in the Bulk file
expandedTextAd.setTitlePart2("Quick & Easy Setup");
// 'Title Part 3' column header in the Bulk file
expandedTextAd.setTitlePart3("Seemless Integration");
// 'Tracking Template' column header in the Bulk file
expandedTextAd.setTrackingUrlTemplate(null);
// 'Custom Parameter' column header in the Bulk file
// Each custom parameter is delimited by a semicolon (;) in the Bulk file            
CustomParameters customParameters = new CustomParameters();
ArrayOfCustomParameter arrayOfCustomParameter = new ArrayOfCustomParameter();
CustomParameter customParameterA = new CustomParameter();
customParameterA.setKey("promoCode");
customParameterA.setValue("PROMO1");
arrayOfCustomParameter.getCustomParameters().add(customParameterA);
CustomParameter customParameterB = new CustomParameter();
customParameterB.setKey("season");
customParameterB.setValue("summer");
arrayOfCustomParameter.getCustomParameters().add(customParameterB);
customParameters.setParameters(arrayOfCustomParameter);
expandedTextAd.setUrlCustomParameters(customParameters);

bulkExpandedTextAd.setExpandedTextAd(expandedTextAd);

uploadEntities.add(bulkExpandedTextAd);

EntityUploadParameters entityUploadParameters = new EntityUploadParameters();
entityUploadParameters.setEntities(uploadEntities);
entityUploadParameters.setOverwriteResultFile(true);
entityUploadParameters.setResultFileDirectory(new File(FileDirectory));
entityUploadParameters.setResultFileName(ResultFileName);
entityUploadParameters.setResponseMode(ResponseMode.ERRORS_AND_RESULTS);

BulkEntityIterable uploadResultEntities = bulkServiceManager.uploadEntitiesAsync(
    entityUploadParameters, 
    null, 
    null
).get();
# Map properties in the Bulk file to the BulkExpandedTextAd
bulk_expanded_text_ad=BulkExpandedTextAd()

# 'Parent Id' column header in the Bulk file
bulk_expanded_text_ad.ad_group_id=AD_GROUP_ID_KEY
# 'Ad Group' column header in the Bulk file
bulk_expanded_text_ad.AdGroupName='AdGroupNameGoesHere'
# 'Campaign' column header in the Bulk file
bulk_expanded_text_ad.CampaignName='ParentCampaignNameGoesHere'
# 'Client Id' column header in the Bulk file
bulk_expanded_text_ad.ClientId='ClientIdGoesHere'

# Map properties in the Bulk file to the 
# ExpandedTextAd object of the Campaign Management service.
expanded_text_ad=set_elements_to_none(campaign_service.factory.create('ExpandedTextAd'))
# 'Ad Format Preference' column header in the Bulk file
expanded_text_ad.AdFormatPreference='All'
# 'Mobile Final Url' column header in the Bulk file
# Each Url is delimited by a semicolon (;) in the Bulk file
mobile_final_urls=campaign_service.factory.create('ns3:ArrayOfstring')
mobile_final_urls.string.append('https://mobile.contoso.com/womenshoesale')
expanded_text_ad.FinalUrls=mobile_final_urls
# 'Final Url' column header in the Bulk file
# Each Url is delimited by a semicolon (;) in the Bulk file
final_urls=campaign_service.factory.create('ns3:ArrayOfstring')
final_urls.string.append('https://www.contoso.com/womenshoesale')
expanded_text_ad.FinalUrls=final_urls
# 'Id' column header in the Bulk file
expanded_text_ad.Id=None
# 'Path 1' column header in the Bulk file
expanded_text_ad.Path1='seattle'
# 'Path 2' column header in the Bulk file
expanded_text_ad.Path2='shoe sale'
# 'Status' column header in the Bulk file
expanded_text_ad.Status='Active'
# 'Text' column header in the Bulk file
expanded_text_ad.Text='Find New Customers & Increase Sales!'
# 'Text Part 2' column header in the Bulk file
expanded_text_ad.TextPart2='Start Advertising on Contoso Today.'
# 'Title Part 1' column header in the Bulk file
expanded_text_ad.TitlePart1='Contoso'
# 'Title Part 2' column header in the Bulk file
expanded_text_ad.TitlePart2='Quick & Easy Setup'
# 'Title Part 3' column header in the Bulk file
expanded_text_ad.TitlePart3='Seemless Integration'
# 'Tracking Template' column header in the Bulk file
expanded_text_ad.TrackingUrlTemplate=None
# 'Custom Parameter' column header in the Bulk file
# Each custom parameter is delimited by a semicolon (;) in the Bulk file            
custom_parameters=set_elements_to_none(campaign_service.factory.create('CustomParameters'))
array_of_custom_parameter=campaign_service.factory.create('ArrayOfCustomParameter')
custom_parameter_a=set_elements_to_none(campaign_service.factory.create('CustomParameter'))
custom_parameter_a.Key='promoCode'
custom_parameter_a.Value='PROMO1'
array_of_custom_parameter.CustomParameter.append(custom_parameter_a)
custom_parameter_b=set_elements_to_none(campaign_service.factory.create('CustomParameter'))
custom_parameter_b.Key='season'
custom_parameter_b.Value='summer'
array_of_custom_parameter.CustomParameter.append(custom_parameter_b)
custom_parameters.Parameters=array_of_custom_parameter
expanded_text_ad.UrlCustomParameters=custom_parameters

bulk_expanded_text_ad.ad=expanded_text_ad

upload_entities.append(bulk_expanded_text_ad)

entity_upload_parameters=EntityUploadParameters(
    entities=upload_entities,
    overwrite_result_file=True,
    result_file_directory=FILE_DIRECTORY,
    result_file_name=RESULT_FILE_NAME,
    response_mode='ErrorsAndResults'
)

upload_result_entities=bulk_service_manager.upload_entities(
    entity_upload_parameters=entity_upload_parameters, 
    progress=None
)

使用 delete_value 更新

若要移除現有的設定,您不應該將空字串 (「」) 寫入至大量檔案,因為大量服務會忽略這類字串。 使用保留的 「delete_value」 字串來刪除或重設選擇性欄位的值。 如果您在選擇性欄位中使用保留的 「delete_value」 字串,則會刪除先前的設定。 例如,如果您將展開文字廣告記錄的 [自訂參數] 欄位設定為 [delete_value],則所有先前的自訂參數都會從展開的文字廣告中刪除。 同樣地,如果您將展開文字廣告記錄的 [追蹤範本] 欄位設定為 [delete_value],則會從展開的文字廣告中刪除先前的追蹤範本。 如需「delete_value」的詳細資訊,請參閱 大量檔案架構 - 使用delete_value更新

BulkFileWriter會在適用的情況下自動寫入「delete_value」。 因為 SDK 會 將行銷活動管理 API 物件對應至大量檔案的內容,所以您無法明確地為具有其他資料類型的屬性設定 「delete_value」 字串。 在這些情況下,您可以使用與透過行銷活動管理 API 更新物件相同的語法。 在下列範例中,將 UrlCustomParameters 設定為空的 CustomParameters 物件,SDK 會在展開文字廣告記錄的 [自訂參數] 欄位中寫入 「delete_value」。 同樣地,藉由將 TrackingUrlTemplate 設定為空字串,SDK 會在展開文字廣告記錄的[追蹤範本] 欄位中寫入 「delete_value」。 ExpandedTextAd物件內的範例語法與您透過「行銷活動管理 API」透過UpdateAds服務作業刪除首碼設定的方式相同。

重要事項

當您建立大量實體時,請勿使用空字串 (「」) 或 「delete_value」 語法。 保留的 「delete_value」 字串僅適用于更新大量記錄。 您不應該設定 屬性,或將它設定為對等的 Null。

var bulkExpandedTextAd = new BulkExpandedTextAd
{
    AdGroupId = adGroupIdKey,
    ExpandedTextAd = new ExpandedTextAd
    {
        Id = expandedTextAdIdKey,
        TrackingUrlTemplate = "",
        UrlCustomParameters = new CustomParameters { }
    },
};
BulkExpandedTextAd bulkExpandedTextAd = new BulkExpandedTextAd();
bulkExpandedTextAd.setAdGroupId(expandedTextAdIdKey);
ExpandedTextAd expandedTextAd = new ExpandedTextAd();
expandedTextAd.setId(adIdKey);
expandedTextAd.setTrackingUrlTemplate("");       
CustomParameters customParameters = new CustomParameters();
expandedTextAd.setUrlCustomParameters(customParameters);
bulkExpandedTextAd.setExpandedTextAd(expandedTextAd);
bulk_expanded_text_ad=BulkExpandedTextAd()
bulk_expanded_text_ad.ad_group_id=AD_GROUP_ID_KEY
expanded_text_ad=set_elements_to_none(campaign_service.factory.create('ExpandedTextAd'))
expanded_text_ad.Id=EXPANDED_TEXT_AD_ID_KEY
expanded_text_ad.TrackingUrlTemplate=''         
custom_parameters=set_elements_to_none(campaign_service.factory.create('CustomParameters'))
expanded_text_ad.UrlCustomParameters=custom_parameters
bulk_expanded_text_ad.ad=expanded_text_ad

下載並上傳

BulkServiceManager支援彈性的大量下載和上傳工作流程。

  • 您可以建立下載或上傳要求, BulkServiceManager 會將您的下載要求提交至大量服務、輪詢服務直到完成,然後將檔案下載到本機目錄。 例如,請參閱 使用 BulkServiceManager 的背景完成

  • 您可以提交下載或上傳要求,然後輪詢直到結果檔案準備好下載為止。 例如,請參閱 使用 BulkServiceManager 提交和下載

  • 如果基於任何原因,您必須從先前的應用程式狀態繼續,您可以使用現有的下載或上傳要求識別碼,並使用它來下載結果檔案。 例如,請參閱 使用 BulkServiceManager 下載結果

不論您是下載並上傳記憶體中的實體,或是自行在檔案中讀取和寫入實體,BulkServiceManager 都會讀取並寫入暫存檔。

使用 BulkServiceManager 完成背景

您可以建立下載或上傳要求, BulkServiceManager 會將您的下載要求提交至大量服務、輪詢服務直到完成,然後將檔案下載到本機目錄。

public async Task RunAsync(AuthorizationData authorizationData)
{
    var bulkServiceManager = new BulkServiceManager(authorizationData);

    var progress = new Progress<BulkOperationProgressInfo>(x =>
        Console.WriteLine(String.Format("{0} % Complete", x.PercentComplete.ToString(CultureInfo.InvariantCulture))));

    var downloadParameters = new DownloadParameters
    {
        CampaignIds = null,
        DataScope = DataScope.EntityData,
        Entities = DownloadEntity.Keywords,
        FileType = DownloadFileType.Csv,
        LastSyncTimeInUTC = null,
        ResultFileDirectory = FileDirectory,
        ResultFileName = ResultFileName,
        OverwriteResultFile = false  // Set this value true if you want to overwrite the same file.
    };

    // Sets the time interval in milliseconds between two status polling attempts. The default value is 5000 (5 seconds).
    bulkServiceManager.StatusPollIntervalInMilliseconds = 5000;
    // Sets the timeout of the HttpClient download operation. The default value is 100000 (100s).
    bulkServiceManager.DownloadHttpTimeout = new TimeSpan(0, 0, 100);

    // You may optionally cancel the DownloadFileAsync operation after a specified time interval. 
    // Pass this object to the DownloadFileAsync operation or specify CancellationToken.None. 
    var tokenSource = new CancellationTokenSource();
    tokenSource.CancelAfter(3600000);

    // The BulkServiceManager will submit your download request to the Bulk service, 
    // poll the service until completed, and download the file to your local directory.

    var resultFile = await bulkServiceManager.DownloadFileAsync(
        parameters: downloadParameters,
        progress: progress,
        cancellationToken: tokenSource.Token
    );

    Console.WriteLine(string.Format("Download result file: {0}\n", resultFile));
}
BulkServiceManager bulkServiceManager = new BulkServiceManager(authorizationData);

Progress<BulkOperationProgressInfo> progress = new Progress<BulkOperationProgressInfo>() {
    @Override
    public void report(BulkOperationProgressInfo value) {
        System.out.println(value.getPercentComplete() + "% Complete\n");
    }
};

DownloadParameters downloadParameters = new DownloadParameters();
downloadParameters.setCampaignIds(null);
ArrayList<DataScope> dataScope = new ArrayList<DataScope>();
dataScope.add(DataScope.ENTITY_DATA);
downloadParameters.setDataScope(dataScope);
downloadParameters.setFileType(FileType);
downloadParameters.setLastSyncTimeInUTC(null);
ArrayList<DownloadEntity> bulkDownloadEntities = new ArrayList<DownloadEntity>();
bulkDownloadEntities.add(DownloadEntity.KEYWORDS);
downloadParameters.setEntities(bulkDownloadEntities);
downloadParameters.setResultFileDirectory(new File(FileDirectory));
downloadParameters.setResultFileName(ResultFileName);
downloadParameters.setOverwriteResultFile(true);    // Set this value true if you want to overwrite the same file.

// Sets the time interval in milliseconds between two status polling attempts. The default value is 5000 (5 seconds).
bulkServiceManager.setStatusPollIntervalInMilliseconds(5000);
// Sets the timeout of the HttpClient download operation. The default value is 100000 (100s).
bulkServiceManager.setDownloadHttpTimeoutInMilliseconds(100000);

// The BulkServiceManager will submit your download request to the Bulk service, 
// poll the service until completed, and download the file to your local directory. 
// You may optionally cancel the downloadFileAsync operation after a specified time interval.
File resultFile = bulkServiceManager.downloadFileAsync(
    downloadParameters, 
    progress, 
    null
).get(3600000, TimeUnit.MILLISECONDS);

System.out.printf("Download result file: %s\n", resultFile.getName());
bulk_service_manager = BulkServiceManager(
    authorization_data=authorization_data, 
    # Sets the time interval in milliseconds between two status polling attempts. 
    # The default value is 5000 (5 seconds).
    poll_interval_in_milliseconds = 5000, 
    environment = ENVIRONMENT,
)
        
download_parameters = DownloadParameters(
    campaign_ids=None,
    data_scope=['EntityData'],
    entities=entities,
    file_type=FILE_TYPE,
    last_sync_time_in_utc=None,
    result_file_directory = FILE_DIRECTORY, 
    result_file_name = DOWNLOAD_FILE_NAME, 
    # Set this value true if you want to overwrite the same file.
    overwrite_result_file = True, 
    # You may optionally cancel the download after a specified time interval.
    timeout_in_milliseconds=3600000 
)

# The BulkServiceManager will submit your download request to the Bulk service, 
# poll the service until completed, and download the file to your local directory.
result_file_path = bulk_service_manager.download_file(
    download_parameters=download_parameters, 
    progress = None
)

print("Download result file: {0}\n".format(result_file_path))

使用 BulkServiceManager 提交和下載

提交下載要求,然後使用 BulkDownloadOperation 結果來追蹤狀態。

public async Task RunAsync(AuthorizationData authorizationData)
{
    var bulkServiceManager = new BulkServiceManager(authorizationData);

    var submitDownloadParameters = new SubmitDownloadParameters
    {
        CampaignIds = null,
        DataScope = DataScope.EntityData,
        Entities = DownloadEntity.Keywords,
        FileType = DownloadFileType.Csv,
        LastSyncTimeInUTC = null
    };

    var bulkDownloadOperation = await bulkServiceManager.SubmitDownloadAsync(submitDownloadParameters);

    // You may optionally cancel the TrackAsync operation after a specified time interval. 
    var tokenSource = new CancellationTokenSource();
    tokenSource.CancelAfter(3600000);

    BulkOperationStatus<DownloadStatus> downloadStatus = await bulkDownloadOperation.TrackAsync(
        null, 
        tokenSource.Token
    );

    var resultFilePath = await bulkDownloadOperation.DownloadResultFileAsync(
        FileDirectory,
        ResultFileName,
        decompress: true,
        overwrite: true // Set this value true if you want to overwrite the same file.
    );   

    Console.WriteLine(String.Format("Download result file: {0}\n", resultFilePath));
}
BulkServiceManager bulkServiceManager = new BulkServiceManager(authorizationData);

SubmitDownloadParameters submitDownloadParameters = new SubmitDownloadParameters();
submitDownloadParameters.setCampaignIds(null);
ArrayList<DataScope> dataScope = new ArrayList<DataScope>();
dataScope.add(DataScope.ENTITY_DATA);
submitDownloadParameters.setDataScope(dataScope);
submitDownloadParameters.setFileType(FileType);
submitDownloadParameters.setLastSyncTimeInUTC(null);
ArrayList<DownloadEntity> bulkDownloadEntities = new ArrayList<DownloadEntity>();
bulkDownloadEntities.add(DownloadEntity.KEYWORDS);
submitDownloadParameters.setEntities(bulkDownloadEntities);

// Submit the download request. You can use the BulkDownloadOperation result to track status yourself using getStatusAsync,
// or use trackAsync to indicate that the application should wait until the download status is completed.

BulkDownloadOperation bulkDownloadOperation = bulkServiceManager.submitDownloadAsync(
    submitDownloadParameters,
    null
).get();

// You may optionally cancel the trackAsync operation after a specified time interval.
BulkOperationStatus<DownloadStatus> downloadStatus = bulkDownloadOperation.trackAsync(
    null
).get(3600000, TimeUnit.MILLISECONDS);

File resultFile = bulkDownloadOperation.downloadResultFileAsync(
    new File(FileDirectory),
    ResultFileName,
    true, // Set this value to true if you want to decompress the ZIP file.
    true,  // Set this value true if you want to overwrite the named file.
    null
).get();

System.out.println(String.format("Download result file: %s\n", resultFile.getName()));
bulk_service_manager = BulkServiceManager(
    authorization_data=authorization_data, 
    poll_interval_in_milliseconds = 5000, 
    environment = ENVIRONMENT,
)

submit_download_parameters = SubmitDownloadParameters(
    data_scope = [ 'EntityData' ],
    entities = [ 'Campaigns', 'AdGroups', 'Keywords', 'Ads' ],
    file_type = 'Csv',
    campaign_ids = None,
    last_sync_time_in_utc = None,
    performance_stats_date_range = None
)

bulk_download_operation = bulk_service_manager.submit_download(submit_download_parameters)

# You may optionally cancel the track() operation after a specified time interval.
download_status = bulk_download_operation.track(timeout_in_milliseconds=3600000)
    
result_file_path = bulk_download_operation.download_result_file(
    result_file_directory = FILE_DIRECTORY, 
    result_file_name = DOWNLOAD_FILE_NAME, 
    decompress = True, 
    overwrite = True, # Set this value true if you want to overwrite the same file.
    timeout_in_milliseconds=3600000 # You may optionally cancel the download after a specified time interval.
)
    
print("Download result file: {0}\n".format(result_file_path))

使用 BulkServiceManager 下載結果

如果基於任何原因,您必須從先前的應用程式狀態繼續,您可以使用現有的下載或上傳要求識別碼,並使用它來下載結果檔案。 追蹤結果,以確保下載狀態已完成。

public async Task RunAsync(AuthorizationData authorizationData)
{
    var bulkServiceManager = new BulkServiceManager(authorizationData);

    var progress = new Progress<BulkOperationProgressInfo>(x =>
        Console.WriteLine(String.Format("{0} % Complete", x.PercentComplete.ToString(CultureInfo.InvariantCulture))));

    // You may optionally cancel the TrackAsync operation after a specified time interval. 
    var tokenSource = new CancellationTokenSource();
    tokenSource.CancelAfter(3600000);

    var bulkDownloadOperation = new BulkDownloadOperation(requestId, authorizationData);

    // Use TrackAsync to indicate that the application should wait to ensure that 
    // the download status is completed.
    var bulkOperationStatus = await bulkDownloadOperation.TrackAsync(null, tokenSource.Token);

    var resultFilePath = await bulkDownloadOperation.DownloadResultFileAsync(
        FileDirectory,
        ResultFileName,
        decompress: true,
        overwrite: true  // Set this value true if you want to overwrite the same file.
    );   

    Console.WriteLine(String.Format("Download result file: {0}", resultFilePath));
    Console.WriteLine(String.Format("Status: {0}", bulkOperationStatus.Status));
    Console.WriteLine(String.Format("TrackingId: {0}\n", bulkOperationStatus.TrackingId));
}
Progress<BulkOperationProgressInfo> progress = new Progress<BulkOperationProgressInfo>() {
    @Override
    public void report(BulkOperationProgressInfo value) {
        System.out.println(value.getPercentComplete() + "% Complete\n");
    }
};

java.lang.String requestId = RequestIdGoesHere;

BulkDownloadOperation bulkDownloadOperation = new BulkDownloadOperation(requestId, authorizationData);

// You may optionally cancel the trackAsync operation after a specified time interval.
BulkOperationStatus<DownloadStatus> downloadStatus = bulkDownloadOperation.trackAsync(
    progress, 
    null
).get(3600000, TimeUnit.MILLISECONDS);

System.out.printf(
    "Download Status:\nPercentComplete: %s\nResultFileUrl: %s\nStatus: %s\n",
    downloadStatus.getPercentComplete(), downloadStatus.getResultFileUrl(), downloadStatus.getStatus()
);

File resultFile = bulkDownloadOperation.downloadResultFileAsync(
    new File(FileDirectory),
    ResultFileName,
    true,    // Set this value to true if you want to decompress the ZIP file
    true,    // Set this value true if you want to overwrite the same file.
    null
).get();

System.out.println(String.format("Download result file: %s", resultFile.getName()));
System.out.println(String.format("Status: %s", downloadStatus.getStatus()));
System.out.println(String.format("TrackingId: %s\n", downloadStatus.getTrackingId()));
request_id = RequestIdGoesHere

bulk_download_operation = BulkDownloadOperation(
    request_id = request_id, 
    authorization_data = authorization_data, 
    poll_interval_in_milliseconds = 5000,
    environment = ENVIRONMENT
)

# Use track() to indicate that the application should wait to ensure that the download status is completed.
# You may optionally cancel the track() operation after a specified time interval.
bulk_operation_status = bulk_download_operation.track(timeout_in_milliseconds=3600000)

result_file_path = bulk_download_operation.download_result_file(
    result_file_directory = FILE_DIRECTORY, 
    result_file_name = DOWNLOAD_FILE_NAME, 
    decompress = True, 
    overwrite = True, # Set this value true if you want to overwrite the same file.
    timeout_in_milliseconds=3600000 # You may optionally cancel the download after a specified time interval.
) 

print("Download result file: {0}\n".format(result_file))
print("Status: {0}\n".format(bulk_operation_status.status))

輪詢和重試

以合理的間隔輪詢下載和上傳結果。 您比任何人都更瞭解您的資料。 例如,如果您下載的帳戶小於一百萬個關鍵字,請考慮以 5 到 20 秒的間隔輪詢。 如果帳戶包含大約一百萬個關鍵字,請考慮在等候五分鐘後,每隔一分鐘輪詢一次。 對於具有大約 400 萬個關鍵字的帳戶,請考慮在等候 10 分鐘後,每隔一分鐘輪詢一次。

BulkServiceManager會在前五次嘗試的 1000 毫秒間隔內自動輪詢結果檔案,而且無法設定該行為。 StatusPollIntervalInMilliseconds屬性會決定在初始五次嘗試之後,每個輪詢嘗試之間的時間間隔。 如需範例,請參閱上方 的背景完成 。 預設值為 5000,因此如果您未設定此值, BulkServiceManager 會依下列分鐘順序輪詢:1、2、3、4、5、10、15、20 等等。 如果您將此值設定為 10000,BulkServiceManager 會依下列順序輪詢:1、2、3、4、5、15、25、35 等等。 最小輪詢間隔為 1000,如果您指定小於 1000 的值,則會擲回例外狀況。

BulkServiceManager會自動重試上傳、下載和輪詢作業,最多可達您設定的逾時持續時間上限。 您可以設定重試逾時持續時間上限。 如果未指定逾時, BulkServiceManager 會繼續重試,直到伺服器傳回逾時或內部錯誤為止。 另外,如果您要上傳或下載大型檔案,您應該考慮設定 UploadHttpTimeoutDownloadHttpTimeout 屬性。

工作目錄和 BulkServiceManager

透過 Bing Ads .NET 和 JAVA SDK,您可以設定工作目錄, 其中 BulkServiceManager 應該儲存暫存的大量檔案。 例如,當您使用 Bing Ads .NET SDK 下載實體時,雖然您只會直接使用 BulkEntity 物件,但會將大量檔案下載到工作目錄。 同樣地,當您上傳實體時,暫存檔會寫入工作目錄,然後上傳至大量服務。 如果未指定另一個工作目錄,則會使用系統臨時目錄。

如果您使用如 Microsoft Azure 的託管服務,您會想要確保不會超過臨時目錄限制。 使用自訂工作目錄可能還有其他原因。 您可以藉由設定WorkingDirectory屬性,為每個BulkServiceManager實例指定不同的工作目錄。 您也必須負責建立和移除任何目錄。 反復查看大量實體之後,您可以從工作目錄清除檔案。

重要事項

CleanupTempFiles方法會移除工作目錄內) 的所有檔案 (,但不會移除任何子目錄,無論這些檔案是否由目前的BulkServiceManager實例所建立。

public async Task RunAsync(AuthorizationData authorizationData)
{
    var bulkServiceManager = new BulkServiceManager(authorizationData);

    var progress = new Progress<BulkOperationProgressInfo>(x =>
        Console.WriteLine(String.Format("{0} % Complete", x.PercentComplete.ToString(CultureInfo.InvariantCulture)))
    );

    var downloadParameters = new DownloadParameters
    {
        CampaignIds = null,
        DataScope = DataScope.EntityData,
        Entities = DownloadEntity.Keywords,
        FileType = DownloadFileType.Csv,
        LastSyncTimeInUTC = null,
        ResultFileDirectory = FileDirectory,
        ResultFileName = ResultFileName,
        OverwriteResultFile = false    // Set this value true if you want to overwrite the same file.
    };

    // The system temp directory will be used if another working directory is not specified. If you are 
    // using a hosted service such as Microsoft Azure you'll want to ensure you do not exceed the file or directory limits. 
    // You can specify a different working directory for each BulkServiceManager instance.

    bulkServiceManager.WorkingDirectory = FileDirectory;

    // The DownloadEntitiesAsync method returns IEnumerable<BulkEntity>, so the download file will not
    // be accessible e.g. for CleanupTempFiles until you iterate over the result e.g. via ToList().

    var resultEntities = (await bulkServiceManager.DownloadEntitiesAsync(
        downloadParameters
    )).ToList();

    // The CleanupTempFiles method removes all files (but not sub-directories) within the working directory, 
    // whether or not the files were created by this BulkServiceManager instance. 

    bulkServiceManager.CleanupTempFiles();
}
BulkServiceManager bulkServiceManager = new BulkServiceManager(authorizationData);

Progress<BulkOperationProgressInfo> progress = new Progress<BulkOperationProgressInfo>() {
    @Override
    public void report(BulkOperationProgressInfo value) {
        System.out.println(value.getPercentComplete() + "% Complete\n");
    }
};

DownloadParameters downloadParameters = new DownloadParameters();
downloadParameters.setCampaignIds(null);
ArrayList<DataScope> dataScope = new ArrayList<DataScope>();
dataScope.add(DataScope.ENTITY_DATA);
downloadParameters.setDataScope(dataScope);
downloadParameters.setFileType(FileType);
downloadParameters.setLastSyncTimeInUTC(null);
ArrayList<DownloadEntity> bulkDownloadEntities = new ArrayList<DownloadEntity>();
bulkDownloadEntities.add(DownloadEntity.KEYWORDS);
downloadParameters.setEntities(bulkDownloadEntities);
downloadParameters.setResultFileDirectory(new File(FileDirectory));
downloadParameters.setResultFileName(ResultFileName);
downloadParameters.setOverwriteResultFile(true);    // Set this value true if you want to overwrite the same file.

// The system temp directory will be used if another working directory is not specified. If you are 
// using a cloud service such as Microsoft Azure you'll want to ensure you do not exceed the file or directory limits. 
// You can specify a different working directory for each BulkServiceManager instance.

bulkServiceManager.setWorkingDirectory(new File(FileDirectory));

// The downloadEntitiesAsync method returns BulkEntityIterable, so the download file will not
// be accessible e.g. for cleanupTempFiles until you iterate over the result and close the BulkEntityIterable instance.

BulkEntityIterable tempEntities = bulkServiceManager.downloadEntitiesAsync(
    downloadParameters,
    null,
    null
).get();

ArrayList<BulkEntity> resultEntities = new ArrayList<BulkEntity>();
for (BulkEntity entity : tempEntities) {
    resultEntities.add(entity);
}

tempEntities.close();

// The cleanupTempFiles method removes all files (not sub-directories) within the working directory, 
// whether or not the files were created by this BulkServiceManager instance. 

bulkServiceManager.cleanupTempFiles();

另請參閱

沙 箱
Bing 廣告 API 程式碼範例
Bing 廣告 API Web 服務位址