Target Criterions Code Example

This example demonstrates how to use target criterions with the Campaign Management API.

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

namespace BingAdsExamplesLibrary.V11
{
    /// <summary>
    /// This example demonstrates how to use target criterions with the Campaign Management API.
    /// </summary>
    public class TargetCriterions : ExampleBase
    {
        public override string Description
        {
            get { return "Target Criterions | Campaign Management V11"; }
        }

        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                CampaignService = new ServiceClient<ICampaignManagementService>(authorizationData);

                List<long> campaignIds = (await GetExampleCampaignIdsAsync(authorizationData)).ToList();
                
                // You can set campaignIds null to get all campaigns in the account, instead of 
                // adding and retrieving the example campaigns.

                var getCampaigns = (await GetCampaignsByIdsAsync(
                    accountId: authorizationData.AccountId,
                    campaignIds: campaignIds,
                    campaignType: AllCampaignTypes)).Campaigns;
                
                // Loop through all campaigns and ad groups to get the target criterion IDs.

                foreach (var campaign in getCampaigns)
                {
                    var campaignId = (long)campaign.Id;

                    // Set campaignCriterionIds null to get all criterions 
                    // (of the specified target criterion type or types) for the current campaign.
                    
                    var campaignCriterions = (await GetCampaignCriterionsByIdsAsync(
                        campaignId: campaignId,
                        campaignCriterionIds: null,
                        criterionType: AllTargetCampaignCriterionTypes))?.CampaignCriterions.ToList();

                    // When you first create a campaign or ad group using the Bing Ads API, it will not have any 
                    // criterions. Effectively, the brand new campaign and ad group target all ages, days, hours, 
                    // devices, genders, and locations. As a best practice, you should consider at a minimum 
                    // adding a campaign location criterion corresponding to the customer market country.

                    if (campaignCriterions == null || campaignCriterions.Count <= 0)
                    {
                        campaignCriterions = new List<CampaignCriterion>();

                        campaignCriterions.Add(new BiddableCampaignCriterion
                        {
                            CampaignId = campaignId,
                            Criterion = new LocationCriterion
                            {
                                // United States
                                LocationId = 190,
                                Type = "LocationCriterion"
                            },
                            CriterionBid = new BidMultiplier
                            {
                                Multiplier = 0
                            },
                            Type = "BiddableCampaignCriterion"
                        });

                        campaignCriterions.Add(new BiddableCampaignCriterion
                        {
                            CampaignId = campaignId,
                            Criterion = new LocationIntentCriterion
                            {
                                IntentOption = IntentOption.PeopleInOrSearchingForOrViewingPages
                            },
                        });

                        var addCampaignCriterionsResponse = await AddCampaignCriterionsAsync(
                            campaignCriterions: campaignCriterions,
                            criterionType: CampaignCriterionType.Targets
                        );
                        
                        // Capture the new criterion IDs.

                        if (addCampaignCriterionsResponse?.CampaignCriterionIds.Count > 0)
                        {
                            var criterionIds = addCampaignCriterionsResponse?.CampaignCriterionIds;
                            for (int index = 0; index < criterionIds.Count; index++)
                            {
                                campaignCriterions[index].Id = criterionIds[index] ?? null;
                            }
                        }
                    }
                    
                    // You can now store or output the campaign criterions.

                    OutputStatusMessage("Campaign Criterions: \n");
                    OutputCampaignCriterions(campaignCriterions);

                    var getAdGroups = (await GetAdGroupsByCampaignIdAsync(
                        campaignId
                    )).AdGroups;

                    // Loop through all ad groups to get the target criterion IDs.
                    foreach (var adGroup in getAdGroups)
                    {
                        var adGroupId = (long)adGroup.Id;

                        // Set adGroupCriterionIds null to get all criterions 
                        // (of the specified target criterion type or types) for the current ad group.
                        var adGroupCriterions = (await GetAdGroupCriterionsByIdsAsync(
                            adGroupId: adGroupId,
                            adGroupCriterionIds: null,
                            criterionType: AllTargetAdGroupCriterionTypes)).AdGroupCriterions.ToList();


                        if(adGroupCriterions != null)
                        {
                            // If the Smartphones device criterion already exists, we'll increase the bid multiplier by 5 percent.

                            var updateAdGroupCriterions = new List<AdGroupCriterion>();
                            foreach (var adGroupCriterion in adGroupCriterions)
                            {
                                var deviceCriterion = adGroupCriterion.Criterion as DeviceCriterion;
                                if (deviceCriterion != null && string.Equals(deviceCriterion.DeviceName, "Smartphones"))
                                {
                                    ((BidMultiplier)((BiddableAdGroupCriterion)adGroupCriterion).CriterionBid).Multiplier *= 1.05;
                                    updateAdGroupCriterions.Add(adGroupCriterion);
                                }
                            }

                            if (updateAdGroupCriterions != null && updateAdGroupCriterions.ToList().Count > 0)
                            {
                                var updateAdGroupCriterionsResponse = await UpdateAdGroupCriterionsAsync(
                                    adGroupCriterions: updateAdGroupCriterions,
                                    criterionType: AdGroupCriterionType.Targets
                                );
                            }

                            // You can now store or output the ad group criterions.

                            OutputStatusMessage("Ad Group Criterions: ");
                            OutputAdGroupCriterions(adGroupCriterions);
                        }
                    }
                }

                // Delete the campaign and ad group that were previously added. 

                await DeleteCampaignsAsync(authorizationData.AccountId, new[] { campaignIds[0] });
                OutputStatusMessage(string.Format("\nDeleted Campaign Id {0}\n", 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<AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<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<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 async Task<IList<long>> GetExampleCampaignIdsAsync(AuthorizationData authorizationData)
        {
            var campaigns = new[]{
                new Campaign
                {
                    Name = "Campaign One " + DateTime.UtcNow,
                    Description = "Red shoes line.",
                    DailyBudget = 20,
                    BudgetType = BudgetLimitType.DailyBudgetStandard,
                    TimeZone = "PacificTimeUSCanadaTijuana",
                },
            };

            var adGroups = new[] {
                new AdGroup
                {
                    Name = "Women's Shoe Sale One " + DateTime.UtcNow,
                    AdDistribution = AdDistribution.Search,
                    SearchBid = new Bid { Amount = 0.09 },
                    Language = "English",
                },
                new AdGroup
                {
                    Name = "Women's Shoe Sale Two " + DateTime.UtcNow,
                    AdDistribution = AdDistribution.Search,
                    SearchBid = new Bid { Amount = 0.09 },
                    Language = "English",
                },
                new AdGroup
                {
                    Name = "Women's Shoe Sale Three " + DateTime.UtcNow,
                    AdDistribution = AdDistribution.Search,
                    SearchBid = new Bid { Amount = 0.09 },
                    Language = "English",
                },
            };

            // Add the campaigns and ad groups

            OutputStatusMessage("Add campaigns:\n");
            AddCampaignsResponse addCampaignsResponse = await AddCampaignsAsync(authorizationData.AccountId, campaigns);
            long?[] nillableCampaignIds = addCampaignsResponse.CampaignIds.ToArray();
            BatchError[] campaignErrors = addCampaignsResponse.PartialErrors.ToArray();
            OutputIds(nillableCampaignIds);
            OutputPartialErrors(campaignErrors);

            OutputStatusMessage("Add ad groups:\n");
            AddAdGroupsResponse addAdGroupsResponse = await AddAdGroupsAsync((long)nillableCampaignIds[0], adGroups);
            long?[] nillableAdGroupIds = addAdGroupsResponse.AdGroupIds.ToArray();
            BatchError[] adGroupErrors = addAdGroupsResponse.PartialErrors.ToArray();
            OutputIds(nillableAdGroupIds);
            OutputPartialErrors(adGroupErrors);
            
            List<long> campaignIds = new List<long>();
            foreach (var campaignId in nillableCampaignIds)
            {
                campaignIds.Add((long)campaignId);
            }

            return campaignIds;
        }
    }
}
package com.microsoft.bingads.examples.v11;

import java.rmi.*;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import com.microsoft.bingads.*;
import com.microsoft.bingads.v11.campaignmanagement.*;

public class TargetCriterions extends ExampleBase {

