Aracılığıyla paylaş


Toplu Service Manager

Bir hesaptaki tüm kampanyalar için reklam gruplarını ve reklamları verimli bir şekilde yönetmek için Toplu hizmet'inden yararlanın. Bing Ads .NET, Java ve Python SDK'ları, toplu kayıtları indirme ve karşıya yükleme üretkenliğini hızlandırmaya yönelik sınıflar sağlar. Örneğin BulkServiceManager indirme isteğinizi Toplu hizmete gönderir, tamamlanana kadar hizmeti yoklar ve dosyayı yerel dizininize indirir. BulkServiceManager sizin için ortak istek üst bilgisi alanlarını da işler ve her hizmet için AuthorizationData nesnesinde Authentication, CustomerId, AccountId ve DeveloperToken özelliklerini bir kez belirtmeye olanak sağlar. Daha fazla bilgi için bkz. AuthorizationData kullanma ve Toplu İstekler kod örneği.

Not

BulkServiceManager yalnızca Bing Ads .NET, Java ve Python SDK'larıyla kullanılabilir. SDK kullansanız da kullanmasanız da toplu hizmeti doğrudan kullanabilirsiniz. Daha fazla bilgi için bkz. Toplu İndirme ve Karşıya Yükleme.

Toplu Dosya Okuyucu ve Yazıcı

Toplu dosyayı okumak ve yazmak için kendi dosya ayrıştırıcınızı uygulamanız gerekmez. BulkEntity türetilmiş sınıflarını okumak ve yazmak için BulkFileReader ve BulkFileWriter nesnelerini kullanabilirsiniz.

Not

BulkServiceManager, dosyalar yerine varlıkları karşıya yükleyip indirdiğinizde arka planda BulkFileReader ve BulkFileWriter kullanır. Geçici dosyalar arka planda kullanılır. Diğer ayrıntılar için bkz . Working Directory ve BulkServiceManager.

Örneğin, aşağıdaki Genişletilmiş Metin Reklamı kaydını toplu bir dosyaya yazmak istediğinizi varsayalım.

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

İlk olarak, Aşağıda Toplu ve Kampanya Yönetimi Varlık Eşlemesi'nde gösterildiği gibi BulkExpandedTextAd nesnesini oluşturun. Ardından BulkExpandedTextAd dosyasını burada gösterildiği gibi BulkFileWriter içeren bir dosyaya yazabilirsiniz.

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

Aşağıda BulkFileReader ile yerel bir dizinden Toplu karşıya yükleme sonuçları dosyasını okuma örneği verilmiştir. Tam indirme, kısmi indirme veya karşıya yükleme sonuçları gibi toplu bir dosyayı BulkFileReader ile okuyabilirsiniz.

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

Toplu ve Kampanya Yönetimi Varlık Haritası

BulkServiceManager, BulkFileReader, BulkFileWriter aracılığıyla Toplu dosyalardan okunan ve toplu dosyalara yazılan tüm nesneler BulkEntity temel sınıfından türetilir; örneğin, BulkCampaign, BulkAdGroup ve BulkExpandedTextAd. Mümkün olduğunda toplu nesneler Kampanya Yönetimi nesne ve değer kümelerini kullanır; örneğin, aşağıdaki BulkExpandedTextAd, Kampanya Yönetimi API'sinin ExpandedTextAd nesnesini içerir.

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 ile güncelleştirme

Mevcut bir ayarı kaldırmak için Toplu dosyaya boş bir dize ("") yazmamalısınız çünkü bu tür dizeler Toplu hizmeti tarafından yoksayılır. İsteğe bağlı bir alanın değerini silmek veya sıfırlamak için ayrılmış "delete_value" dizesini kullanın. İsteğe bağlı bir alanda ayrılmış "delete_value" dizesini kullanırsanız, önceki ayar silinir. Örneğin, Genişletilmiş Metin Reklamı kaydının Özel Parametre alanını "delete_value" olarak ayarlarsanız, genişletilmiş metin reklamından önceki tüm özel parametreler silinir. Aynı şekilde, Genişletilmiş Metin Reklamı kaydının İzleme Şablonu alanını "delete_value" olarak ayarlarsanız, önceki izleme şablonu genişletilmiş metin reklamından silinir. "delete_value" hakkında daha fazla ayrıntı için bkz. Toplu Dosya Şeması - delete_value ile güncelleştirme.

