Esempio di codice etichette

Questo esempio illustra come aggiungere etichette e associarle a campagne e gruppi di annunci.

Consiglio

Usare il selettore di linguaggio nell'intestazione della documentazione per scegliere C#, Java, Php o Python.

Per ottenere i token di accesso e aggiornamento per l'utente di Microsoft Advertising e effettuare la prima chiamata al servizio usando l'API Bing Ads, vedere la guida introduttiva . È consigliabile esaminare la guida introduttiva e le procedure dettagliate per il linguaggio preferito, ad esempio C#, Java, Php e Python.

I file di supporto per gli esempi C#, Java, Php e Python sono disponibili in GitHub. È possibile clonare ogni repository o riutilicare i frammenti in base alle esigenze.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.BingAds.V13.CampaignManagement;
using Microsoft.BingAds;

namespace BingAdsExamplesLibrary.V13
{
    /// <summary>
    /// How to add labels and associate them with
    /// campaigns, ad groups, keywords, and ads.
    /// </summary>
    public class Labels : ExampleBase
    {
        public override string Description
        {
            get { return "Labels | Campaign Management V13"; }
        }

        protected const int MaxGetLabelsByIds = 1000;
        protected const int MaxLabelIdsForGetLabelAssociations = 1;
        protected const int MaxEntityIdsForGetLabelAssociations = 100;
        protected const int MaxPagingSize = 1000;

        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;

                CampaignManagementExampleHelper CampaignManagementExampleHelper = new CampaignManagementExampleHelper(
                    OutputStatusMessageDefault: this.OutputStatusMessage);
                CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
                    authorizationData: authorizationData,
                    environment: environment);

                // Add an ad group in a campaign. Later we will create labels for them. 
                // Although not included in this example you can also create labels for ads and keywords. 

                var campaigns = new[]{
                    new Campaign
                    {
                        BudgetType = BudgetLimitType.DailyBudgetStandard,
                        DailyBudget = 50,
                        CampaignType = CampaignType.Search,
                        Languages = new string[] { "All" },
                        Name = "Everyone's Shoes " + DateTime.UtcNow,
                        TimeZone = "PacificTimeUSCanadaTijuana",
                    },
                };