    static ServiceClient<ICampaignManagementService> CampaignService; 
        
    public static void main(java.lang.String[] args) 
    {
        AuthorizationData authorizationData;
        
        authorizationData = new AuthorizationData();
        authorizationData.setDeveloperToken(DeveloperToken);
        authorizationData.setAuthentication(new PasswordAuthentication(UserName, Password));
        authorizationData.setCustomerId(CustomerId);
        authorizationData.setAccountId(AccountId);
         
        CampaignService = new ServiceClient<ICampaignManagementService>(
                authorizationData, 
                ExampleBase.API_ENVIRONMENT,
                ICampaignManagementService.class);
                        
        ArrayList<CampaignCriterionType> allTargetCampaignCriterionTypes = new ArrayList<CampaignCriterionType>();
        allTargetCampaignCriterionTypes.add(CampaignCriterionType.AGE);
        allTargetCampaignCriterionTypes.add(CampaignCriterionType.DAY_TIME);
        allTargetCampaignCriterionTypes.add(CampaignCriterionType.DEVICE);
        allTargetCampaignCriterionTypes.add(CampaignCriterionType.GENDER);
        allTargetCampaignCriterionTypes.add(CampaignCriterionType.LOCATION);
        allTargetCampaignCriterionTypes.add(CampaignCriterionType.LOCATION_INTENT);
        allTargetCampaignCriterionTypes.add(CampaignCriterionType.RADIUS);
                
        ArrayList<AdGroupCriterionType> allTargetAdGroupCriterionTypes = new ArrayList<AdGroupCriterionType>();
        allTargetAdGroupCriterionTypes.add(AdGroupCriterionType.AGE);
        allTargetAdGroupCriterionTypes.add(AdGroupCriterionType.DAY_TIME);
        allTargetAdGroupCriterionTypes.add(AdGroupCriterionType.DEVICE);
        allTargetAdGroupCriterionTypes.add(AdGroupCriterionType.GENDER);
        allTargetAdGroupCriterionTypes.add(AdGroupCriterionType.LOCATION);
        allTargetAdGroupCriterionTypes.add(AdGroupCriterionType.LOCATION_INTENT);
        allTargetAdGroupCriterionTypes.add(AdGroupCriterionType.RADIUS);
        
        try
        {
            ArrayOflong campaignIds = GetExampleCampaignIds(authorizationData);
                     
            ArrayList<CampaignType> campaignTypes = new ArrayList<CampaignType>();
            campaignTypes.add(CampaignType.DYNAMIC_SEARCH_ADS);
            campaignTypes.add(CampaignType.SHOPPING);
            campaignTypes.add(CampaignType.SEARCH_AND_CONTENT);
            
            // You can set campaignIds null to get all campaigns in the account, instead of 
            // adding and retrieving the example campaigns.
            
            ArrayOfCampaign getCampaigns = getCampaignsByIds(
                    authorizationData.getAccountId(),
                    campaignIds,
                    campaignTypes);
            
            // Loop through all campaigns and ad groups to get the target criterion IDs.

            for(Campaign campaign: getCampaigns.getCampaigns())
            {
                // Set campaignCriterionIds null to get all criterions 
                // (of the specified target criterion type or types) for the current campaign.
                
                GetCampaignCriterionsByIdsResponse getCampaignCriterionsByIdsResponse = getCampaignCriterionsByIds(
                    campaignIds.getLongs().get(0), 
                    null, 
                    allTargetCampaignCriterionTypes);
                ArrayOfCampaignCriterion campaignCriterions = getCampaignCriterionsByIdsResponse.getCampaignCriterions();

                // When you first create a campaign or ad group using the Bing Ads API, it will not have any 
                // criterions. Effectively, the brand new campaign and ad group target all ages, days, hours, 
                // devices, genders, and locations. As a best practice, you should consider at a minimum 
                // adding a campaign location criterion corresponding to the customer market country.
        		
                if (campaignCriterions == null || campaignCriterions.getCampaignCriterions().size() <= 0)
                {
                    campaignCriterions = new ArrayOfCampaignCriterion();

                    LocationCriterion locationCriterion = new LocationCriterion();
                    locationCriterion.setLocationId((long)190);
                    locationCriterion.setType("LocationCriterion");
        			
                    BidMultiplier criterionBid = new BidMultiplier();
                    criterionBid.setMultiplier(0.0);

                    BiddableCampaignCriterion firstBiddableCriterion = new BiddableCampaignCriterion();
                    firstBiddableCriterion.setCampaignId(campaign.getId());
                    firstBiddableCriterion.setCriterion(locationCriterion);
                    firstBiddableCriterion.setCriterionBid(criterionBid);
                    firstBiddableCriterion.setType("BiddableCampaignCriterion");

                    campaignCriterions.getCampaignCriterions().add(firstBiddableCriterion);

                    LocationIntentCriterion locationIntentCriterion = new LocationIntentCriterion();
                    locationIntentCriterion.setIntentOption(IntentOption.PEOPLE_IN_OR_SEARCHING_FOR_OR_VIEWING_PAGES);

                    BiddableCampaignCriterion secondBiddableCriterion = new BiddableCampaignCriterion();
                    secondBiddableCriterion.setCampaignId(campaign.getId());
                    secondBiddableCriterion.setCriterion(locationIntentCriterion);

                    campaignCriterions.getCampaignCriterions().add(secondBiddableCriterion);

                    ArrayList<CampaignCriterionType> criterionTypes = new ArrayList<CampaignCriterionType>();
		    criterionTypes.add(CampaignCriterionType.TARGETS);
                    AddCampaignCriterionsResponse addCriterionsResponse = addCampaignCriterions(campaignCriterions, criterionTypes);

                    // Capture the new criterion IDs.
        			
                    if(addCriterionsResponse.getCampaignCriterionIds().getLongs().isEmpty())
                    {
                        List<Long> criterionIds = addCriterionsResponse.getCampaignCriterionIds().getLongs();
                        for (int index = 0; index < criterionIds.size(); index++)
                        {
                            campaignCriterions.getCampaignCriterions().get(index).setId(criterionIds.get(index));
                        }
                    }
                }
        		
                // You can now store or output the campaign criterions.

                outputStatusMessage("Campaign Criterions: \n");
                outputCampaignCriterions(campaignCriterions);
                
                List<AdGroup> adGroups = getAdGroupsByCampaignId(campaign.getId()).getAdGroups().getAdGroups();
                
                // Loop through all ad groups to get the target criterion IDs.
                
                for(AdGroup adGroup: adGroups)
                {
                    // Set adGroupCriterionIds null to get all criterions 
                    // (of the specified target criterion type or types) for the current ad group.
                    
                    ArrayOfAdGroupCriterion adGroupCriterions = getAdGroupCriterionsByIds(
                        adGroup.getId(), 
                        null, 
                        allTargetAdGroupCriterionTypes).getAdGroupCriterions();
                    
                    if(adGroupCriterions.getAdGroupCriterions().size() > 0)
                    {
                        // If the Smartphones device criterion already exists, we'll increase the bid multiplier by 5 percent.

                        ArrayOfAdGroupCriterion updateAdGroupCriterions = new ArrayOfAdGroupCriterion();

                        for(AdGroupCriterion adGroupCriterion: adGroupCriterions.getAdGroupCriterions())
                        {
                            if(adGroupCriterion.getCriterion() instanceof DeviceCriterion)
                            {
                                DeviceCriterion deviceCriterion = (DeviceCriterion) adGroupCriterion.getCriterion();
                                if(deviceCriterion.getDeviceName() == "Smartphones")
                                {
                                    double multiplier = ((BidMultiplier)((BiddableAdGroupCriterion)adGroupCriterion).getCriterionBid()).getMultiplier();
                                    ((BidMultiplier)((BiddableAdGroupCriterion)adGroupCriterion).getCriterionBid()).setMultiplier(multiplier * 1.05);
                                    updateAdGroupCriterions.getAdGroupCriterions().add(adGroupCriterion);
                                }
                            }
                        }

                        GetAdGroupCriterionsByIdsResponse getAdGroupCriterionsByIdsResponse = null;

                        if(updateAdGroupCriterions.getAdGroupCriterions().size() > 0)
                        {
                            ArrayList<AdGroupCriterionType> adGroupCriterionTypes = new ArrayList<AdGroupCriterionType>();
                            adGroupCriterionTypes.add(AdGroupCriterionType.TARGETS);

                            UpdateAdGroupCriterionsResponse updateAdGroupCriterionsResponse = updateAdGroupCriterions(
                                    updateAdGroupCriterions, 
                                    adGroupCriterionTypes);
                        }

                        // You can now store or output the ad group criterions.

                        outputStatusMessage("Ad Group Criterions: ");
                        outputAdGroupCriterions(adGroupCriterions);
                    }
                }
            }
            
            // Delete the campaign and ad group that were previously added. 

            deleteCampaigns(authorizationData.getAccountId(), campaignIds);
            System.out.printf("Deleted CampaignId %d\n", campaignIds.getLongs().get(0));
                        
            outputStatusMessage("Program execution completed\n"); 
        }
        // Catch authentication exceptions
        catch (OAuthTokenRequestException ex)
        {
            outputStatusMessage("Couldn't get OAuth tokens. Error: " + ex.getDetails().getError() + "/nDescription: " + ex.getDetails().getDescription());
        }
        // Catch Campaign Management service exceptions
        catch (ApiFaultDetail_Exception ex)
        {
            outputStatusMessage(ex.getMessage());
        }
        catch (AdApiFaultDetail_Exception ex)
        {
            outputStatusMessage(ex.getMessage());
        }
        catch (EditorialApiFaultDetail_Exception ex)
        {
            outputStatusMessage(ex.getMessage());
        }
        // Catch general exception
        catch(Exception e)
        {
            outputStatusMessage(e.getMessage());
        }
    }
    