BulkFileWriter, uygun olduğunda otomatik olarak "delete_value" yazar. SDK, Kampanya Yönetimi API'sinin nesnelerini Bir Toplu dosyanın içeriğiyle eşlediğinden , diğer veri türlerine sahip özellikler için "delete_value" dizesini açıkça ayarlayamazsınız. Bu gibi durumlarda, Kampanya Yönetimi API'sini kullanarak nesneyi güncelleştirmek için kullandığınız söz dizimini kullanabilirsiniz. Aşağıdaki örnekte UrlCustomParameters'ı boş bir CustomParameters nesnesine ayarlayarak SDK, Genişletilmiş Metin Reklam kaydının Özel Parametre alanına "delete_value" yazar. Benzer şekilde, TrackingUrlTemplate'ı boş bir dizeye ayarlayarak SDK, Genişletilmiş Metin Reklam kaydının İzleme Şablonu alanına "delete_value" yazar. ExpandedTextAd nesnesi içindeki örnek söz dizimi, Kampanya Yönetimi API'si aracılığıyla UpdateAds hizmeti işlemi aracılığıyla previus ayarlarını silme yöntemiyle aynıdır.

Önemli

Toplu varlık oluştururken boş dizeler ("") veya "delete_value" söz dizimi kullanmayın. Ayrılmış "delete_value" dizesi yalnızca Toplu kayıtları güncelleştirmek için geçerlidir. Özelliğini ayarlamamalı veya null eşdeğerine ayarlamamalısınız.

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

İndirme ve Karşıya Yükleme

BulkServiceManager esnek toplu indirme ve karşıya yükleme iş akışlarını destekler.

  • İndirme veya karşıya yükleme isteği oluşturabilirsiniz; BulkServiceManager indirme isteğinizi Toplu hizmete gönderir, tamamlanana kadar hizmeti yoklar ve dosyayı yerel dizininize indirir. Örneğin, bkz. BulkServiceManager ile Arka Plan Tamamlama.

  • İndirme veya karşıya yükleme isteği gönderebilir ve sonuç dosyası indirilmeye hazır olana kadar yoklayabilirsiniz. Örneğin, bkz. BulkServiceManager ile Gönderme ve İndirme.

  • Herhangi bir nedenle önceki bir uygulama durumundan devam etmek zorundaysanız, mevcut bir indirme veya karşıya yükleme isteği tanımlayıcısını kullanabilir ve sonuç dosyasını indirmek için kullanabilirsiniz. Örneğin, bkz. BulkServiceManager ile Sonuçları İndirme.

İster bellekteki varlıkları indirip karşıya yükleyin ister kendiniz okuyup bir dosyaya yazın, BulkServiceManager geçici bir dosyayı okur ve yazar.

BulkServiceManager ile Arka Plan Tamamlama

İndirme veya karşıya yükleme isteği oluşturabilirsiniz; BulkServiceManager indirme isteğinizi Toplu hizmete gönderir, tamamlanana kadar hizmeti yoklar ve dosyayı yerel dizininize indirir.

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 ile Gönderme ve İndirme

İndirme isteğini gönderin ve ardından durumu izlemek için BulkDownloadOperation sonucunu kullanın.

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 ile Sonuçları İndirme

Herhangi bir nedenle önceki bir uygulama durumundan devam etmek zorundaysanız, mevcut bir indirme veya karşıya yükleme isteği tanımlayıcısını kullanabilir ve sonuç dosyasını indirmek için kullanabilirsiniz. İndirme durumunun tamamlandığından emin olmak için sonucu izleyin.

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

Yoklama ve Yeniden Deneme

