Condividi tramite


Service Manager bulk

Sfrutta il servizio Bulk per gestire in modo efficiente gruppi di annunci e annunci per tutte le campagne in un account. Gli SDK Bing Ads .NET, Java e Python offrono classi per accelerare la produttività per il download e il caricamento di record bulk. Ad esempio , BulkServiceManager invierà la richiesta di download al servizio Bulk, eseguirà il polling del servizio fino al completamento e scaricherà il file nella directory locale. BulkServiceManager gestisce automaticamente anche i campi di intestazione della richiesta comuni, consentendo di specificare le proprietà Authentication, CustomerId, AccountId e DeveloperToken nell'oggetto AuthorizationData una volta per ogni servizio. Per altre informazioni, vedere Uso di AuthorizationData e l'esempio di codice Richieste bulk .

Nota

BulkServiceManager è disponibile solo con gli SDK Bing Ads .NET, Java e Python. Indipendentemente dal fatto che si usi o meno un SDK, è possibile usare direttamente il servizio bulk . Per altre informazioni, vedere Download e caricamento bulk.

Lettore file bulk e writer

Non è necessario implementare il proprio parser di file per leggere e scrivere il file bulk. È possibile utilizzare oggetti BulkFileReader e BulkFileWriter per leggere e scrivere classi derivate da BulkEntity .

Nota

BulkServiceManager usa BulkFileReader e BulkFileWriter in background quando si caricano e scaricano entità anziché file. I file temporanei vengono usati in background. Per altre informazioni, vedere Directory di lavoro e BulkServiceManager.

Si supponga, ad esempio, di voler scrivere il record di annunci di testo espanso seguente in un file bulk.

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

Creare innanzitutto l'oggetto BulkExpandedTextAd, come illustrato di seguito in Bulk and Campaign Management Entity Map. È quindi possibile scrivere BulkExpandedTextAd in un file con BulkFileWriter, come illustrato di seguito.

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()

Di seguito è riportato un esempio di lettura del file dei risultati del caricamento bulk da una directory locale con BulkFileReader. È possibile leggere un file bulk con BulkFileReader, sia che si tratti di download completo, download parziale o caricamento dei risultati.

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])

Mappa entità gestione campagne e bulk

Tutti gli oggetti letti e scritti in file bulk tramite BulkServiceManager, BulkFileReader, BulkFileWriter derivano dalla classe di base BulkEntity, ad esempio BulkCampaign, BulkAdGroup e BulkExpandedTextAd. Laddove possibile, gli oggetti bulk sfruttano oggetti Campaign Management e set di valori, ad esempio l'oggetto BulkExpandedTextAd seguente contiene l'API Campaign Management 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
)

Eseguire l'aggiornamento con delete_value

Per rimuovere un'impostazione esistente, non è consigliabile scrivere una stringa vuota ("") nel file bulk perché tali stringhe vengono ignorate dal servizio Bulk. Usare la stringa riservata "delete_value" per eliminare o reimpostare il valore di un campo facoltativo. Se si usa la stringa riservata "delete_value" in un campo facoltativo, l'impostazione precedente verrà eliminata. Ad esempio, se imposti il campo Parametro personalizzato del record annunci di testo espanso su "delete_value", tutti i parametri personalizzati precedenti verranno eliminati dall'annuncio di testo espanso. Analogamente, se imposti il campo Modello di rilevamento del record annunci di testo espanso su "delete_value", il modello di rilevamento precedente verrà eliminato dall'annuncio di testo espanso. Per altre informazioni su "delete_value", vedere Bulk File Schema - Update with delete_value (Schema file bulk - Aggiornamento con delete_value).

BulkFileWriter scrive automaticamente "delete_value" se applicabile. Poiché l'SDK esegue il mapping degli oggetti DELL'API Campaign Management al contenuto di un file bulk, non è possibile impostare in modo esplicito la stringa "delete_value" per le proprietà con altri tipi di dati. In questi casi è possibile usare la stessa sintassi usata per aggiornare l'oggetto tramite l'API Campaign Management. Nell'esempio seguente impostando UrlCustomParameters su un oggetto CustomParameters vuoto, l'SDK scriverà "delete_value" nel campo Parametro personalizzato del record di annunci di testo espanso . Analogamente, impostando TrackingUrlTemplate su una stringa vuota, l'SDK scriverà "delete_value" nel campo Modello di rilevamento del record di annunci di testo espanso . La sintassi di esempio all'interno dell'oggetto ExpandedTextAd è identica alla modalità di eliminazione delle impostazioni preliminari tramite l'operazione del servizio UpdateAds tramite l'API Campaign Management.

Importante

Non usare stringhe vuote ("") o la sintassi "delete_value" quando si crea un'entità Bulk. La stringa riservata "delete_value" è applicabile solo per l'aggiornamento di record bulk. Non è consigliabile impostare la proprietà o impostarla su un equivalente 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

Scaricare e caricare