    private static ArrayOflong GetExampleCampaignIds(AuthorizationData authorizationData)
    {

    	ArrayOfCampaign campaigns = new ArrayOfCampaign();
    	
    	Campaign campaignOne = new Campaign();
    	campaignOne.setName("Campaign One " + Instant.now());
    	campaignOne.setDescription("Red shoes line.");
    	campaignOne.setDailyBudget(20.00);
    	campaignOne.setBudgetType(BudgetLimitType.DAILY_BUDGET_STANDARD);
    	campaignOne.setTimeZone("PacificTimeUSCanadaTijuana");
    	campaigns.getCampaigns().add(campaignOne);
    	
    	ArrayOfAdGroup adGroups = new ArrayOfAdGroup();
    	
    	AdGroup shoesOne = new AdGroup();
    	Bid searchBidOne = new Bid();
    	searchBidOne.setAmount(0.09);
    	List<AdDistribution> distributionListOne = new ArrayList<AdDistribution>();
    	distributionListOne.add(AdDistribution.SEARCH);
    	shoesOne.setName("Women's Shoe Sale One");
    	shoesOne.setLanguage("English");
    	shoesOne.setSearchBid(searchBidOne);
    	shoesOne.setAdDistribution(distributionListOne);
    	adGroups.getAdGroups().add(shoesOne);
    	
    	AdGroup shoesTwo = new AdGroup();
    	Bid searchBidTwo = new Bid();
    	searchBidTwo.setAmount(0.09);
    	List<AdDistribution> distributionListTwo = new ArrayList<AdDistribution>();
    	distributionListTwo.add(AdDistribution.SEARCH);
    	shoesTwo.setName("Women's Shoe Sale Two");
    	shoesTwo.setLanguage("English");
    	shoesTwo.setSearchBid(searchBidTwo);
    	shoesTwo.setAdDistribution(distributionListTwo);
    	adGroups.getAdGroups().add(shoesTwo);
    	
    	AdGroup shoesThree = new AdGroup();
    	Bid searchBidThree = new Bid();
    	searchBidThree.setAmount(0.09);
    	List<AdDistribution> distributionListThree = new ArrayList<AdDistribution>();
    	distributionListThree.add(AdDistribution.SEARCH);
    	shoesThree.setName("Women's Shoe Sale Three");
    	shoesThree.setLanguage("English");
    	shoesThree.setSearchBid(searchBidThree);
    	shoesThree.setAdDistribution(distributionListThree);
    	adGroups.getAdGroups().add(shoesThree);
       
       // Add the campaigns and ad groups
       
       try
       {
            outputStatusMessage("Add campaigns:\n");
            AddCampaignsResponse addCampaignsResponse = addCampaigns(AccountId, campaigns);
            ArrayOfNullableOflong nullableCampaignIds = addCampaignsResponse.getCampaignIds();
            outputIds(nullableCampaignIds);
            outputPartialErrors(addCampaignsResponse.getPartialErrors());

            outputStatusMessage("Add ad groups:\n");
            AddAdGroupsResponse addAdGroupsResponse = addAdGroups(nullableCampaignIds.getLongs().get(0), adGroups);
            ArrayOfNullableOflong nullableAdGroupIds = addAdGroupsResponse.getAdGroupIds();
            outputIds(nullableAdGroupIds);
            outputPartialErrors(addAdGroupsResponse.getPartialErrors());

            ArrayOflong campaignIds = new com.microsoft.bingads.v11.campaignmanagement.ArrayOflong();
            campaignIds.getLongs().add(nullableCampaignIds.getLongs().get(0));

            return campaignIds;
        }
        catch(Exception e)
        {
            outputStatusMessage(e.getMessage());

            return null;
        }
    }
    