                OutputStatusMessage("-----\nAddCampaigns:");
                AddCampaignsResponse addCampaignsResponse = await CampaignManagementExampleHelper.AddCampaignsAsync(
                    accountId: authorizationData.AccountId,
                    campaigns: campaigns);
                long?[] campaignIds = addCampaignsResponse.CampaignIds.ToArray();
                BatchError[] campaignErrors = addCampaignsResponse.PartialErrors.ToArray();
                OutputStatusMessage("CampaignIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(campaignIds);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(campaignErrors);

                var adGroups = new[] {
                    new AdGroup
                    {
                        Name = "Everyone's Red Shoe Sale",
                        StartDate = null,
                        EndDate = new Date {
                            Month = 12,
                            Day = 31,
                            Year = DateTime.UtcNow.Year + 1
                        },
                        CpcBid = new Bid { Amount = 0.09 },
                    }
                };

                OutputStatusMessage("-----\nAddAdGroups:");
                AddAdGroupsResponse addAdGroupsResponse = await CampaignManagementExampleHelper.AddAdGroupsAsync(
                    campaignId: (long)campaignIds[0],
                    adGroups: adGroups,
                    returnInheritedBidStrategyTypes: false);
                long?[] adGroupIds = addAdGroupsResponse.AdGroupIds.ToArray();
                BatchError[] adGroupErrors = addAdGroupsResponse.PartialErrors.ToArray();
                OutputStatusMessage("AdGroupIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(adGroupIds);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(adGroupErrors);
                
                // Add labels and associate them with the campaign and ad group.

                var random = new Random();
                var labels = new List<Label>();

                for (var labelIndex = 0; labelIndex < 5; labelIndex++)
                {
                    var color = string.Format("#{0:X6}", random.Next(0x100000));
                    labels.Add(new Label
                    {
                        ColorCode = color,
                        Description = "Label Description",
                        Name = "Label Name " + color + " " + DateTime.UtcNow
                    });
                }

                OutputStatusMessage("-----\nAddLabels:");
                AddLabelsResponse addLabelsResponse = await CampaignManagementExampleHelper.AddLabelsAsync(labels);
                long?[] nullableLabelIds = addLabelsResponse.LabelIds.ToArray();
                BatchError[] labelErrors = addLabelsResponse.PartialErrors.ToArray();
                OutputStatusMessage("LabelIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(nullableLabelIds);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(labelErrors);
                
                var labelIds = GetNonNullableIds(nullableLabelIds);

                OutputStatusMessage("-----\nGetLabelsByIds:");
                var getLabelsByIdsResponse = await CampaignManagementExampleHelper.GetLabelsByIdsAsync(
                    labelIds: labelIds,
                    pageInfo: new Paging
                    {
                        Index = 0,
                        Size = MaxGetLabelsByIds
                    }
                );
                var getLabels = getLabelsByIdsResponse.Labels;
                labelErrors = getLabelsByIdsResponse.PartialErrors.ToArray();
                OutputStatusMessage("Labels:");
                CampaignManagementExampleHelper.OutputArrayOfLabel(getLabels);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(labelErrors);
                
                var campaignLabelAssociations = CreateExampleLabelAssociationsByEntityId((long)campaignIds[0], labelIds);
                OutputStatusMessage("-----\nAssociating all of the labels with a campaign...");
                CampaignManagementExampleHelper.OutputArrayOfLabelAssociation(campaignLabelAssociations);
                var setLabelAssociationsResponse = await CampaignManagementExampleHelper.SetLabelAssociationsAsync(
                    entityType: EntityType.Campaign, 
                    labelAssociations: campaignLabelAssociations);
                
                var adGroupLabelAssociations = CreateExampleLabelAssociationsByEntityId((long)adGroupIds[0], labelIds);
                OutputStatusMessage("-----\nAssociating all of the labels with an ad group...");
                CampaignManagementExampleHelper.OutputArrayOfLabelAssociation(adGroupLabelAssociations);
                setLabelAssociationsResponse = await CampaignManagementExampleHelper.SetLabelAssociationsAsync(
                    entityType: EntityType.AdGroup,
                    labelAssociations: adGroupLabelAssociations);
                
                OutputStatusMessage("-----\nUse paging to get all campaign label associations...");
                var getLabelAssociationsByLabelIds = await GetLabelAssociationsByLabelIdsHelperAsync(
                    CampaignManagementExampleHelper,
                    entityType: EntityType.Campaign,
                    labelIds: labelIds);
                CampaignManagementExampleHelper.OutputArrayOfLabelAssociation(getLabelAssociationsByLabelIds);

                OutputStatusMessage("-----\nUse paging to get all ad group label associations...");
                getLabelAssociationsByLabelIds = await GetLabelAssociationsByLabelIdsHelperAsync(
                    CampaignManagementExampleHelper: CampaignManagementExampleHelper,
                    entityType: EntityType.AdGroup,
                    labelIds: labelIds);
                CampaignManagementExampleHelper.OutputArrayOfLabelAssociation(getLabelAssociationsByLabelIds);
                
                OutputStatusMessage("-----\nGet label associations for the campaigns...");
                var getLabelAssociationsByEntityIds = await GetLabelAssociationsByEntityIdsHelperAsync(
                    CampaignManagementExampleHelper: CampaignManagementExampleHelper,
                    entityType: EntityType.Campaign,
                    entityIds: GetNonNullableIds(campaignIds)
                );
                CampaignManagementExampleHelper.OutputArrayOfLabelAssociation(getLabelAssociationsByEntityIds);

                OutputStatusMessage("-----\nGet label associations for the ad groups...");
                getLabelAssociationsByEntityIds = await GetLabelAssociationsByEntityIdsHelperAsync(
                    CampaignManagementExampleHelper: CampaignManagementExampleHelper,
                    entityType: EntityType.AdGroup,
                    entityIds: GetNonNullableIds(adGroupIds)
                );
                CampaignManagementExampleHelper.OutputArrayOfLabelAssociation(getLabelAssociationsByEntityIds);
                
                OutputStatusMessage("-----\nDelete all label associations that we set above...");

                // Deleting the associations is not necessary if you are deleting the corresponding campaign(s), as the 
                // contained ad groups, ads, and associations would also be deleted.

                var deleteLabelAssociationsResponse = await CampaignManagementExampleHelper.DeleteLabelAssociationsAsync(
                    entityType: EntityType.Campaign,
                    labelAssociations: campaignLabelAssociations);
                deleteLabelAssociationsResponse = await CampaignManagementExampleHelper.DeleteLabelAssociationsAsync(
                    entityType: EntityType.AdGroup,
                    labelAssociations: adGroupLabelAssociations);
                
                // Delete the account's labels. 

                OutputStatusMessage("-----\nDeleteLabels:");
                var deleteLabelsResponse = await CampaignManagementExampleHelper.DeleteLabelsAsync(
                    labelIds: labelIds);

                foreach (var id in labelIds)
                {
                    OutputStatusMessage(string.Format("Deleted Label Id {0}", id));
                }

                // Delete the campaign and everything it contains e.g., ad groups and ads.

                OutputStatusMessage("-----\nDeleteCampaigns:");
                await CampaignManagementExampleHelper.DeleteCampaignsAsync(
                    accountId: authorizationData.AccountId,
                    campaignIds: new[] { (long)campaignIds[0] });
                OutputStatusMessage(string.Format("Deleted Campaign Id {0}", campaignIds[0]));
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Campaign Management service exceptions
            catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.ApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.EditorialApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }

        private static List<LabelAssociation> CreateExampleLabelAssociationsByEntityId(long entityId, List<long> labelIds)
        {
            var labelAssociations = new List<LabelAssociation>();
            foreach (var labelId in labelIds)
            {
                labelAssociations.Add(
                    new LabelAssociation
                    {
                        EntityId = entityId,
                        LabelId = labelId
                    }
                );
            }
            return labelAssociations;
        }

        private async Task<List<LabelAssociation>> GetLabelAssociationsByLabelIdsHelperAsync(
            CampaignManagementExampleHelper CampaignManagementExampleHelper,
            EntityType entityType,
            IList<long> labelIds
            )
        {
            var labelAssociations = new List<LabelAssociation>();
            var labelIdsPageIndex = 0;

            while (labelIdsPageIndex * MaxLabelIdsForGetLabelAssociations < labelIds.Count)
            {
                var getLabelIds =
                    labelIds.Skip(labelIdsPageIndex++ * MaxLabelIdsForGetLabelAssociations).Take(MaxLabelIdsForGetLabelAssociations).ToList();

                var labelAssociationsPageIndex = 0;
                var foundLastPage = false;

                while (!foundLastPage)
                {
                    var getLabelAssociationsByLabelIds = await CampaignManagementExampleHelper.GetLabelAssociationsByLabelIdsAsync(
                        entityType: entityType,
                        labelIds: getLabelIds,
                        pageInfo: new Paging
                        {
                            Index = labelAssociationsPageIndex++,
                            Size = MaxPagingSize
                        }
                    ).ConfigureAwait(continueOnCapturedContext: false);

                    labelAssociations.AddRange(getLabelAssociationsByLabelIds.LabelAssociations);
                    foundLastPage = MaxPagingSize > getLabelAssociationsByLabelIds.LabelAssociations.Count;
                }
            }

            return labelAssociations;
        }

        private async Task<List<LabelAssociation>> GetLabelAssociationsByEntityIdsHelperAsync(
            CampaignManagementExampleHelper CampaignManagementExampleHelper,
            EntityType entityType,
            IList<long> entityIds
            )
        {
            var labelAssociations = new List<LabelAssociation>();
            var entityIdsPageIndex = 0;

            while (entityIdsPageIndex * MaxEntityIdsForGetLabelAssociations < entityIds.Count)
            {
                var getEntityIds =
                    entityIds.Skip(entityIdsPageIndex++ * MaxEntityIdsForGetLabelAssociations).Take(MaxEntityIdsForGetLabelAssociations).ToList();

                var getLabelAssociationsByEntityIds = await CampaignManagementExampleHelper.GetLabelAssociationsByEntityIdsAsync(
                    entityIds: getEntityIds,
                    entityType: entityType
                ).ConfigureAwait(continueOnCapturedContext: false);

                labelAssociations.AddRange(getLabelAssociationsByEntityIds.LabelAssociations);
            }

            return labelAssociations;
        }
    }
}
package com.microsoft.bingads.examples.v13;

import java.util.Random;
import java.rmi.RemoteException;
import java.util.Calendar;
import java.util.List;

import com.microsoft.bingads.*;
import com.microsoft.bingads.v13.campaignmanagement.*;

public class Labels extends ExampleBase {