makul aralıklarla indirme ve karşıya yükleme sonuçlarını yoklama. Verilerinizi herkesten daha iyi biliyorsunuz. Örneğin, bir milyondan az anahtar sözcük içeren bir hesap indirirseniz 5 ile 20 saniye arasında bir aralıkta yoklamayı göz önünde bulundurun. Hesap yaklaşık bir milyon anahtar sözcük içeriyorsa, beş dakika bekledikten sonra bir dakikalık aralıklarla yoklamayı göz önünde bulundurun. Yaklaşık dört milyon anahtar sözcüğü olan hesaplar için 10 dakika bekledikten sonra bir dakikalık aralıklarla yoklamayı göz önünde bulundurun.

BulkServiceManager, ilk beş deneme için 1000 milisaniyelik aralıklarla sonuç dosyasını otomatik olarak yoklar ve bu davranış yapılandırılamaz. StatusPollIntervalInMilliseconds özelliği, ilk beş denemeden sonra her yoklama girişimi arasındaki zaman aralığını belirler. Örnek için lütfen yukarıdaki Arka Plan Tamamlama bölümüne bakın. Varsayılan değer 5000'dir, bu nedenle bu değeri ayarlamazsanız BulkServiceManager şu dakika dizisinde yoklar: 1, 2, 3, 4, 5, 10, 15, 20 vb. Bu değeri 10000 olarak ayarlarsanız BulkServiceManager şu sırayla yoklar: 1, 2, 3, 4, 5, 15, 25, 35 vb. En düşük yoklama aralığı 1000'dir ve 1000'den küçük bir değer belirtirseniz özel durum oluşturulur.

BulkServiceManager, ayarladığınız maksimum zaman aşımı süresine kadar karşıya yükleme, indirme ve yoklama işlemlerini otomatik olarak yeniden dener. En uzun yeniden deneme zaman aşımı süresini ayarlayabilirsiniz. Zaman aşımı belirtilmezse, Sunucu bir zaman aşımı veya iç hata döndürene kadar BulkServiceManager yeniden denemeye devam eder. Ayrıca, büyük dosyaları karşıya yüklüyor veya indiriyorsanız UploadHttpTimeout veya DownloadHttpTimeout özelliklerini ayarlamayı düşünmelisiniz.

Çalışma Dizini ve BulkServiceManager

Bing Ads .NET ve Java SDK'ları ile BulkServiceManager'ın geçici toplu dosyaları depolaması gereken çalışma dizinini ayarlayabilirsiniz. Örneğin, Bing Ads .NET SDK'sı ile varlıkları indirdiğinizde, yalnızca BulkEntity nesneleriyle doğrudan çalışacak olmanıza rağmen, toplu bir dosya çalışma dizinine indirilir. Benzer şekilde, varlıkları karşıya yüklediğinizde, çalışma dizinine geçici bir dosya yazılır ve ardından Toplu hizmete yüklenir. Başka bir çalışma dizini belirtilmezse sistem geçici dizini kullanılır.

Microsoft Azure gibi barındırılan bir hizmet kullanıyorsanız geçici dizin sınırlarını aşmadığınızdan emin olmak istersiniz. Özel çalışma dizini kullanmanın başka nedenleri olabilir. WorkingDirectory özelliğini ayarlayarak her BulkServiceManager örneği için farklı bir çalışma dizini belirtebilirsiniz. Ayrıca tüm dizinleri oluşturmak ve kaldırmak sizin sorumluluğundadır. Toplu varlıklar üzerinde yineleme yaptıktan sonra, dosyaları çalışma dizininden temizleyebilirsiniz.

Önemli

CleanupTempFiles yöntemi, dosyaların geçerli BulkServiceManager örneği tarafından oluşturulup oluşturulmadığına bakılmaksızın çalışma dizini içindeki tüm dosyaları (ancak alt dizinleri kaldırmaz) kaldırır.

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

Ayrıca Bkz

Sandbox
Bing Ads API Kod Örnekleri
Bing Ads API Web Hizmeti Adresleri