    // Adds one or more campaigns to the specified account.

    static AddCampaignsResponse addCampaigns(long accountId, ArrayOfCampaign campaigns) throws RemoteException, Exception
    {
        AddCampaignsRequest request = new AddCampaignsRequest();

        request.setAccountId(accountId);
        request.setCampaigns(campaigns);

        return CampaignService.getService().addCampaigns(request);
    }

    // Deletes one or more campaigns from the specified account.

    static void deleteCampaigns(
            long accountId, 
            ArrayOflong campaignIds) throws RemoteException, Exception
    {
        DeleteCampaignsRequest request = new DeleteCampaignsRequest();

        request.setAccountId(accountId);
        request.setCampaignIds(campaignIds);

        CampaignService.getService().deleteCampaigns(request);
    }

    // Adds one or more ad groups to the specified campaign.

    static AddAdGroupsResponse addAdGroups(long campaignId, ArrayOfAdGroup adGroups) throws RemoteException, Exception
    {
        AddAdGroupsRequest request = new AddAdGroupsRequest();

        request.setCampaignId(campaignId);
        request.setAdGroups(adGroups);

        return CampaignService.getService().addAdGroups(request);
    }


    static ArrayOfCampaign getCampaignsByIds(
                long accountId, 
                ArrayOflong campaignIds,
                ArrayList<CampaignType> campaignType) throws RemoteException, Exception
    {
        GetCampaignsByIdsRequest request = new GetCampaignsByIdsRequest();

        request.setAccountId(accountId);
        request.setCampaignIds(campaignIds);
        request.setCampaignType(campaignType);

        return CampaignService.getService().getCampaignsByIds(request).getCampaigns();
    }

    static GetAdGroupsByCampaignIdResponse getAdGroupsByCampaignId(long campaignId) throws RemoteException, Exception
    {
        GetAdGroupsByCampaignIdRequest request = new GetAdGroupsByCampaignIdRequest();

        request.setCampaignId(campaignId);

        return CampaignService.getService().getAdGroupsByCampaignId(request);
    }
    
    static AddAdGroupCriterionsResponse addAdGroupCriterions(
            ArrayOfAdGroupCriterion adGroupCriterions,
            ArrayList<AdGroupCriterionType> criterionType) throws RemoteException, Exception
    {
        AddAdGroupCriterionsRequest request = new AddAdGroupCriterionsRequest();

        request.setAdGroupCriterions(adGroupCriterions);
        request.setCriterionType(criterionType);

        return CampaignService.getService().addAdGroupCriterions(request);
    }

    static GetAdGroupCriterionsByIdsResponse getAdGroupCriterionsByIds(
        long adGroupId,
        ArrayOflong adGroupCriterionIds,
        ArrayList<AdGroupCriterionType> criterionType) throws RemoteException, Exception
    {
        GetAdGroupCriterionsByIdsRequest request = new GetAdGroupCriterionsByIdsRequest();

        request.setAdGroupCriterionIds(adGroupCriterionIds);
        request.setAdGroupId(adGroupId);
        request.setCriterionType(criterionType);

        return CampaignService.getService().getAdGroupCriterionsByIds(request);
    }
    
    static AddCampaignCriterionsResponse addCampaignCriterions(
            ArrayOfCampaignCriterion campaignCriterions,
            ArrayList<CampaignCriterionType> criterionType) throws RemoteException, Exception
    {
        AddCampaignCriterionsRequest request = new AddCampaignCriterionsRequest();

        request.setCampaignCriterions(campaignCriterions);
        request.setCriterionType(criterionType);

        return CampaignService.getService().addCampaignCriterions(request);
    }

    static GetCampaignCriterionsByIdsResponse getCampaignCriterionsByIds(
        long campaignId,
        ArrayOflong campaignCriterionIds,
        ArrayList<CampaignCriterionType> criterionType) throws RemoteException, Exception
    {
        GetCampaignCriterionsByIdsRequest request = new GetCampaignCriterionsByIdsRequest();

        request.setCampaignCriterionIds(campaignCriterionIds);
        request.setCampaignId(campaignId);
        request.setCriterionType(criterionType);

        return CampaignService.getService().getCampaignCriterionsByIds(request);
    }

