Compartir a través de


Service Manager masiva

Aprovecha el servicio bulk para administrar de forma eficaz los grupos de anuncios y los anuncios de todas las campañas de una cuenta. Los SDK de .NET, Java y Python de Bing Ads proporcionan clases para acelerar la productividad para descargar y cargar registros masivos. Por ejemplo , BulkServiceManager enviará la solicitud de descarga al servicio masivo, sondeará el servicio hasta que se complete y descargará el archivo en el directorio local. BulkServiceManager también controla automáticamente los campos de encabezado de solicitud comunes, lo que permite especificar las propiedades Authentication, CustomerId, AccountId y DeveloperToken en el objeto AuthorizationData una vez para cada servicio. Para obtener más información, vea Uso de AuthorizationData y el ejemplo de código de solicitudes masivas .

Nota:

BulkServiceManager solo está disponible con los SDK de .NET, Java y Python de Bing Ads. Tanto si usa un SDK como si no, puede usar el servicio masivo directamente. Para obtener más información, consulte Descarga y carga masivas.

Lector y escritor de archivos masivos

No es necesario implementar su propio analizador de archivos para leer y escribir el archivo masivo. Puede usar objetos BulkFileReader y BulkFileWriter para leer y escribir clases derivadas de BulkEntity .

Nota:

BulkServiceManager usa BulkFileReader y BulkFileWriter en segundo plano al cargar y descargar entidades en lugar de archivos. Los archivos temporales se usan en segundo plano. Para obtener más información, vea Directorio de trabajo y BulkServiceManager.

Por ejemplo, supongamos que desea escribir el siguiente registro de anuncios de texto expandido en un archivo masivo.

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

En primer lugar, cree el objeto BulkExpandedTextAd como se muestra a continuación en Mapa de entidades de administración masiva y de campañas. A continuación, puede escribir BulkExpandedTextAd en un archivo con BulkFileWriter, como se muestra aquí.

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

Este es un ejemplo de lectura del archivo de resultados de carga masiva de un directorio local con BulkFileReader. Puede leer un archivo masivo con BulkFileReader, ya sea descarga completa, descarga parcial o carga de resultados.

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

Mapa de entidades de administración masiva y de campañas

Todos los objetos leídos y escritos en archivos bulk a través de BulkServiceManager, BulkFileReader y BulkFileWriter derivan de la clase base BulkEntity, por ejemplo, BulkCampaign, BulkAdGroup y BulkExpandedTextAd. Siempre que sea posible, los objetos masivos aprovechan objetos y conjuntos de valores de Campaign Management, por ejemplo, el siguiente objeto BulkExpandedTextAd contiene el objeto ExpandedTextAd de campaign management API.

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
)

Actualización con delete_value

Para quitar una configuración existente, no debe escribir una cadena vacía ("") en el archivo masivo porque el servicio bulk omite dichas cadenas. Use la cadena reservada "delete_value" para eliminar o restablecer el valor de un campo opcional. Si usa la cadena reservada "delete_value" en un campo opcional, se eliminará la configuración anterior. Por ejemplo, si estableces el campo Parámetro personalizado del registro de anuncios de texto expandido en "delete_value", todos los parámetros personalizados anteriores se eliminarán del anuncio de texto expandido. Del mismo modo, si estableces el campo Plantilla de seguimiento del registro de anuncios de texto expandido en "delete_value", la plantilla de seguimiento anterior se eliminará del anuncio de texto expandido. Para obtener más información sobre "delete_value", vea Esquema de archivo masivo: actualización con delete_value.

BulkFileWriter escribe automáticamente "delete_value" cuando corresponda. Dado que el SDK asigna objetos de API de Campaign Management al contenido de un archivo masivo, no se puede establecer explícitamente la cadena "delete_value" para las propiedades con otros tipos de datos. En esos casos, puede usar la misma sintaxis que usaría para actualizar el objeto a través de campaign management API. En el ejemplo siguiente, al establecer UrlCustomParameters en un objeto CustomParameters vacío, el SDK escribirá "delete_value" en el campo Parámetro personalizado del registro Anuncio de texto expandido . Del mismo modo, al establecer TrackingUrlTemplate en una cadena vacía, el SDK escribirá "delete_value" en el campo Plantilla de seguimiento del registro de anuncios de texto expandido . La sintaxis de ejemplo dentro del objeto ExpandedTextAd es idéntica a la forma en que eliminaría la configuración de previus a través de la operación de servicio UpdateAds a través de campaign management API.

Importante

No use cadenas vacías ("") ni la sintaxis "delete_value" al crear una entidad masiva. La cadena reservada "delete_value" solo se aplica para actualizar registros masivos. No debe establecer la propiedad o establecerla en un valor null equivalente.

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

Descargar y cargar

