Labels Code Example

This example demonstrates how to add labels and associate them with campaigns and ad groups.

Tip

Use the language selector in the documentation header to choose C#, Java, Php, or Python.

To get access and refresh tokens for your Microsoft Advertising user and make your first service call using the Bing Ads API, see the Quick Start guide. You'll want to review the Get Started guide and walkthroughs for your preferred language e.g., C#, Java, Php, and Python.

Supporting files for C#, Java, Php, and Python examples are available at GitHub. You can clone each repository or repurpose snippets as needed.

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;
}
from auth_helper import *
from campaignmanagement_example_helper import *
import random

# You must provide credentials in auth_helper.py.

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 main(authorization_data):

    try:
        # 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=campaign_service.factory.create('ArrayOfCampaign')
        campaign=set_elements_to_none(campaign_service.factory.create('Campaign'))
        campaign.BudgetType='DailyBudgetStandard'
        campaign.DailyBudget=50
        languages=campaign_service.factory.create('ns3:ArrayOfstring')
        languages.string.append('All')
        campaign.Languages=languages
        campaign.Name="Women's Shoes " + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
        campaign.TimeZone='PacificTimeUSCanadaTijuana'
        campaigns.Campaign.append(campaign)

        output_status_message("-----\nAddCampaigns:")
        add_campaigns_response=campaign_service.AddCampaigns(
            AccountId=authorization_data.account_id,
            Campaigns=campaigns
        )
        campaign_ids={
            'long': add_campaigns_response.CampaignIds['long'] if add_campaigns_response.CampaignIds['long'] else None
        }
        output_status_message("CampaignIds:")
        output_array_of_long(campaign_ids)
        output_status_message("PartialErrors:")
        output_array_of_batcherror(add_campaigns_response.PartialErrors)
        
        ad_groups=campaign_service.factory.create('ArrayOfAdGroup')
        ad_group=set_elements_to_none(campaign_service.factory.create('AdGroup'))
        ad_group.Name="Women's Red Shoe Sale"
        end_date=campaign_service.factory.create('Date')
        end_date.Day=31
        end_date.Month=12
        current_time=gmtime()
        end_date.Year=current_time.tm_year + 1
        ad_group.EndDate=end_date
        cpc_bid=campaign_service.factory.create('Bid')
        cpc_bid.Amount=0.09
        ad_group.CpcBid=cpc_bid
        ad_groups.AdGroup.append(ad_group)

        output_status_message("-----\nAddAdGroups:")
        add_ad_groups_response=campaign_service.AddAdGroups(
            CampaignId=campaign_ids['long'][0],
            AdGroups=ad_groups,
            ReturnInheritedBidStrategyTypes=False
        )
        ad_group_ids={
            'long': add_ad_groups_response.AdGroupIds['long'] if add_ad_groups_response.AdGroupIds['long'] else None
        }
        output_status_message("AdGroupIds:")
        output_array_of_long(ad_group_ids)
        output_status_message("PartialErrors:")
        output_array_of_batcherror(add_ad_groups_response.PartialErrors)

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

        labels=campaign_service.factory.create('ArrayOfLabel')
        for index in range(5):
            color = "#{0:06x}".format(random.randint(0,100000))
            label=set_elements_to_none(campaign_service.factory.create('Label'))
            label.ColorCode = color
            label.Description = "Label Description"
            label.Name = "Label Name " + color + " " + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
            labels.Label.append(label)
               
        output_status_message("-----\nAddLabels:")
        add_labels_response=campaign_service.AddLabels(
            Labels=labels
        )
        label_ids={
            'long': add_labels_response.LabelIds['long'] if add_labels_response.LabelIds['long'] else None
        }
        output_status_message("LabelIds:")
        output_array_of_long(label_ids)
        output_status_message("PartialErrors:")
        output_array_of_batcherror(add_labels_response.PartialErrors)
                
        paging=set_elements_to_none(campaign_service.factory.create('Paging'))
        paging.Index=0
        paging.Size=10
        
        output_status_message("-----\nGetLabelsByIds:")
        get_labels_by_ids_response = campaign_service.GetLabelsByIds(
            LabelIds=label_ids,
            PageInfo=paging
        )
        output_status_message("Labels:")
        output_array_of_label(get_labels_by_ids_response.Labels)
        output_status_message("PartialErrors:")
        output_array_of_batcherror(add_labels_response.PartialErrors)
                
        campaign_label_associations = create_example_label_associations_by_entity_id(campaign_ids['long'][0], label_ids)
        output_status_message("-----\nAssociating all of the labels with a campaign...")
        output_array_of_labelassociation(campaign_label_associations)
        set_label_associations_response=campaign_service.SetLabelAssociations(
            EntityType='Campaign', 
            LabelAssociations=campaign_label_associations)

        ad_group_label_associations = create_example_label_associations_by_entity_id(ad_group_ids['long'][0], label_ids)
        output_status_message("-----\nAssociating all of the labels with an ad group...")
        output_array_of_labelassociation(ad_group_label_associations)
        set_label_associations_response=campaign_service.SetLabelAssociations(
            EntityType='AdGroup', 
            LabelAssociations=ad_group_label_associations)

        output_status_message("-----\nUse paging to get all campaign label associations...")
        get_label_associations_by_label_ids = get_label_associations_by_label_ids_helper(
            entity_type='Campaign',
            label_ids=label_ids)
        output_array_of_labelassociation(get_label_associations_by_label_ids)

        output_status_message("-----\nUse paging to get all ad group label associations...")
        get_label_associations_by_label_ids = get_label_associations_by_label_ids_helper(
            entity_type='AdGroup',
            label_ids=label_ids)
        output_array_of_labelassociation(get_label_associations_by_label_ids)

        output_status_message("-----\nGet all label associations for the campaigns...")
        get_label_associations_by_entity_ids = get_label_associations_by_entity_ids_helper(
            entity_type='Campaign',
            entity_ids=campaign_ids
        )
        output_array_of_labelassociation(get_label_associations_by_entity_ids)

        output_status_message("-----\nGet all label associations for the ad groups...")
        get_label_associations_by_entity_ids = get_label_associations_by_entity_ids_helper(
            entity_type='AdGroup',
            entity_ids=ad_group_ids
        )
        output_array_of_labelassociation(get_label_associations_by_entity_ids)

        output_status_message("-----\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.

        deleteLabelAssociationsResponse = campaign_service.DeleteLabelAssociations(
            EntityType='Campaign', 
            LabelAssociations=campaign_label_associations)
        deleteLabelAssociationsResponse = campaign_service.DeleteLabelAssociations(
            EntityType='AdGroup', 
            LabelAssociations=ad_group_label_associations)

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

        output_status_message("-----\nDeleteLabels:")
        delete_labels_response = campaign_service.DeleteLabels(
            LabelIds=label_ids)

        for id in label_ids['long']:
            output_status_message("Deleted Label Id {0}".format(id))

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

        output_status_message("-----\nDeleteCampaigns:")
        campaign_service.DeleteCampaigns(
            AccountId=authorization_data.account_id,
            CampaignIds=campaign_ids
        )
        output_status_message("Deleted Campaign Id {0}".format(campaign_ids['long'][0]))

    except WebFault as ex:
        output_webfault_errors(ex)
    except Exception as ex:
        output_status_message(ex)

def create_example_label_associations_by_entity_id(entity_id, label_ids):
    label_associations = campaign_service.factory.create('ArrayOfLabelAssociation')
    for label_id in label_ids['long']:
        label_association = campaign_service.factory.create('LabelAssociation')
        label_association.EntityId = entity_id
        label_association.LabelId = label_id
        label_associations.LabelAssociation.append(label_association)

    return label_associations

def get_label_associations_by_label_ids_helper(entity_type, label_ids):
    label_associations = campaign_service.factory.create('ArrayOfLabelAssociation')
    label_ids_page_index = 0

    while (label_ids_page_index * MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS < len(label_ids['long'])):
        start_index = label_ids_page_index * MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS
        label_ids_page_index += 1
        get_label_ids = list(label_ids['long'][start_index : start_index + MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS])
        
        label_associations_page_index = 0
        found_last_page = False

        while (not found_last_page):
            paging=set_elements_to_none(campaign_service.factory.create('Paging'))
            paging.Index=label_associations_page_index
            label_associations_page_index += 1
            paging.Size=MAX_PAGING_SIZE
            get_label_associations_by_label_ids = campaign_service.GetLabelAssociationsByLabelIds(
                EntityType=entity_type,
                LabelIds={'long': get_label_ids},
                PageInfo=paging
            )

            label_associations.LabelAssociation.extend(get_label_associations_by_label_ids.LabelAssociations['LabelAssociation'])
            found_last_page = MAX_PAGING_SIZE > len(get_label_associations_by_label_ids.LabelAssociations['LabelAssociation'])

    return label_associations

def get_label_associations_by_entity_ids_helper(entity_type, entity_ids):
    label_associations = campaign_service.factory.create('ArrayOfLabelAssociation')
    entity_ids_page_index = 0

    while (entity_ids_page_index * MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS < len(entity_ids['long'])):
        start_index = entity_ids_page_index * MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS
        entity_ids_page_index += 1
        get_entity_ids = list(entity_ids['long'][start_index : start_index + MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS])

        get_label_associations_by_entity_ids = campaign_service.GetLabelAssociationsByEntityIds(
            EntityIds={'long': get_entity_ids},
            EntityType=entity_type
        )

        label_associations.LabelAssociation.extend(get_label_associations_by_entity_ids.LabelAssociations['LabelAssociation'])

    return label_associations

# Main execution
if __name__ == '__main__':

    print("Loading the web service client proxies...")
    
    authorization_data=AuthorizationData(
        account_id=None,
        customer_id=None,
        developer_token=DEVELOPER_TOKEN,
        authentication=None,
    )

    campaign_service=ServiceClient(
        service='CampaignManagementService', 
        version=13,
        authorization_data=authorization_data, 
        environment=ENVIRONMENT,
    )

    authenticate(authorization_data)
        
    main(authorization_data)

See Also

Get Started with the Bing Ads API