    static UpdateAdGroupCriterionsResponse updateAdGroupCriterions(
            ArrayOfAdGroupCriterion adGroupCriterions,
            ArrayList<AdGroupCriterionType> criterionType) throws RemoteException, Exception
    {
        UpdateAdGroupCriterionsRequest request = new UpdateAdGroupCriterionsRequest();

        request.setAdGroupCriterions(adGroupCriterions);
        request.setCriterionType(criterionType);

        return CampaignService.getService().updateAdGroupCriterions(request);
    }
}
<?php

namespace Microsoft\BingAds\Samples\V11;

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

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

include "/../AuthHelper.php";
include "/CampaignManagementHelper.php";
include "/CustomerManagementHelper.php";

use SoapVar;
use SoapFault;
use Exception;

// Specify the Microsoft\BingAds\V11\CampaignManagement classes that will be used.
use Microsoft\BingAds\V11\CampaignManagement\Campaign;
use Microsoft\BingAds\V11\CampaignManagement\AdGroup;
use Microsoft\BingAds\V11\CampaignManagement\BiddableAdGroupCriterion;
use Microsoft\BingAds\V11\CampaignManagement\DeviceCriterion;
use Microsoft\BingAds\V11\CampaignManagement\BidMultiplier;
use Microsoft\BingAds\V11\CampaignManagement\AdGroupCriterion;
use Microsoft\BingAds\V11\CampaignManagement\AdGroupCriterionType;
use Microsoft\BingAds\V11\CampaignManagement\AdGroupCriterionStatus;
use Microsoft\BingAds\V11\CampaignManagement\BiddableCampaignCriterion;
use Microsoft\BingAds\V11\CampaignManagement\CampaignCriterion;
use Microsoft\BingAds\V11\CampaignManagement\LocationCriterion;
use Microsoft\BingAds\V11\CampaignManagement\LocationIntentCriterion;
use Microsoft\BingAds\V11\CampaignManagement\IntentOption;
use Microsoft\BingAds\V11\CampaignManagement\CampaignCriterionType;
use Microsoft\BingAds\V11\CampaignManagement\CampaignCriterionStatus;
use Microsoft\BingAds\V11\CampaignManagement\BudgetLimitType;
use Microsoft\BingAds\V11\CampaignManagement\AdDistribution;
use Microsoft\BingAds\V11\CampaignManagement\Bid;
use Microsoft\BingAds\V11\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\AuthHelper;
use Microsoft\BingAds\Samples\V11\CampaignManagementHelper;
use Microsoft\BingAds\Samples\V11\CustomerManagementHelper;

$GLOBALS['AuthorizationData'] = null;
$GLOBALS['Proxy'] = null;
$GLOBALS['CustomerProxy'] = null; 
$GLOBALS['CampaignProxy'] = null; 

// Disable WSDL caching.

ini_set("soap.wsdl_cache_enabled", "0");
ini_set("soap.wsdl_cache_ttl", "0");

try
{
    // You should authenticate for Bing Ads production services with a Microsoft Account, 
    // instead of providing the Bing Ads username and password set. 
    
    //AuthHelper::AuthenticateWithOAuth();

    // However, authentication with a Microsoft Account is currently not supported in Sandbox,
    // so it is recommended that you set the UserName and Password in sandbox for testing.

    AuthHelper::AuthenticateWithUserName();

    $GLOBALS['CustomerProxy'] = new ServiceClient(ServiceClientType::CustomerManagementVersion11, $GLOBALS['AuthorizationData'], AuthHelper::GetApiEnvironment());

    // Set the GetUser request parameter to an empty user identifier to get the current 
    // authenticated Bing Ads user, and then search for all accounts the user may access.

    $user = CustomerManagementHelper::GetUser(null)->User;

    // For this example we'll use the first account.

    $accounts = CustomerManagementHelper::SearchAccountsByUserId($user->Id)->Accounts;
    $GLOBALS['AuthorizationData']->AccountId = $accounts->Account[0]->Id;
    $GLOBALS['AuthorizationData']->CustomerId = $accounts->Account[0]->ParentCustomerId;

    $GLOBALS['CampaignProxy'] = new ServiceClient(ServiceClientType::CampaignManagementVersion11, $GLOBALS['AuthorizationData'], AuthHelper::GetApiEnvironment());

    $campaignIds = GetExampleCampaignIds();
    
    // You can set campaignIds null to get all campaigns in the account, instead of 
    // adding and retrieving the example campaigns.

    $getCampaigns = CampaignManagementHelper::GetCampaignsByIds(
        $GLOBALS['AuthorizationData']->AccountId, 
        $campaignIds, 
        CampaignManagementHelper::AllCampaignTypes)->Campaigns;
    
    // Loop through all campaigns and ad groups to get the target criterion IDs.

    foreach ($getCampaigns->Campaign as $campaign)
    {
        $campaignId = $campaign->Id;

        // Set campaignCriterionIds null to get all criterions 
        // (of the specified target criterion type or types) for the current campaign.
        
        $campaignCriterions = CampaignManagementHelper::GetCampaignCriterionsByIds(
            $campaignId,
            null,
            CampaignManagementHelper::AllTargetCampaignCriterionTypes)->CampaignCriterions;

        // When you first create a campaign or ad group using the Bing Ads API, it will not have any 
        // criterions. Effectively, the brand new campaign and ad group target all ages, days, hours, 
        // devices, genders, and locations. As a best practice, you should consider at a minimum 
        // adding a campaign location criterion corresponding to the customer market country.

        if(empty($campaignCriterions) || !(isset($campaignCriterions->CampaignCriterion)))
        {
            $campaignCriterions = array();

            $locationBiddableCampaignCriterion = new BiddableCampaignCriterion();
            $locationBiddableCampaignCriterion->CampaignId = $campaignId;
            $locationCriterion = new LocationCriterion();
            $locationCriterion->LocationId = 190;
            $encodedLocationCriterion = new SoapVar($locationCriterion, SOAP_ENC_OBJECT, 'LocationCriterion', $GLOBALS['CampaignProxy']->GetNamespace());
            $locationBiddableCampaignCriterion->Criterion = $encodedLocationCriterion;
            $bidMultiplier = new BidMultiplier();
            $bidMultiplier->Multiplier = 0;
            $encodedBidMultiplier = new SoapVar($bidMultiplier, SOAP_ENC_OBJECT, 'BidMultiplier', $GLOBALS['CampaignProxy']->GetNamespace());
            $locationBiddableCampaignCriterion->CriterionBid = $encodedBidMultiplier;

            $encodedCriterion = new SoapVar($locationBiddableCampaignCriterion, SOAP_ENC_OBJECT, 'BiddableCampaignCriterion', $GLOBALS['CampaignProxy']->GetNamespace());
            $campaignCriterions[] = $encodedCriterion;

            $locationIntentBiddableCampaignCriterion = new BiddableCampaignCriterion();
            $locationIntentBiddableCampaignCriterion->CampaignId = $campaignId;
            $locationIntentCriterion = new LocationIntentCriterion();
            $locationIntentCriterion->IntentOption = IntentOption::PeopleInOrSearchingForOrViewingPages;
            $encodedLocationIntentCriterion = new SoapVar($locationIntentCriterion, SOAP_ENC_OBJECT, 'LocationIntentCriterion', $GLOBALS['CampaignProxy']->GetNamespace());
            $locationIntentBiddableCampaignCriterion->Criterion = $encodedLocationIntentCriterion;

            $encodedCriterion = new SoapVar($locationIntentBiddableCampaignCriterion, SOAP_ENC_OBJECT, 'BiddableCampaignCriterion', $GLOBALS['CampaignProxy']->GetNamespace());
            $campaignCriterions[] = $encodedCriterion;

            $addCampaignCriterionsResponse = CampaignManagementHelper::AddCampaignCriterions(
                $campaignCriterions,
                CampaignCriterionType::Targets
            );

            // Capture the new criterion IDs either via AddCampaignCriterionsResponse or you can call GetCampaignCriterionsByIds.

            $campaignCriterions = CampaignManagementHelper::GetCampaignCriterionsByIds(
                $campaignId,
                null,
                CampaignManagementHelper::AllTargetCampaignCriterionTypes)->CampaignCriterions;
        }
        
        // You can now store or output the campaign criterions.

        print("Campaign Criterions: \n\n");
        if(isset($campaignCriterions->CampaignCriterion)){
            CampaignManagementHelper::OutputCampaignCriterions($campaignCriterions->CampaignCriterion);
        }        

        $getAdGroups = CampaignManagementHelper::GetAdGroupsByCampaignId($campaignId)->AdGroups;

        // Loop through all ad groups to get the target criterion IDs.
        foreach ($getAdGroups->AdGroup as $adGroup)
        {
            $adGroupId = $adGroup->Id;

            // Set adGroupCriterionIds null to get all criterions 
            // (of the specified target criterion type or types) for the current ad group.
            $adGroupCriterions = CampaignManagementHelper::GetAdGroupCriterionsByIds(
                    $adGroupId,
                    null,
                    CampaignManagementHelper::AllTargetAdGroupCriterionTypes)->AdGroupCriterions;

            if (!empty($adGroupCriterions) && isset($adGroupCriterions->AdGroupCriterion))
            {
                // If the Smartphones device criterion already exists, we'll increase the bid multiplier by 5 percent.

                $updateAdGroupCriterions = array();
                foreach($adGroupCriterions->AdGroupCriterion as $adGroupCriterion)
                {
                    if ($adGroupCriterion->Type === "BiddableAdGroupCriterion" && 
                        $adGroupCriterion->Criterion->Type === "DeviceCriterion" && 
                        $adGroupCriterion->Criterion->DeviceName === "Smartphones")
                    {
                        $updateAdGroupCriterion = new BiddableAdGroupCriterion();
                        $updateAdGroupCriterion->Id = $adGroupCriterion->Id;
                        $updateAdGroupCriterion->AdGroupId = $adGroupCriterion->AdGroupId;
                        $deviceCriterion = new DeviceCriterion();
                        $deviceCriterion->DeviceName = $adGroupCriterion->Criterion->DeviceName;
                        $updateAdGroupCriterion->Criterion = new SoapVar($deviceCriterion, SOAP_ENC_OBJECT, 'DeviceCriterion', $GLOBALS['CampaignProxy']->GetNamespace());
                        $criterionBid = new BidMultiplier();
                        $criterionBid->Multiplier = $adGroupCriterion->CriterionBid->Multiplier * 1.05;
                        $updateAdGroupCriterion->CriterionBid = new SoapVar($criterionBid, SOAP_ENC_OBJECT, 'BidMultiplier', $GLOBALS['CampaignProxy']->GetNamespace());

                        $updateAdGroupCriterions[] = new SoapVar($updateAdGroupCriterion, SOAP_ENC_OBJECT, 'BiddableAdGroupCriterion', $GLOBALS['CampaignProxy']->GetNamespace());
                    }
                }
                
                $updateAdGroupCriterionsResponse = CampaignManagementHelper::UpdateAdGroupCriterions(
                    $updateAdGroupCriterions,
                    AdGroupCriterionType::Targets
                );

                $adGroupCriterions = CampaignManagementHelper::GetAdGroupCriterionsByIds(
                    $adGroupId,
                    null,
                    CampaignManagementHelper::AllTargetAdGroupCriterionTypes)->AdGroupCriterions;
                
                // You can now store or output the ad group criterions.

                print("Ad Group Criterions: \n\n");
                if(isset($adGroupCriterions->AdGroupCriterion))
                {
                    CampaignManagementHelper::OutputAdGroupCriterions($adGroupCriterions->AdGroupCriterion);
                }
            }
        }
    }

    // Delete the campaign and ad group that were previously added. 

    CampaignManagementHelper::DeleteCampaigns($GLOBALS['AuthorizationData']->AccountId, array($campaignIds[0]));
    printf("\nDeleted CampaignId %d\n\n", $campaignIds[0]);
}
catch (SoapFault $e)
{
    // Output the last request/response.
	
    print "\nLast SOAP request/response:\n";
    printf("Fault Code: %s\nFault String: %s\n", $e->faultcode, $e->faultstring);
    print $GLOBALS['Proxy']->GetWsdl() . "\n";
    print $GLOBALS['Proxy']->GetService()->__getLastRequest()."\n";
    print $GLOBALS['Proxy']->GetService()->__getLastResponse()."\n";
	
    // Campaign Management service operations can throw AdApiFaultDetail.
    if (isset($e->detail->AdApiFaultDetail))
    {
        // Log this fault.

        print "The operation failed with the following faults:\n";

        $errors = is_array($e->detail->AdApiFaultDetail->Errors->AdApiError)
        ? $e->detail->AdApiFaultDetail->Errors->AdApiError
        : array('AdApiError' => $e->detail->AdApiFaultDetail->Errors->AdApiError);

        // If the AdApiError array is not null, the following are examples of error codes that may be found.
        foreach ($errors as $error)
        {
            print "AdApiError\n";
            printf("Code: %d\nError Code: %s\nMessage: %s\n", $error->Code, $error->ErrorCode, $error->Message);

            switch ($error->Code)
            {
                case 105:  // InvalidCredentials
                    break;
                case 117:  // CallRateExceeded
                    break;
                default:
                    print "Please see MSDN documentation for more details about the error code output above.\n";
                    break;
            }
        }
    }

    // Campaign Management service operations can throw ApiFaultDetail.
    elseif (isset($e->detail->EditorialApiFaultDetail))
    {
        // Log this fault.

        print "The operation failed with the following faults:\n";

        // If the BatchError array is not null, the following are examples of error codes that may be found.
        if (!empty($e->detail->EditorialApiFaultDetail->BatchErrors))
        {
            $errors = is_array($e->detail->EditorialApiFaultDetail->BatchErrors->BatchError)
            ? $e->detail->EditorialApiFaultDetail->BatchErrors->BatchError
            : array('BatchError' => $e->detail->EditorialApiFaultDetail->BatchErrors->BatchError);

            foreach ($errors as $error)
            {
                printf("BatchError at Index: %d\n", $error->Index);
                printf("Code: %d\nError Code: %s\nMessage: %s\n", $error->Code, $error->ErrorCode, $error->Message);

                switch ($error->Code)
                {
                    default:
                        print "Please see MSDN documentation for more details about the error code output above.\n";
                        break;
                }
            }
        }

        // If the EditorialError array is not null, the following are examples of error codes that may be found.
        if (!empty($e->detail->EditorialApiFaultDetail->EditorialErrors))
        {
            $errors = is_array($e->detail->EditorialApiFaultDetail->EditorialErrors->EditorialError)
            ? $e->detail->EditorialApiFaultDetail->EditorialErrors->EditorialError
            : array('BatchError' => $e->detail->EditorialApiFaultDetail->EditorialErrors->EditorialError);

            foreach ($errors as $error)
            {
                printf("EditorialError at Index: %d\n", $error->Index);
                printf("Code: %d\nError Code: %s\nMessage: %s\n", $error->Code, $error->ErrorCode, $error->Message);
                printf("Appealable: %s\nDisapproved Text: %s\nCountry: %s\n", $error->Appealable, $error->DisapprovedText, $error->PublisherCountry);

                switch ($error->Code)
                {
                    default:
                        print "Please see MSDN documentation for more details about the error code output above.\n";
                        break;
                }
            }
        }

        // If the OperationError array is not null, the following are examples of error codes that may be found.
        if (!empty($e->detail->EditorialApiFaultDetail->OperationErrors))
        {
            $errors = is_array($e->detail->EditorialApiFaultDetail->OperationErrors->OperationError)
            ? $e->detail->EditorialApiFaultDetail->OperationErrors->OperationError
            : array('OperationError' => $e->detail->EditorialApiFaultDetail->OperationErrors->OperationError);

            foreach ($errors as $error)
            {
                print "OperationError\n";
                printf("Code: %d\nError Code: %s\nMessage: %s\n", $error->Code, $error->ErrorCode, $error->Message);

                switch ($error->Code)
                {
                    case 106:   // UserIsNotAuthorized
                        break;
                    case 1102:  // CampaignServiceInvalidAccountId
                        break;
                    default:
                        print "Please see MSDN documentation for more details about the error code output above.\n";
                        break;
                }
            }
        }
    }
}
catch (Exception $e)
{
    if ($e->getPrevious())
    {
        ; // Ignore fault exceptions that we already caught.
    }
    else
    {
        print $e->getCode()." ".$e->getMessage()."\n\n";
        print $e->getTraceAsString()."\n\n";
    }
}

function GetExampleCampaignIds()
{
    $campaigns = array();
   
    $campaign = new Campaign();
    $campaign->Name = "Campaign One " . $_SERVER['REQUEST_TIME'];
    $campaign->Description = "Red shoes line.";
    $campaign->BudgetType = BudgetLimitType::DailyBudgetStandard;
    $campaign->DailyBudget = 20.00;
    $campaign->TimeZone = "PacificTimeUSCanadaTijuana";

    $campaigns[] = $campaign;

    
    $adGroups = array();

    date_default_timezone_set('UTC');

    for($index = 0; $index < 3; $index++)
    {
        $adGroup = new AdGroup();
        $adGroup->Name = "Women's Shoe Sale " . $index . " " . $_SERVER['REQUEST_TIME'];
        $adGroup->AdDistribution = AdDistribution::Search;
        $adGroup->StartDate = null;
        $endDate = new Date();
        $endDate->Day = 31;
        $endDate->Month = 12;
        $endDate->Year = date("Y");
        $adGroup->EndDate = $endDate;
        $adGroup->SearchBid = new Bid();
        $adGroup->SearchBid->Amount = 0.09;
        $adGroup->Language = "English";
        $adGroups[] = $adGroup;
    }

    print "AddCampaigns\n";
    $addCampaignsResponse = CampaignManagementHelper::AddCampaigns($GLOBALS['AuthorizationData']->AccountId, $campaigns);
    $nillableCampaignIds = $addCampaignsResponse->CampaignIds->long;
    CampaignManagementHelper::OutputIds($nillableCampaignIds);
    if(isset($addCampaignsResponse->PartialErrors->BatchError)){
        CampaignManagementHelper::OutputPartialErrors($addCampaignsResponse->PartialErrors->BatchError);
    }

    print "AddAdGroups\n";
    $addAdGroupsResponse = CampaignManagementHelper::AddAdGroups($nillableCampaignIds[0], $adGroups);
    $nillableAdGroupIds = $addAdGroupsResponse->AdGroupIds->long;
    CampaignManagementHelper::OutputIds($nillableAdGroupIds);
    if(isset($addAdGroupsResponse->PartialErrors->BatchError)){
        CampaignManagementHelper::OutputPartialErrors($addAdGroupsResponse->PartialErrors->BatchError);
    }

    $campaignIds = array();
    foreach($nillableCampaignIds as $campaignId)
    {
        $campaignIds[] = $campaignId;
    }

    return $campaignIds;
}
from auth_helper import *
from output_helper import *

# You must provide credentials in auth_helper.py.

def get_example_campaign_ids(authorization_data):