BulkServiceManager admite flujos de trabajo flexibles de carga y descarga masiva.

  • Puede crear una solicitud de descarga o carga y BulkServiceManager enviará la solicitud de descarga al servicio masivo, sondeará el servicio hasta que se complete y descargará el archivo en el directorio local. Por ejemplo, vea Finalización en segundo plano con BulkServiceManager.

  • Puede enviar una solicitud de descarga o carga y, a continuación, sondear hasta que el archivo de resultados esté listo para descargarse. Por ejemplo, vea Enviar y descargar con BulkServiceManager.

  • Si por algún motivo tiene que reanudar desde un estado de aplicación anterior, puede usar un identificador de solicitud de carga o descarga existente y usarlo para descargar el archivo de resultados. Por ejemplo, vea Descargar resultados con BulkServiceManager.

Tanto si descarga y carga entidades en la memoria como si las lee y escribe en un archivo, BulkServiceManager lee y escribe en un archivo temporal.

Finalización en segundo plano con BulkServiceManager

Puede crear una solicitud de descarga o carga y BulkServiceManager enviará la solicitud de descarga al servicio masivo, sondeará el servicio hasta que se complete y descargará el archivo en el directorio local.

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

Enviar y descargar con BulkServiceManager

Envíe la solicitud de descarga y, a continuación, use el resultado BulkDownloadOperation para realizar un seguimiento del estado.

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

Descargar resultados con BulkServiceManager

Si por algún motivo tiene que reanudar desde un estado de aplicación anterior, puede usar un identificador de solicitud de carga o descarga existente y usarlo para descargar el archivo de resultados. Realice un seguimiento del resultado para asegurarse de que el estado de descarga se ha completado.

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

Sondear y reintentar

Sondee los resultados de descarga y carga a intervalos razonables. Conoce sus datos mejor que nadie. Por ejemplo, si descarga una cuenta que es mucho menos de un millón de palabras clave, considere la posibilidad de sondear a intervalos de 5 a 20 segundos. Si la cuenta contiene aproximadamente un millón de palabras clave, considere la posibilidad de sondear a intervalos de un minuto después de esperar cinco minutos. En el caso de las cuentas con aproximadamente cuatro millones de palabras clave, considere la posibilidad de sondear a intervalos de un minuto después de esperar 10 minutos.

BulkServiceManager sondea automáticamente el archivo de resultado en intervalos de 1000 milisegundos para los cinco primeros intentos, y ese comportamiento no es configurable. La propiedad StatusPollIntervalInMilliseconds determina el intervalo de tiempo entre cada intento de sondeo después de los cinco intentos iniciales. Para obtener un ejemplo, consulte Finalización en segundo plano anterior. El valor predeterminado es 5000, por lo que si no establece este valor , BulkServiceManager sondeará en la siguiente secuencia de minutos: 1, 2, 3, 4, 5, 10, 15, 20, etc. Si establece este valor en 10000, BulkServiceManager sondeará en la siguiente secuencia: 1, 2, 3, 4, 5, 15, 25, 35, etc. El intervalo de sondeo mínimo es 1000 y, si especifica un valor inferior a 1000, se producirá una excepción.

BulkServiceManager volverá a intentar automáticamente las operaciones de carga, descarga y sondeo hasta la duración máxima del tiempo de espera que establezca. Puede establecer la duración máxima del tiempo de espera de reintento. Si no se especifica ningún tiempo de espera, BulkServiceManager seguirá reintento hasta que el servidor devuelva un tiempo de espera o un error interno. Por separado, si va a cargar o descargar archivos grandes, debe considerar la posibilidad de establecer las propiedades UploadHttpTimeout o DownloadHttpTimeout .

Directorio de trabajo y BulkServiceManager

Con los SDK de .NET y Java de Bing Ads, puede establecer el directorio de trabajo donde BulkServiceManager debe almacenar archivos masivos temporales. Por ejemplo, al descargar entidades con el SDK de .NET de Bing Ads, aunque solo trabajará directamente con objetos BulkEntity , se descarga un archivo masivo en el directorio de trabajo. Del mismo modo, al cargar entidades, se escribe un archivo temporal en el directorio de trabajo y, a continuación, se carga en el servicio masivo. El directorio temporal del sistema se usará si no se especifica otro directorio de trabajo.

Si usa un servicio hospedado como Microsoft Azure, querrá asegurarse de que no supera los límites del directorio temporal. Puede haber otras razones para usar un directorio de trabajo personalizado. Puede especificar un directorio de trabajo diferente para cada instancia de BulkServiceManager estableciendo la propiedad WorkingDirectory . También es responsable de crear y quitar directorios. Una vez que haya iterado sobre las entidades masivas, puede limpiar los archivos del directorio de trabajo.

Importante

El método CleanupTempFiles quita todos los archivos (pero no los subdirectorios) del directorio de trabajo, independientemente de que la instancia actual de BulkServiceManager haya creado o no los archivos.

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

Consulta también

Espacio aislado
Ejemplos de código de api de Bing Ads
Direcciones del servicio web de la API de Bing Ads