BulkServiceManager supporta flussi di lavoro di download e caricamento bulk flessibili.

  • È possibile creare una richiesta di download o caricamento e BulkServiceManager invierà la richiesta di download al servizio bulk, eseguirà il polling del servizio fino al completamento e scaricherà il file nella directory locale. Ad esempio, vedere Completamento in background con BulkServiceManager.

  • È possibile inviare una richiesta di download o caricamento e quindi eseguire il polling fino a quando il file dei risultati non è pronto per il download. Ad esempio, vedere Inviare e scaricare con BulkServiceManager.

  • Se per qualsiasi motivo è necessario riprendere da uno stato precedente dell'applicazione, è possibile usare un identificatore di richiesta di download o caricamento esistente e usarlo per scaricare il file dei risultati. Ad esempio, vedere Scaricare i risultati con BulkServiceManager.

Indipendentemente dal fatto che le entità vengano scaricate e caricate in memoria o le si legga e le si scriva in un file, BulkServiceManager legge e scrive in un file temporaneo.

Completamento in background con BulkServiceManager

È possibile creare una richiesta di download o caricamento e BulkServiceManager invierà la richiesta di download al servizio bulk, eseguirà il polling del servizio fino al completamento e scaricherà il file nella directory locale.

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))

Inviare e scaricare con BulkServiceManager

Inviare la richiesta di download e quindi usare il risultato BulkDownloadOperation per tenere traccia dello stato.

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))

Scaricare i risultati con BulkServiceManager

Se per qualsiasi motivo è necessario riprendere da uno stato precedente dell'applicazione, è possibile usare un identificatore di richiesta di download o caricamento esistente e usarlo per scaricare il file dei risultati. Tenere traccia del risultato per assicurarsi che lo stato di download sia completato.

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))

Polling e ripetizione dei tentativi

Eseguire il polling dei risultati di download e caricamento a intervalli ragionevoli. Conosci i tuoi dati meglio di chiunque altro. Ad esempio, se si scarica un account che è ben inferiore a un milione di parole chiave, prendere in considerazione il polling a intervalli da 5 a 20 secondi. Se l'account contiene circa un milione di parole chiave, prendere in considerazione il polling a intervalli di un minuto dopo cinque minuti di attesa. Per gli account con circa quattro milioni di parole chiave, prendere in considerazione il polling a intervalli di un minuto dopo l'attesa di 10 minuti.

BulkServiceManager esegue automaticamente il polling del file dei risultati in intervalli di 1000 millisecondi per i primi cinque tentativi e tale comportamento non è configurabile. La proprietà StatusPollIntervalInMilliseconds determina l'intervallo di tempo tra ogni tentativo di polling dopo i cinque tentativi iniziali. Per un esempio, vedere Completamento in background sopra. Il valore predefinito è 5000, quindi se non si imposta questo valore , BulkServiceManager eseguirà il polling nella sequenza di minuti seguente: 1, 2, 3, 4, 5, 10, 15, 20 e così via. Se si imposta questo valore su 10000, BulkServiceManager eseguirà il polling nella sequenza seguente: 1, 2, 3, 4, 5, 15, 25, 35 e così via. L'intervallo di polling minimo è 1000 e se si specifica un valore minore di 1000 verrà generata un'eccezione.

BulkServiceManager ritenterà automaticamente le operazioni di caricamento, download e polling fino alla durata massima di timeout impostata. È possibile impostare la durata massima del timeout dei tentativi. Se non viene specificato alcun timeout, BulkServiceManager continuerà a riprovare fino a quando il server non restituisce un timeout o un errore interno. Separatamente, se si caricano o si scaricano file di grandi dimensioni, è consigliabile impostare le proprietà UploadHttpTimeout o DownloadHttpTimeout .

Directory di lavoro e BulkServiceManager

Con gli SDK Bing Ads .NET e Java, è possibile impostare la directory di lavoro in cui BulkServiceManager deve archiviare i file bulk temporanei. Ad esempio, quando si scaricano entità con Bing Ads .NET SDK, anche se si userà direttamente solo gli oggetti BulkEntity , un file bulk viene scaricato nella directory di lavoro. Analogamente, quando si caricano le entità, un file temporaneo viene scritto nella directory di lavoro e quindi caricato nel servizio bulk. La directory temporanea di sistema verrà usata se non viene specificata un'altra directory di lavoro.

Se si usa un servizio ospitato, ad esempio Microsoft Azure, assicurarsi di non superare i limiti della directory temporanea. Potrebbero esserci altri motivi per usare una directory di lavoro personalizzata. È possibile specificare una directory di lavoro diversa per ogni istanza di BulkServiceManager impostando la proprietà WorkingDirectory . L'utente è anche responsabile della creazione e della rimozione di eventuali directory. Dopo aver eseguito l'iterazione sulle entità bulk, è possibile pulire i file dalla directory di lavoro.

Importante

Il metodo CleanupTempFiles rimuove tutti i file (ma non tutte le sottodirectory) all'interno della directory di lavoro, indipendentemente dal fatto che i file siano stati creati o meno dall'istanza BulkServiceManager corrente.

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();

Vedere anche

Sandbox
Esempi di codice API Bing Ads
Indirizzi del servizio Web dell'API Bing Ads