    campaigns=campaign_service.factory.create('ArrayOfCampaign')
    campaign=set_elements_to_none(campaign_service.factory.create('Campaign'))
    campaign.CampaignType=['SearchAndContent']
    campaign.Name="Women's Shoes " + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
    campaign.Description='Red shoes line.'
    campaign.DailyBudget=50
    campaign.BudgetType='DailyBudgetStandard'
    campaign.TimeZone='PacificTimeUSCanadaTijuana'
    campaigns.Campaign.append(campaign)

    ad_groups=campaign_service.factory.create('ArrayOfAdGroup')

    for index in range(3):
        ad_group=set_elements_to_none(campaign_service.factory.create('AdGroup'))
        ad_group.Name="Women's Shoe Sale " + str(index)
        ad_group.AdDistribution=['Search']
        search_bid=campaign_service.factory.create('Bid')
        search_bid.Amount=0.09
        ad_group.SearchBid=search_bid
        ad_group.Language='English'
        ad_groups.AdGroup.append(ad_group)

    # Add the campaigns and ad groups

    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('Campaign Ids:')
    output_ids(campaign_ids)
    if hasattr(add_campaigns_response.PartialErrors, 'BatchError'):
        output_partial_errors(add_campaigns_response.PartialErrors)
        
    add_ad_groups_response=campaign_service.AddAdGroups(
        CampaignId=campaign_ids['long'][0],
        AdGroups=ad_groups
    )
    ad_group_ids={
        'long': add_ad_groups_response.AdGroupIds['long'] if add_ad_groups_response.AdGroupIds['long'] else None
    }
    output_status_message("Ad Group Ids:")
    output_ids(ad_group_ids)
    if hasattr(add_ad_groups_response.PartialErrors, 'BatchError'):
        output_partial_errors(add_ad_groups_response.PartialErrors)
    