    static java.lang.Integer MAX_GET_LABELS_BY_IDS = 1000;
    static java.lang.Integer MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS = 1;
    static java.lang.Integer MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS = 100;
    static java.lang.Integer MAX_PAGING_SIZE = 1000;
        
    public static void main(java.lang.String[] args) {
    
        try
        {
            authorizationData = getAuthorizationData();
             
            CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
                authorizationData, 
                API_ENVIRONMENT,
                ICampaignManagementService.class);

            // Add an ad group in a campaign. Later we will create labels for them. 
            // Although not included in this example you can also create labels for ads and keywords. 

            ArrayOfCampaign campaigns = new ArrayOfCampaign();
            Campaign campaign = new Campaign();
            campaign.setBudgetType(BudgetLimitType.DAILY_BUDGET_STANDARD);
            campaign.setDailyBudget(50.00);
            ArrayOfstring languages = new ArrayOfstring();
            languages.getStrings().add("All");
            campaign.setLanguages(languages);
            campaign.setName("Everyone's Shoes " + System.currentTimeMillis());
            campaign.setTimeZone("PacificTimeUSCanadaTijuana");
            campaigns.getCampaigns().add(campaign);

            outputStatusMessage("-----\nAddCampaigns:");
            AddCampaignsResponse addCampaignsResponse = CampaignManagementExampleHelper.addCampaigns(
                    authorizationData.getAccountId(), 
                    campaigns);            
            ArrayOfNullableOflong campaignIds = addCampaignsResponse.getCampaignIds();
            ArrayOfBatchError campaignErrors = addCampaignsResponse.getPartialErrors();
            outputStatusMessage("CampaignIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(campaignIds);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(campaignErrors);

            // Add an ad group within the campaign.
            
            ArrayOfAdGroup adGroups = new ArrayOfAdGroup();
            AdGroup adGroup = new AdGroup();
            adGroup.setName("Everyone's Red Shoe Sale");
            adGroup.setStartDate(null);
            Calendar calendar = Calendar.getInstance();
            adGroup.setEndDate(new com.microsoft.bingads.v13.campaignmanagement.Date());
            adGroup.getEndDate().setDay(31);
            adGroup.getEndDate().setMonth(12);
            adGroup.getEndDate().setYear(calendar.get(Calendar.YEAR));
            Bid CpcBid = new Bid();
            CpcBid.setAmount(0.09);
            adGroup.setCpcBid(CpcBid);
            adGroups.getAdGroups().add(adGroup);

            outputStatusMessage("-----\nAddAdGroups:");
            AddAdGroupsResponse addAdGroupsResponse = CampaignManagementExampleHelper.addAdGroups(
                    campaignIds.getLongs().get(0), 
                    adGroups, 
                    false);
            ArrayOfNullableOflong adGroupIds = addAdGroupsResponse.getAdGroupIds();
            ArrayOfBatchError adGroupErrors = addAdGroupsResponse.getPartialErrors();
            outputStatusMessage("CampaignIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(adGroupIds);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(adGroupErrors); 

            // Add labels and associate them with the campaign and ad group.
            
            Random random = new Random();
            ArrayOfLabel labels = new ArrayOfLabel();

            for (int labelIndex = 0; labelIndex < 5; labelIndex++)
            {
                java.lang.String color = String.format("#%06x", random.nextInt(0x100000));
                Label label = new Label();
                label.setColorCode(color);
                label.setDescription("Label Description");
                label.setName("Label Name " + color + " " + System.currentTimeMillis());
                labels.getLabels().add(label);
            }
            
            outputStatusMessage("-----\nAddLabels:");
            AddLabelsResponse addLabelsResponse = CampaignManagementExampleHelper.addLabels(labels);
            ArrayOfNullableOflong labelIds = addLabelsResponse.getLabelIds();
            ArrayOfBatchError labelErrors = addLabelsResponse.getPartialErrors();
            outputStatusMessage("LabelIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(labelIds);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(labelErrors);
            
            ArrayOflong getLabelIds = getNonNullableIds(labelIds);

            Paging paging = new Paging();
            paging.setIndex(0);
            paging.setSize(MAX_GET_LABELS_BY_IDS);

            outputStatusMessage("-----\nGetLabelsByIds:");
            GetLabelsByIdsResponse getLabelsByIdsResponse = CampaignManagementExampleHelper.getLabelsByIds(
                getLabelIds,
                paging);
            outputStatusMessage("Labels:");
            CampaignManagementExampleHelper.outputArrayOfLabel(getLabelsByIdsResponse.getLabels());
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(labelErrors);

            ArrayOfLabelAssociation campaignLabelAssociations = createExampleLabelAssociationsByEntityId(
                    campaignIds.getLongs().get(0), 
                    getLabelIds);
            outputStatusMessage("-----\nAssociating all of the labels with a campaign...");
            CampaignManagementExampleHelper.outputArrayOfLabelAssociation(campaignLabelAssociations);
            SetLabelAssociationsResponse setLabelAssociationsResponse = CampaignManagementExampleHelper.setLabelAssociations(
                    EntityType.CAMPAIGN, 
                    campaignLabelAssociations);

            ArrayOfLabelAssociation adGroupLabelAssociations = createExampleLabelAssociationsByEntityId(
                    adGroupIds.getLongs().get(0), 
                    getLabelIds);
            outputStatusMessage("-----\nAssociating all of the labels with an ad group...");
            CampaignManagementExampleHelper.outputArrayOfLabelAssociation(adGroupLabelAssociations);
            setLabelAssociationsResponse = CampaignManagementExampleHelper.setLabelAssociations(
                    EntityType.AD_GROUP, 
                    adGroupLabelAssociations);

            outputStatusMessage("-----\nUse paging to get all campaign label associations...");
            ArrayOfLabelAssociation getLabelAssociationsByLabelIds = getLabelAssociationsByLabelIdsHelper(
                EntityType.CAMPAIGN,
                getLabelIds);
            CampaignManagementExampleHelper.outputArrayOfLabelAssociation(getLabelAssociationsByLabelIds);

            outputStatusMessage("-----\nUse paging to get all ad group label associations...");
            getLabelAssociationsByLabelIds = getLabelAssociationsByLabelIdsHelper(
                EntityType.AD_GROUP,
                getLabelIds);
            CampaignManagementExampleHelper.outputArrayOfLabelAssociation(getLabelAssociationsByLabelIds);

            outputStatusMessage("-----\nGet label associations for the campaigns...");
            ArrayOfLabelAssociation getLabelAssociationsByEntityIds = getLabelAssociationsByEntityIdsHelper(
                EntityType.CAMPAIGN,
                getNonNullableIds(campaignIds));
            CampaignManagementExampleHelper.outputArrayOfLabelAssociation(getLabelAssociationsByEntityIds);

            outputStatusMessage("-----\nGet label associations for the ad groups...");
            getLabelAssociationsByEntityIds = getLabelAssociationsByEntityIdsHelper(
                EntityType.AD_GROUP,
                getNonNullableIds(adGroupIds));
            CampaignManagementExampleHelper.outputArrayOfLabelAssociation(getLabelAssociationsByEntityIds);

            outputStatusMessage("-----\nDelete all label associations that we set above...");

            // Deleting the associations is not necessary if you are deleting the corresponding campaign(s), as the 
            // contained ad groups, keywords, ads, and associations would also be deleted.

            DeleteLabelAssociationsResponse deleteLabelAssociationsResponse = CampaignManagementExampleHelper.deleteLabelAssociations(
                    EntityType.CAMPAIGN, 
                    campaignLabelAssociations);
            deleteLabelAssociationsResponse = CampaignManagementExampleHelper.deleteLabelAssociations(
                    EntityType.AD_GROUP, 
                    adGroupLabelAssociations);

            // Deleting the campaign(s) removes the corresponding label associations but not remove the labels.

            outputStatusMessage("-----\nDeleteLabels:");
            DeleteLabelsResponse deleteLabelsResponse = CampaignManagementExampleHelper.deleteLabels(
                    getLabelIds);
            
            for (java.lang.Long id : getLabelIds.getLongs())
            {
                outputStatusMessage(String.format("Deleted Label Id %s", id));
            }

            // Delete the campaign and everything it contains e.g., ad groups and ads.

            outputStatusMessage("-----\nDeleteCampaigns:");
            ArrayOflong deleteCampaignIds = new ArrayOflong();
            deleteCampaignIds.getLongs().add(campaignIds.getLongs().get(0));
            CampaignManagementExampleHelper.deleteCampaigns(
                    authorizationData.getAccountId(), 
                    deleteCampaignIds);
            outputStatusMessage(String.format("Deleted CampaignId %d", deleteCampaignIds.getLongs().get(0))); 
        } 
        catch (Exception ex) {
            String faultXml = ExampleExceptionHelper.getBingAdsExceptionFaultXml(ex, System.out);
            outputStatusMessage(faultXml);
            String message = ExampleExceptionHelper.handleBingAdsSDKException(ex, System.out);
            outputStatusMessage(message);
        }
    }
    
    static ArrayOfLabelAssociation createExampleLabelAssociationsByEntityId(java.lang.Long entityId, ArrayOflong labelIds)
    {
        ArrayOfLabelAssociation labelAssociations = new ArrayOfLabelAssociation();
        for (java.lang.Long labelId : labelIds.getLongs())
        {
            LabelAssociation labelAssociation = new LabelAssociation();
            labelAssociation.setEntityId(entityId);
            labelAssociation.setLabelId(labelId);
            labelAssociations.getLabelAssociations().add(labelAssociation);
        }
        return labelAssociations;
    }

    static ArrayOfLabelAssociation getLabelAssociationsByLabelIdsHelper(
        EntityType entityType,
        ArrayOflong labelIds
        ) throws Exception, RemoteException
    {
        ArrayOfLabelAssociation labelAssociations = new ArrayOfLabelAssociation();
        int labelIdsPageIndex = 0;

        while (labelIdsPageIndex * MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS < labelIds.getLongs().size())
        {
            int startIndex = labelIdsPageIndex++ * MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS;
            int toIndex = labelIds.getLongs().size() - startIndex - MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS < 0 ? 
                    labelIds.getLongs().size() : 
                    startIndex + MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS;
            List<java.lang.Long> idSubList = labelIds.getLongs().subList(startIndex, toIndex);
            ArrayOflong getLabelIds = new ArrayOflong();
            for (java.lang.Long id : idSubList){
                getLabelIds.getLongs().add(id);
            }
            
            int labelAssociationsPageIndex = 0;
            boolean foundLastPage = false;
            
            Paging paging = new Paging();
            paging.setSize(MAX_PAGING_SIZE);

            while (!foundLastPage)
            {               
                paging.setIndex(labelAssociationsPageIndex++);
                GetLabelAssociationsByLabelIdsResponse getLabelAssociationsByLabelIds = CampaignManagementExampleHelper.getLabelAssociationsByLabelIds(
                    entityType,
                    getLabelIds,
                    paging
                );

                labelAssociations.getLabelAssociations().addAll(getLabelAssociationsByLabelIds.getLabelAssociations().getLabelAssociations());
                foundLastPage = MAX_PAGING_SIZE > getLabelAssociationsByLabelIds.getLabelAssociations().getLabelAssociations().size();
            }
        }

        return labelAssociations;
    }

    static ArrayOfLabelAssociation getLabelAssociationsByEntityIdsHelper(
        EntityType entityType,
        ArrayOflong entityIds
        ) throws Exception, RemoteException
    {
        ArrayOfLabelAssociation labelAssociations = new ArrayOfLabelAssociation();
        int entityIdsPageIndex = 0;

        while (entityIdsPageIndex * MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS < entityIds.getLongs().size())
        {
            int startIndex = entityIdsPageIndex++ * MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS;
            int toIndex = entityIds.getLongs().size() - startIndex - MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS < 0 ? 
                    entityIds.getLongs().size() : 
                    startIndex + MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS;
            List<java.lang.Long> idSubList = entityIds.getLongs().subList(startIndex, toIndex);
            ArrayOflong getEntityIds = new ArrayOflong();
            for (java.lang.Long id : idSubList){
                getEntityIds.getLongs().add(id);
            }

            GetLabelAssociationsByEntityIdsResponse getLabelAssociationsByEntityIds = CampaignManagementExampleHelper.getLabelAssociationsByEntityIds(
                getEntityIds,
                entityType
            );

            labelAssociations.getLabelAssociations().addAll(getLabelAssociationsByEntityIds.getLabelAssociations().getLabelAssociations());
        }

        return labelAssociations;
    }
    
    static ArrayOflong getNonNullableIds(ArrayOfNullableOflong nullableIds)
    {
        ArrayOflong ids = new ArrayOflong();
        for (java.lang.Long nullableId : nullableIds.getLongs())
        {
            ids.getLongs().add(nullableId);
        }
        return ids;
    }
 }
<?php

namespace Microsoft\BingAds\Samples\V13;

// For more information about installing and using the Bing Ads PHP SDK, 
// see https://go.microsoft.com/fwlink/?linkid=838593.

require_once __DIR__ . "/../vendor/autoload.php";

include __DIR__ . "/AuthHelper.php";
include __DIR__ . "/CampaignManagementExampleHelper.php";

use SoapVar;
use SoapFault;
use Exception;

//Specify the Microsoft\BingAds\V13\CampaignManagement classes that will be used.
use Microsoft\BingAds\V13\CampaignManagement\Campaign;
use Microsoft\BingAds\V13\CampaignManagement\CampaignType;
use Microsoft\BingAds\V13\CampaignManagement\Label;
use Microsoft\BingAds\V13\CampaignManagement\LabelAssociation;
use Microsoft\BingAds\V13\CampaignManagement\Paging;
use Microsoft\BingAds\V13\CampaignManagement\EntityType;
use Microsoft\BingAds\V13\CampaignManagement\AdGroup;
use Microsoft\BingAds\V13\CampaignManagement\Keyword;
use Microsoft\BingAds\V13\CampaignManagement\ExpandedTextAd;
use Microsoft\BingAds\V13\CampaignManagement\Bid;
use Microsoft\BingAds\V13\CampaignManagement\MatchType;
use Microsoft\BingAds\V13\CampaignManagement\BudgetLimitType;
use Microsoft\BingAds\V13\CampaignManagement\Date;

// Specify the Microsoft\BingAds\Auth classes that will be used.
use Microsoft\BingAds\Auth\ServiceClient;
use Microsoft\BingAds\Auth\ServiceClientType;

// Specify the Microsoft\BingAds\Samples classes that will be used.
use Microsoft\BingAds\Samples\V13\AuthHelper;
use Microsoft\BingAds\Samples\V13\CampaignManagementExampleHelper;

$GLOBALS['MaxGetLabelsByIds'] = 1000;
$GLOBALS['MaxLabelIdsForGetLabelAssociations'] = 1;
$GLOBALS['MaxEntityIdsForGetLabelAssociations'] = 100;
$GLOBALS['MaxPagingSize'] = 1000;
    
try
{
    // Authenticate user credentials and set the account ID for the sample.  
    AuthHelper::Authenticate();

    // Add an ad group in a campaign. Later we will create labels for them. 
    // Although not included in this example you can also create labels for ads and keywords. 
    
    $campaigns = array();   
    $campaign = new Campaign();
    $campaign->Name = "Women's Shoes " . $_SERVER['REQUEST_TIME'];
    $campaign->BudgetType = BudgetLimitType::DailyBudgetStandard;
    $campaign->DailyBudget = 50.00;
    $campaign->Languages = array("All");
    $campaign->TimeZone = "PacificTimeUSCanadaTijuana";
    $campaigns[] = $campaign;
    
    print("-----\r\nAddCampaigns:\r\n");
    $addCampaignsResponse = CampaignManagementExampleHelper::AddCampaigns(
        $GLOBALS['AuthorizationData']->AccountId, 
        $campaigns
    );
    $campaignIds = $addCampaignsResponse->CampaignIds;
    print("CampaignIds:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLong($campaignIds);
    print("PartialErrors:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfBatchError($addCampaignsResponse->PartialErrors);

    $adGroups = array();
    $adGroup = new AdGroup();
    $adGroup->CpcBid = new Bid();
    $adGroup->CpcBid->Amount = 0.09;
    date_default_timezone_set('UTC');
    $endDate = new Date();
    $endDate->Day = 31;
    $endDate->Month = 12;
    $endDate->Year = date("Y");
    $adGroup->EndDate = $endDate;
    $adGroup->Name = "Women's Red Shoe Sale";    
    $adGroup->StartDate = null;    
    $adGroups[] = $adGroup;
 
    print("-----\r\nAddAdGroups:\r\n");
    $addAdGroupsResponse = CampaignManagementExampleHelper::AddAdGroups(
        $campaignIds->long[0], 
        $adGroups,
        null
    );
    $adGroupIds = $addAdGroupsResponse->AdGroupIds;
    print("AdGroupIds:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLong($adGroupIds);
    print("PartialErrors:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfBatchError($addAdGroupsResponse->PartialErrors);

    // Add labels and associate them with the campaign and ad group.

    $labels = array();

    for ($labelIndex = 0; $labelIndex < 5; $labelIndex++)
    {
        $color = "#".substr("000000".dechex(rand()),-6); 
        $label = new Label();
        $label->ColorCode = $color;
        $label->Description = "Label Description";
        $label->Name = "Label Name " . $color . " " . $_SERVER['REQUEST_TIME'];
        $labels[] = $label;
    }
    
    print("-----\r\nAddLabels:\r\n");
    $addLabelsResponse = CampaignManagementExampleHelper::AddLabels(
        $labels
    );
    $labelIds = $addLabelsResponse->LabelIds;
    $labelErrors = $addLabelsResponse->PartialErrors;
    print("LabelIds:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLong($labelIds);
    print("PartialErrors:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfBatchError($labelErrors);

    $labelsPaging = new Paging();
    $labelsPaging->Index = 0;
    $labelsPaging->Size = $GLOBALS['MaxGetLabelsByIds'];

    print("-----\r\nGetLabelsByIds:\r\n");
    $getLabelsByIdsResponse = CampaignManagementExampleHelper::GetLabelsByIds(
        $labelIds,
        $labelsPaging
    );
    print("Labels:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLabel($getLabelsByIdsResponse->Labels);
    print("PartialErrors:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfBatchError($getLabelsByIdsResponse->PartialErrors);

    $campaignLabelAssociations = CreateExampleLabelAssociationsByEntityId($campaignIds->long[0], $labelIds);
    print("-----\nAssociating all of the labels with a campaign...\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLabelAssociation($campaignLabelAssociations);
    $setLabelAssociationsResponse = CampaignManagementExampleHelper::SetLabelAssociations(
        EntityType::Campaign, 
        $campaignLabelAssociations
    );

    $adGroupLabelAssociations = CreateExampleLabelAssociationsByEntityId($adGroupIds->long[0], $labelIds);
    print("-----\nAssociating all of the labels with an ad group...\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLabelAssociation($adGroupLabelAssociations);
    $setLabelAssociationsResponse = CampaignManagementExampleHelper::SetLabelAssociations(
        EntityType::AdGroup, 
        $adGroupLabelAssociations
    );

    print("-----\nUse paging to get all campaign label associations...\r\n");
    $getLabelAssociationsByLabelIds = GetLabelAssociationsByLabelIdsHelper(
        EntityType::Campaign,
        $labelIds
    );

    print("-----\nUse paging to get all ad group label associations...\r\n");
    $getLabelAssociationsByLabelIds = GetLabelAssociationsByLabelIdsHelper(
        EntityType::AdGroup,
        $labelIds
    );

    print("-----\nGet all label associations for all specified campaigns...\r\n");
    $getLabelAssociationsByEntityIds = GetLabelAssociationsByEntityIdsHelper(
        EntityType::Campaign,
        $campaignIds
    );

    print("-----\nGet all label associations for all specified ad groups...\r\n");
    $getLabelAssociationsByEntityIds = GetLabelAssociationsByEntityIdsHelper(
        EntityType::AdGroup,
        $adGroupIds
    );

    print("-----\nDelete all label associations that we set above....\r\n");

    // Deleting the associations is not necessary if you are deleting the corresponding campaign(s), as the 
    // contained ad groups, ads, and associations would also be deleted.

    $deleteLabelAssociationsResponse = CampaignManagementExampleHelper::DeleteLabelAssociations(
        EntityType::Campaign, 
        $campaignLabelAssociations
    );
    $deleteLabelAssociationsResponse = CampaignManagementExampleHelper::DeleteLabelAssociations(
        EntityType::AdGroup, 
        $adGroupLabelAssociations
    );

    // Delete the account's labels. 

    print("-----\r\nDeleteLabels:\r\n");
    $deleteLabelsResponse = CampaignManagementExampleHelper::DeleteLabels(
        $labelIds
    );

    foreach ($labelIds->long as $id)
    {
        printf("Deleted Label Id %s\r\n", $id);
    }

    // Delete the campaign and everything it contains e.g., ad groups and ads.

    print("-----\r\nDeleteCampaigns:\r\n");
    CampaignManagementExampleHelper::DeleteCampaigns(
        $GLOBALS['AuthorizationData']->AccountId, 
        array($campaignIds->long[0])
    );
    printf("Deleted CampaignId %s\r\n", $campaignIds->long[0]);
}
catch (SoapFault $e)
{
    printf("-----\r\nFault Code: %s\r\nFault String: %s\r\nFault Detail: \r\n", $e->faultcode, $e->faultstring);
    var_dump($e->detail);
    print "-----\r\nLast SOAP request/response:\r\n";
    print $GLOBALS['Proxy']->GetWsdl() . "\r\n";
    print $GLOBALS['Proxy']->GetService()->__getLastRequest()."\r\n";
    print $GLOBALS['Proxy']->GetService()->__getLastResponse()."\r\n";
}
catch (Exception $e)
{
    // Ignore fault exceptions that we already caught.
    if ($e->getPrevious())
    { ; }
    else
    {
        print $e->getCode()." ".$e->getMessage()."\n\n";
        print $e->getTraceAsString()."\n\n";
    }
}

function CreateExampleLabelAssociationsByEntityId(
    $entityId, 
    $labelIds)
{
    $labelAssociations = array();
    foreach ($labelIds->long as $labelId)
    {
        $labelAssociation = new LabelAssociation();
        $labelAssociation->EntityId = $entityId;
        $labelAssociation->LabelId = $labelId;
        $labelAssociations[] = $labelAssociation;
    }
    return $labelAssociations;
}

function GetLabelAssociationsByLabelIdsHelper(
    $entityType,
    $labelIds)
{
    $labelAssociations = array();
    $labelIdsPageIndex = 0;

    while ($labelIdsPageIndex * $GLOBALS['MaxLabelIdsForGetLabelAssociations'] < count($labelIds->long))
    {
        $getLabelIds = array_slice(
            $labelIds->long, 
            $labelIdsPageIndex++ * $GLOBALS['MaxLabelIdsForGetLabelAssociations'], 
            $GLOBALS['MaxLabelIdsForGetLabelAssociations']
        );

        $labelAssociationsPageIndex = 0;
        $foundLastPage = false;

        while (!$foundLastPage)
        {
            $labelsPaging = new Paging();
            $labelsPaging->Index = $labelAssociationsPageIndex++;
            $labelsPaging->Size = $GLOBALS['MaxPagingSize'];

            $getLabelAssociationsByLabelIds = CampaignManagementExampleHelper::GetLabelAssociationsByLabelIds(
                $entityType,
                $getLabelIds,
                $labelsPaging
            );
            
            CampaignManagementExampleHelper::OutputArrayOfLabelAssociation($getLabelAssociationsByLabelIds->LabelAssociations);

            $labelAssociations = array_merge(
                $labelAssociations, 
                $getLabelAssociationsByLabelIds->LabelAssociations->LabelAssociation
            );

            $foundLastPage = $GLOBALS['MaxPagingSize'] > count($getLabelAssociationsByLabelIds->LabelAssociations->LabelAssociation);
        }
    }

    return $labelAssociations;
}

function GetLabelAssociationsByEntityIdsHelper(
    $entityType,
    $entityIds)
{
    $labelAssociations = array();
    $entityIdsPageIndex = 0;

    while ($entityIdsPageIndex * $GLOBALS['MaxEntityIdsForGetLabelAssociations'] < count($entityIds->long))
    {
        $getEntityIds = array_slice(
            $entityIds->long, 
            $entityIdsPageIndex++ * $GLOBALS['MaxEntityIdsForGetLabelAssociations'], 
            $GLOBALS['MaxEntityIdsForGetLabelAssociations']
        );
        
        $getLabelAssociationsByEntityIds = CampaignManagementExampleHelper::GetLabelAssociationsByEntityIds(
            $getEntityIds,
            $entityType
        );

        CampaignManagementExampleHelper::OutputArrayOfLabelAssociation($getLabelAssociationsByEntityIds->LabelAssociations);        
        
        $labelAssociations = array_merge(
            $labelAssociations, 
            $getLabelAssociationsByEntityIds->LabelAssociations->LabelAssociation
        );
    }

    return $labelAssociations;
}
import uuid
import random
from auth_helper import *
from openapi_client.models.campaign import *

# Constants for pagination
MAX_GET_LABELS_BY_IDS = 1000
MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS = 1
MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS = 100
MAX_PAGING_SIZE = 1000

def create_label_associations_by_entity_id(entity_id, label_ids):
    """
    Create label associations for a given entity ID and label IDs.
    
    Args:
        entity_id: The entity ID (campaign or ad group)
        label_ids: List of label IDs to associate
        
    Returns:
        List of LabelAssociation objects
    """
    label_associations = []
    for label_id in label_ids:
        association = LabelAssociation(
            entity_id=entity_id,
            label_id=label_id
        )
        label_associations.append(association)
    return label_associations

def get_label_associations_by_label_ids_helper(campaign_service, entity_type, label_ids):
    """
    Get all label associations by label IDs with pagination.
    
    Args:
        campaign_service: The campaign service client
        entity_type: The entity type (Campaign or AdGroup)
        label_ids: List of label IDs
    """
    print(f"Getting label associations by label IDs for {entity_type}...")
    
    label_associations = []
    label_ids_page_index = 0
    
    while label_ids_page_index * MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS < len(label_ids):
        get_label_ids = label_ids[
            label_ids_page_index * MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS:
            (label_ids_page_index + 1) * MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS
        ]
        label_ids_page_index += 1
        
        label_associations_page_index = 0
        found_last_page = False
        
        while not found_last_page:
            paging = Paging(
                index=label_associations_page_index,
                size=MAX_PAGING_SIZE
            )
            label_associations_page_index += 1
            
            get_associations_request = GetLabelAssociationsByLabelIdsRequest(
                entity_type=entity_type,
                label_ids=get_label_ids,
                page_info=paging
            )
            
            get_associations_response = campaign_service.get_label_associations_by_label_ids(
                get_label_associations_by_label_ids_request=get_associations_request
            )
            
            associations = get_associations_response.LabelAssociations
            if associations:
                label_associations.extend(associations)
                found_last_page = len(associations) < MAX_PAGING_SIZE
            else:
                found_last_page = True
    
    print(f"  Found {len(label_associations)} label associations")

def get_label_associations_by_entity_ids_helper(campaign_service, entity_type, entity_ids):
    """
    Get all label associations by entity IDs with pagination.
    
    Args:
        campaign_service: The campaign service client
        entity_type: The entity type (Campaign or AdGroup)
        entity_ids: List of entity IDs
    """
    print(f"Getting label associations by entity IDs for {entity_type}...")
    
    label_associations = []
    entity_ids_page_index = 0
    
    while entity_ids_page_index * MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS < len(entity_ids):
        get_entity_ids = entity_ids[
            entity_ids_page_index * MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS:
            (entity_ids_page_index + 1) * MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS
        ]
        entity_ids_page_index += 1
        
        get_associations_request = GetLabelAssociationsByEntityIdsRequest(
            entity_type=entity_type,
            entity_ids=get_entity_ids
        )
        
        get_associations_response = campaign_service.get_label_associations_by_entity_ids(
            get_label_associations_by_entity_ids_request=get_associations_request
        )
        
        associations = get_associations_response.LabelAssociations
        if associations:
            label_associations.extend(associations)
    
    print(f"  Found {len(label_associations)} label associations")

def main(authorization_data):
    try:
        # Create a campaign
        print("Creating campaign...")
        
        campaign = Campaign(
            name="Women's Shoes " + str(uuid.uuid4()),
            budget_type=BudgetLimitType.DAILYBUDGETSTANDARD,
            daily_budget=50.00,
            languages=['All'],
            time_zone='PacificTimeUSCanadaTijuana'
        )
        
        add_campaigns_request = AddCampaignsRequest(
            account_id=authorization_data.account_id,
            campaigns=[campaign]
        )
        
        add_campaigns_response = campaign_service.add_campaigns(
            add_campaigns_request=add_campaigns_request
        )
        
        campaign_ids = add_campaigns_response.CampaignIds
        print(f"Created Campaign ID: {campaign_ids[0]}")
        
        # Create an ad group
        print("\nCreating ad group...")
        
        current_year = datetime.now().year
        
        ad_group = AdGroup(
            name="Ad Group Women's Red Shoe Sale" + str(uuid.uuid4())[:8],
            cpc_bid=Bid(amount=0.09),
            end_date=Date(day=31, month=12, year=current_year)
        )
        
        add_ad_groups_request = AddAdGroupsRequest(
            campaign_id=campaign_ids[0],
            ad_groups=[ad_group]
        )
        
        add_ad_groups_response = campaign_service.add_ad_groups(
            add_ad_groups_request=add_ad_groups_request
        )
        
        ad_group_ids = add_ad_groups_response.AdGroupIds
        print(f"Created Ad Group ID: {ad_group_ids[0]}")
        
        # Create labels
        print("\nCreating labels...")
        
        labels = []
        for i in range(5):
            # Generate random color code
            color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
            label = Label(
                color_code=color,
                description='Label Description',
                name=f'Label Name {color} {str(uuid.uuid4())[:8]}'
            )
            labels.append(label)
        
        add_labels_request = AddLabelsRequest(
            labels=labels
        )
        
        add_labels_response = campaign_service.add_labels(
            add_labels_request=add_labels_request
        )
        
        label_ids = add_labels_response.LabelIds
        print(f"Created Label IDs: {label_ids}")
        
        if add_labels_response.PartialErrors:
            print(f"Partial Errors: {add_labels_response.PartialErrors}")
        
        # Get labels by IDs
        print("\nGetting labels by IDs...")
        
        paging = Paging(
            index=0,
            size=MAX_GET_LABELS_BY_IDS
        )
        
        get_labels_request = GetLabelsByIdsRequest(
            label_ids=label_ids,
            page_info=paging
        )
        
        get_labels_response = campaign_service.get_labels_by_ids(
            get_labels_by_ids_request=get_labels_request
        )
        
        retrieved_labels = get_labels_response.Labels
        print(f"Retrieved {len(retrieved_labels)} labels")
        
        # Associate labels with campaign
        print("\nAssociating all labels with campaign...")
        
        campaign_label_associations = create_label_associations_by_entity_id(
            campaign_ids[0],
            label_ids
        )
        
        set_campaign_associations_request = SetLabelAssociationsRequest(
            entity_type=EntityType.CAMPAIGN,
            label_associations=campaign_label_associations
        )
        
        set_campaign_associations_response = campaign_service.set_label_associations(
            set_label_associations_request=set_campaign_associations_request
        )
        
        if set_campaign_associations_response.PartialErrors:
            print(f"Partial Errors: {set_campaign_associations_response.PartialErrors}")
        else:
            print("Campaign label associations set successfully")
        
        # Associate labels with ad group
        print("\nAssociating all labels with ad group...")
        
        ad_group_label_associations = create_label_associations_by_entity_id(
            ad_group_ids[0],
            label_ids
        )
        
        set_ad_group_associations_request = SetLabelAssociationsRequest(
            entity_type=EntityType.ADGROUP,
            label_associations=ad_group_label_associations
        )
        
        set_ad_group_associations_response = campaign_service.set_label_associations(
            set_label_associations_request=set_ad_group_associations_request
        )
        
        if set_ad_group_associations_response.PartialErrors:
            print(f"Partial Errors: {set_ad_group_associations_response.PartialErrors}")
        else:
            print("Ad group label associations set successfully")
        
        # Get label associations by label IDs for campaigns
        print("\nGetting campaign label associations by label IDs (with paging)...")
        get_label_associations_by_label_ids_helper(
            campaign_service,
            EntityType.CAMPAIGN,
            label_ids
        )
        
        # Get label associations by label IDs for ad groups
        print("\nGetting ad group label associations by label IDs (with paging)...")
        get_label_associations_by_label_ids_helper(
            campaign_service,
            EntityType.ADGROUP,
            label_ids
        )
        
        # Get label associations by entity IDs for campaigns
        print("\nGetting label associations by campaign entity IDs...")
        get_label_associations_by_entity_ids_helper(
            campaign_service,
            EntityType.CAMPAIGN,
            campaign_ids
        )
        
        # Get label associations by entity IDs for ad groups
        print("\nGetting label associations by ad group entity IDs...")
        get_label_associations_by_entity_ids_helper(
            campaign_service,
            EntityType.ADGROUP,
            ad_group_ids
        )
        
        # Delete label associations
        print("\nDeleting label associations...")
        
        # Delete campaign label associations
        delete_campaign_associations_request = DeleteLabelAssociationsRequest(
            entity_type=EntityType.CAMPAIGN,
            label_associations=campaign_label_associations
        )
        
        delete_campaign_associations_response = campaign_service.delete_label_associations(
            delete_label_associations_request=delete_campaign_associations_request
        )
        
        if delete_campaign_associations_response.PartialErrors:
            print(f"Campaign Partial Errors: {delete_campaign_associations_response.PartialErrors}")
        else:
            print("Campaign label associations deleted successfully")
        
        # Delete ad group label associations
        delete_ad_group_associations_request = DeleteLabelAssociationsRequest(
            entity_type=EntityType.ADGROUP,
            label_associations=ad_group_label_associations
        )
        
        delete_ad_group_associations_response = campaign_service.delete_label_associations(
            delete_label_associations_request=delete_ad_group_associations_request
        )
        
        if delete_ad_group_associations_response.PartialErrors:
            print(f"Ad Group Partial Errors: {delete_ad_group_associations_response.PartialErrors}")
        else:
            print("Ad group label associations deleted successfully")
        
        # Delete labels
        print("\nDeleting labels...")
        
        delete_labels_request = DeleteLabelsRequest(
            label_ids=label_ids
        )
        
        delete_labels_response = campaign_service.delete_labels(
            delete_labels_request=delete_labels_request
        )
        
        if delete_labels_response.PartialErrors:
            print(f"Partial Errors: {delete_labels_response.PartialErrors}")
        else:
            print(f"Deleted Label IDs: {label_ids}")
        
        # Delete campaign
        print("\nDeleting campaign...")
        
        delete_campaigns_request = DeleteCampaignsRequest(
            account_id=authorization_data.account_id,
            campaign_ids=campaign_ids
        )
        
        campaign_service.delete_campaigns(
            delete_campaigns_request=delete_campaigns_request
        )
        
        print(f"Deleted Campaign ID {campaign_ids[0]}")
        
    except Exception as ex:
        print(f"Error occurred: {str(ex)}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    print("Loading the web service client...")
    
    authorization_data = AuthorizationData(
        account_id=None,
        customer_id=None,
        developer_token=DEVELOPER_TOKEN,
        authentication=None,
    )
    
    authenticate(authorization_data)
    
    campaign_service = ServiceClient(
        service='CampaignManagementService',
        version=13,
        authorization_data=authorization_data,
        environment=ENVIRONMENT,
    )
    
    main(authorization_data)

Vedere anche

Introduzione all'API Bing Ads