    return campaign_ids

def main(authorization_data):

    try:
        campaign_ids = get_example_campaign_ids(authorization_data)
                
        # You can set campaign_ids null to get all campaigns in the account, instead of 
        # adding and retrieving the example campaigns.

        get_campaigns=campaign_service.GetCampaignsByIds(
            AccountId=authorization_data.account_id,
            CampaignIds=campaign_ids,
            CampaignType=ALL_CAMPAIGN_TYPES
        ).Campaigns
                        
        # Loop through all campaigns and ad groups to get the target criterion IDs.

        for campaign in get_campaigns['Campaign']:
            campaign_id = campaign.Id

            # Set campaign_criterion_ids null to get all criterions 
            # (of the specified target criterion type or types) for the current campaign.

            get_campaign_criterions_by_ids_response = campaign_service.GetCampaignCriterionsByIds(
                CampaignId=campaign_id,
                CampaignCriterionIds=None,
                CriterionType=ALL_TARGET_CAMPAIGN_CRITERION_TYPES
            )
            campaign_criterions= get_campaign_criterions_by_ids_response.CampaignCriterions['CampaignCriterion'] \
                if hasattr(get_campaign_criterions_by_ids_response.CampaignCriterions, 'CampaignCriterion') \
                else None
            
            # When you first create a campaign or ad group using the Bing Ads API, it will not have any 
            # criterions. Effectively, the brand new campaign and ad group target all ages, days, hours, 
            # devices, genders, and locations. As a best practice, you should consider at a minimum 
            # adding a campaign location criterion corresponding to the customer market country.

            if campaign_criterions is None or len(campaign_criterions['CampaignCriterion']) <= 0:
                campaign_criterions=campaign_service.factory.create('ArrayOfCampaignCriterion')

                # Define the Campaign Location Criterion

                campaign_location_criterion=set_elements_to_none(campaign_service.factory.create('BiddableCampaignCriterion'))
                campaign_location_criterion.Type='BiddableCampaignCriterion'
                campaign_location_criterion.CampaignId=campaign_id

                bid_multiplier=set_elements_to_none(campaign_service.factory.create('BidMultiplier'))
                bid_multiplier.Type='BidMultiplier'
                bid_multiplier.Multiplier=0
                campaign_location_criterion.CriterionBid=bid_multiplier
                
                location_criterion=set_elements_to_none(campaign_service.factory.create('LocationCriterion'))
                location_criterion.Type='LocationCriterion'
                # United States
                location_criterion.LocationId=190
                campaign_location_criterion.Criterion=location_criterion

                campaign_criterions.CampaignCriterion.append(campaign_location_criterion)

                # Define the Campaign Location Intent Criterion

                campaign_location_intent_criterion=set_elements_to_none(campaign_service.factory.create('BiddableCampaignCriterion'))
                campaign_location_intent_criterion.Type='BiddableCampaignCriterion'
                campaign_location_intent_criterion.CampaignId=campaign_id
                
                location_intent_criterion=set_elements_to_none(campaign_service.factory.create('LocationIntentCriterion'))
                location_intent_criterion.Type='LocationIntentCriterion'
                location_intent_criterion.IntentOption='PeopleInOrSearchingForOrViewingPages'
                campaign_location_intent_criterion.Criterion=location_intent_criterion

                campaign_criterions.CampaignCriterion.append(campaign_location_intent_criterion)

                add_campaign_criterions_response = campaign_service.AddCampaignCriterions(
                    CampaignCriterions=campaign_criterions,
                    CriterionType='Targets'
                )
                
                # Capture the new criterion IDs.

                if add_campaign_criterions_response is not None and len(add_campaign_criterions_response.CampaignCriterionIds) > 0:
                    campaign_criterion_ids={
                        'long': add_campaign_criterions_response.CampaignCriterionIds['long'] if add_campaign_criterions_response.CampaignCriterionIds['long'] else None
                    }
                    for index in range(len(campaign_criterion_ids['long'])):
                        campaign_criterions['CampaignCriterion'][index].Id = campaign_criterion_ids['long'][index]
                         
            # You can now store or output the campaign criterions

            output_status_message("Campaign Criterions: \n")
            output_campaign_criterions(campaign_criterions)

            get_ad_groups=campaign_service.GetAdGroupsByCampaignId(
                CampaignId=campaign_id
            )

            # Loop through all ad groups to get the target criterion IDs.
            for ad_group in get_ad_groups['AdGroup']:
                ad_group_id = ad_group.Id

                # Set ad_group_criterion_ids null to get all criterions 
                # (of the specified target criterion type or types) for the current ad group.
                get_ad_group_criterions_by_ids_response = campaign_service.GetAdGroupCriterionsByIds(
                    AdGroupId=ad_group_id,
                    AdGroupCriterionIds=None,
                    CriterionType=ALL_TARGET_AD_GROUP_CRITERION_TYPES
                )
                ad_group_criterions= get_ad_group_criterions_by_ids_response \
                    if hasattr(get_ad_group_criterions_by_ids_response, 'AdGroupCriterion') \
                    else None

                if ad_group_criterions is not None:

                    # If the Smartphones device criterion already exists, we'll increase the bid multiplier by 5 percent.
 
                    update_ad_group_criterions=campaign_service.factory.create('ArrayOfAdGroupCriterion')
                    for ad_group_criterion in ad_group_criterions['AdGroupCriterion']:
                        if ad_group_criterion.Criterion is not None \
                           and ad_group_criterion.Criterion.Type.lower() == 'devicecriterion' \
                           and ad_group_criterion.Criterion.DeviceName.lower() == "smartphones":
                            ad_group_criterion.CriterionBid.Multiplier *= 1.05
                            update_ad_group_criterions.AdGroupCriterion.append(ad_group_criterion)
                        
                    if update_ad_group_criterions is not None and len(update_ad_group_criterions) > 0:
                        update_ad_group_criterions_response = campaign_service.UpdateAdGroupCriterions(
                            AdGroupCriterions=update_ad_group_criterions,
                            CriterionType='Targets'
                        )
                        
                    # You can now store or output the ad group criterions

                    output_status_message("Ad Group Criterions: ")
                    output_ad_group_criterions(ad_group_criterions)

        # Delete the campaign and ad group that were previously added. 
                
        campaign_service.DeleteCampaigns(
            AccountId=authorization_data.account_id,
            CampaignIds=campaign_ids
        )

        for campaign_id in campaign_ids['long']:
            output_status_message("Deleted CampaignId {0}\n".format(campaign_id))

        output_status_message("Program execution completed")

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

# Main execution

if __name__ == '__main__':

    print("Python loads the web service proxies at runtime, so you will observe " \
          "a performance delay between program launch and main execution...\n")

    authorization_data=AuthorizationData(
        account_id=None,
        customer_id=None,
        developer_token=DEVELOPER_TOKEN,
        authentication=None,
    )

    campaign_service_v10=ServiceClient(
        service='CampaignManagementService', 
        authorization_data=authorization_data, 
        environment=ENVIRONMENT,
        version=10,
    )

    campaign_service=ServiceClient(
        service='CampaignManagementService', 
        authorization_data=authorization_data, 
        environment=ENVIRONMENT,
        version=11,
    )
    
    adinsight_service=ServiceClient(
        service='AdInsightService', 
        authorization_data=authorization_data, 
        environment=ENVIRONMENT,
        version=11
    )

    # You should authenticate for Bing Ads production services with a Microsoft Account, 
    # instead of providing the Bing Ads username and password set. 
    # Authentication with a Microsoft Account is currently not supported in Sandbox.       

    authenticate(authorization_data)       

    main(authorization_data)

See Also

Get Started with the Bing Ads API