Edit

Remarketing Lists Code Example

This example demonstrates how to associate remarketing lists with a new ad group.

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 associate remarketing lists with a new ad group.
    /// </summary>
    public class RemarketingLists : ExampleBase
    {
        public static ServiceClient<ICampaignManagementService> Service;

        public override string Description
        {
            get { return "Remarketing Lists | Campaign Management V13"; }
        }

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

                // Before you can track conversions or target audiences using a remarketing list 
                // you need to create a UET tag, and then add the UET tag tracking code to every page of your website.
                // For more information, please see Universal Event Tracking at https://go.microsoft.com/fwlink/?linkid=829965.

                // First you should call the GetUetTagsByIds operation to check whether a tag has already been created. 
                // You can leave the TagIds element null or empty to request all UET tags available for the customer.

                OutputStatusMessage("-----\nGetUetTagsByIds:");
                var uetTags = (await CampaignManagementExampleHelper.GetUetTagsByIdsAsync(
                    tagIds: null))?.UetTags;

                // If you do not already have a UET tag that can be used, or if you need another UET tag, 
                // call the AddUetTags service operation to create a new UET tag. If the call is successful, 
                // the tracking script that you should add to your website is included in a corresponding 
                // UetTag within the response message. 

                if (uetTags == null || uetTags.Count < 1)
                {
                    var uetTag = new UetTag
                    {
                        Description = "My First Uet Tag",
                        Name = "New Uet Tag",
                    };
                    OutputStatusMessage("-----\nAddUetTags:");
                    uetTags = (await CampaignManagementExampleHelper.AddUetTagsAsync(
                        uetTags: new[] { uetTag })).UetTags;
                }

                if (uetTags == null || uetTags.Count < 1)
                {
                    OutputStatusMessage(
                        string.Format("You do not have any UET tags registered for CustomerId {0}.", authorizationData.CustomerId)
                    );
                    return;
                }

                OutputStatusMessage("List of all UET Tags:");
                CampaignManagementExampleHelper.OutputArrayOfUetTag(uetTags);

                // After you retreive the tracking script from the AddUetTags or GetUetTagsByIds operation, 
                // the next step is to add the UET tag tracking code to your website. 

                // We will use the same UET tag for the remainder of this example.
                var tagId = uetTags[0].Id;
                
                // Add remarketing lists that depend on the UET Tag Id retreived above.

                var addAudiences = new[] {
                    new RemarketingList
                    {
                        Description = "New list with CustomEventsRule",
                        MembershipDuration = 30,
                        Name = "Remarketing List with CustomEventsRule " + DateTime.UtcNow,
                        ParentId = authorizationData.AccountId,
                        // The rule definition is translated to the following logical expression: 
                        // (Category Equals video) and (Action Equals play) and (Label Equals trailer) 
                        // and (Value Equals 5)
                        Rule = new CustomEventsRule
                        {
                            // The type of user interaction you want to track.
                            Action = "play",
                            ActionOperator = StringOperator.Equals,
                            // The category of event you want to track. 
                            Category = "video",
                            CategoryOperator = StringOperator.Equals,
                            // The name of the element that caused the action.
                            Label = "trailer",
                            LabelOperator = StringOperator.Equals,
                            // A numerical value associated with that event. 
                            // Could be length of the video played etc.
                            Value = 5.00m,
                            ValueOperator = NumberOperator.Equals,
                        },
                        Scope = EntityScope.Account,
                        TagId = tagId
                    },
                    new RemarketingList
                    {
                        Description = "New list with PageVisitorsRule",
                        MembershipDuration = 30,
                        Name = "Remarketing List with PageVisitorsRule " + DateTime.UtcNow,
                        ParentId = authorizationData.AccountId,
                        // The rule definition is translated to the following logical expression: 
                        // ((Url Contains X) and (ReferrerUrl DoesNotContain Z)) or ((Url DoesNotBeginWith Y)) 
                        // or ((ReferrerUrl Equals Z))
                        Rule = new PageVisitorsRule
                        {
                            RuleItemGroups = new []
                            {
                                new RuleItemGroup
                                {
                                    Items = new []
                                    {
                                        new StringRuleItem
                                        {
                                            Operand = "Url",
                                            Operator = StringOperator.Contains,
                                            Value = "X"
                                        },
                                        new StringRuleItem
                                        {
                                            Operand = "ReferrerUrl",
                                            Operator = StringOperator.DoesNotContain,
                                            Value = "Z"
                                        },
                                    }
                                },
                                new RuleItemGroup
                                {
                                    Items = new []
                                    {
                                        new StringRuleItem
                                        {
                                            Operand = "Url",
                                            Operator = StringOperator.DoesNotBeginWith,
                                            Value = "Y"
                                        },
                                    }
                                },
                                new RuleItemGroup
                                {
                                    Items = new []
                                    {
                                        new StringRuleItem
                                        {
                                            Operand = "ReferrerUrl",
                                            Operator = StringOperator.Equals,
                                            Value = "Z"
                                        },
                                    }
                                },
                            },
                        },
                        Scope = EntityScope.Account,
                        TagId = tagId
                    },
                    new RemarketingList
                    {
                        Description = "New list with PageVisitorsWhoDidNotVisitAnotherPageRule",
                        MembershipDuration = 30,
                        Name = "Remarketing List with PageVisitorsWhoDidNotVisitAnotherPageRule " + DateTime.UtcNow,
                        ParentId = authorizationData.AccountId,
                        // The rule definition is translated to the following logical expression: 
                        // (((Url Contains X) and (ReferrerUrl DoesNotContain Z)) or ((Url DoesNotBeginWith Y)) 
                        // or ((ReferrerUrl Equals Z))) 
                        // and not (((Url BeginsWith A) and (ReferrerUrl BeginsWith B)) or ((Url Contains C)))
                        Rule = new PageVisitorsWhoDidNotVisitAnotherPageRule
                        {
                            ExcludeRuleItemGroups = new []
                            {
                                new RuleItemGroup
                                {
                                    Items = new []
                                    {
                                        new StringRuleItem
                                        {
                                            Operand = "Url",
                                            Operator = StringOperator.BeginsWith,
                                            Value = "A"
                                        },
                                        new StringRuleItem
                                        {
                                            Operand = "ReferrerUrl",
                                            Operator = StringOperator.BeginsWith,
                                            Value = "B"
                                        },
                                    }
                                },
                                new RuleItemGroup
                                {
                                    Items = new []
                                    {
                                        new StringRuleItem
                                        {
                                            Operand = "Url",
                                            Operator = StringOperator.Contains,
                                            Value = "C"
                                        },
                                    }
                                },
                            },
                            IncludeRuleItemGroups = new []
                            {
                                new RuleItemGroup
                                {
                                    Items = new []
                                    {
                                        new StringRuleItem
                                        {
                                            Operand = "Url",
                                            Operator = StringOperator.Contains,
                                            Value = "X"
                                        },
                                        new StringRuleItem
                                        {
                                            Operand = "ReferrerUrl",
                                            Operator = StringOperator.DoesNotContain,
                                            Value = "Z"
                                        },
                                    }
                                },
                                new RuleItemGroup
                                {
                                    Items = new []
                                    {
                                        new StringRuleItem
                                        {
                                            Operand = "Url",
                                            Operator = StringOperator.DoesNotBeginWith,
                                            Value = "Y"
                                        },
                                    }
                                },
                                new RuleItemGroup
                                {
                                    Items = new []
                                    {
                                        new StringRuleItem
                                        {
                                            Operand = "ReferrerUrl",
                                            Operator = StringOperator.Equals,
                                            Value = "Z"
                                        },
                                    }
                                },
                            },
                        },
                        Scope = EntityScope.Account,
                        TagId = tagId
                    },
                    new RemarketingList
                    {
                        Description = "New list with PageVisitorsWhoVisitedAnotherPageRule",
                        MembershipDuration = 30,
                        Name = "Remarketing List with PageVisitorsWhoVisitedAnotherPageRule " + DateTime.UtcNow,
                        ParentId = authorizationData.AccountId,
                        // The rule definition is translated to the following logical expression: 
                        // (((Url Contains X) and (ReferrerUrl NotEquals Z)) or ((Url DoesNotBeginWith Y)) or 
                        // ((ReferrerUrl Equals Z))) 
                        // and (((Url BeginsWith A) and (ReferrerUrl BeginsWith B)) or ((Url Contains C)))
                        Rule = new PageVisitorsWhoVisitedAnotherPageRule
                        {
                            AnotherRuleItemGroups = new []
                            {
                                new RuleItemGroup
                                {
                                    Items = new []
                                    {
                                        new StringRuleItem
                                        {
                                            Operand = "Url",
                                            Operator = StringOperator.BeginsWith,
                                            Value = "A"
                                        },
                                        new StringRuleItem
                                        {
                                            Operand = "ReferrerUrl",
                                            Operator = StringOperator.BeginsWith,
                                            Value = "B"
                                        },
                                    }
                                },
                                new RuleItemGroup
                                {
                                    Items = new []
                                    {
                                        new StringRuleItem
                                        {
                                            Operand = "Url",
                                            Operator = StringOperator.Contains,
                                            Value = "C"
                                        },
                                    }
                                },
                            },
                            RuleItemGroups = new []
                            {
                                new RuleItemGroup
                                {
                                    Items = new []
                                    {
                                        new StringRuleItem
                                        {
                                            Operand = "Url",
                                            Operator = StringOperator.Contains,
                                            Value = "X"
                                        },
                                        new StringRuleItem
                                        {
                                            Operand = "ReferrerUrl",
                                            Operator = StringOperator.DoesNotContain,
                                            Value = "Z"
                                        },
                                    }
                                },
                                new RuleItemGroup
                                {
                                    Items = new []
                                    {
                                        new StringRuleItem
                                        {
                                            Operand = "Url",
                                            Operator = StringOperator.DoesNotBeginWith,
                                            Value = "Y"
                                        },
                                    }
                                },
                                new RuleItemGroup
                                {
                                    Items = new []
                                    {
                                        new StringRuleItem
                                        {
                                            Operand = "ReferrerUrl",
                                            Operator = StringOperator.Equals,
                                            Value = "Z"
                                        },
                                    }
                                },
                            },
                        },
                        Scope = EntityScope.Account,
                        TagId = tagId
                    },
                };

                // RemarketingList extends the Audience base class. 
                // We manage remarketing lists with Audience operations.

                OutputStatusMessage("-----\nAddAudiences:");
                var addAudiencesResponse = await CampaignManagementExampleHelper.AddAudiencesAsync(
                    audiences: addAudiences);
                long?[] audienceIds = addAudiencesResponse.AudienceIds.ToArray();
                BatchError[] audienceErrors = addAudiencesResponse.PartialErrors.ToArray();
                OutputStatusMessage("AudienceIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(audienceIds);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(audienceErrors);
                
                // Add an ad group in a campaign. The ad group will later be associated with remarketing lists. 

                var campaigns = new[]{
                    new Campaign
                    {
                        BudgetType = BudgetLimitType.DailyBudgetStandard,
                        DailyBudget = 50,
                        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 },

                        // Applicable for all remarketing lists that are associated with this ad group. TargetAndBid indicates 
                        // that you want to show ads only to people included in the remarketing list, with the option to change
                        // the bid amount. Ads in this ad group will only show to people included in the remarketing list.
                        Settings = new[]
                        {
                            new TargetSetting
                            {
                                Details = new []
                                {
                                    new TargetSettingDetail
                                    {
                                        CriterionTypeGroup = CriterionTypeGroup.Audience,
                                        TargetAndBid = true
                                    }
                                }
                            }
                        },
                    }
                };
                
                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);

                // Associate all of the remarketing lists created above with the new ad group.

                var adGroupRemarketingListAssociations = new List<AdGroupCriterion>();                               
                
                foreach (var audienceId in audienceIds)
                {
                    if(audienceId != null)
                    {
                        var biddableAdGroupCriterion = new BiddableAdGroupCriterion
                        {
                            AdGroupId = (long)adGroupIds[0],
                            Criterion = new AudienceCriterion
                            {
                                AudienceId = audienceId,
                                AudienceType = AudienceType.RemarketingList,
                            },
                            CriterionBid = new BidMultiplier
                            {
                                Multiplier = 20.00,
                            },
                            Status = AdGroupCriterionStatus.Active,
                        };

                        adGroupRemarketingListAssociations.Add(biddableAdGroupCriterion);
                    }
                }
                
                OutputStatusMessage("-----\nAddAdGroupCriterions:");
                CampaignManagementExampleHelper.OutputArrayOfAdGroupCriterion(adGroupRemarketingListAssociations);
                AddAdGroupCriterionsResponse addAdGroupCriterionsResponse = await CampaignManagementExampleHelper.AddAdGroupCriterionsAsync(
                        adGroupCriterions: adGroupRemarketingListAssociations,
                        criterionType: AdGroupCriterionType.Audience);
                long?[] nullableAdGroupCriterionIds = addAdGroupCriterionsResponse.AdGroupCriterionIds.ToArray();
                OutputStatusMessage("AdGroupCriterionIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(nullableAdGroupCriterionIds);
                BatchErrorCollection[] adGroupCriterionErrors =
                    addAdGroupCriterionsResponse.NestedPartialErrors.ToArray();
                OutputStatusMessage("NestedPartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchErrorCollection(adGroupCriterionErrors);
                
                // 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]));

                // Delete the remarketing lists.

                OutputStatusMessage("-----\nDeleteAudiences:");
                await CampaignManagementExampleHelper.DeleteAudiencesAsync(
                    audienceIds: new[] { (long)audienceIds[0] });
                OutputStatusMessage(string.Format("Deleted Audience Id {0}", audienceIds[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);
            }
        }

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

import java.util.ArrayList;
import java.util.Calendar;

import com.microsoft.bingads.*;
import com.microsoft.bingads.v13.campaignmanagement.*;
import java.math.BigDecimal;

// How to associate remarketing lists with a new ad group.

public class RemarketingLists extends ExampleBase {
    
    public static void main(java.lang.String[] args) {
     
        try
        {
            authorizationData = getAuthorizationData();
             
            CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
                        authorizationData, 
                        API_ENVIRONMENT,
                        ICampaignManagementService.class);

            // Before you can track conversions or target audiences using a remarketing list 
            // you need to create a UET tag, and then add the UET tag tracking code to every page of your website.
            // For more information, please see Universal Event Tracking at https://go.microsoft.com/fwlink/?linkid=829965.

            // First you should call the GetUetTagsByIds operation to check whether a tag has already been created. 
            // You can leave the TagIds element null or empty to request all UET tags available for the customer.

            outputStatusMessage("-----\nGetUetTagsByIds:");
            GetUetTagsByIdsResponse getUetTagsByIdsResponse = CampaignManagementExampleHelper.getUetTagsByIds(
                    null);
            ArrayOfUetTag uetTags = getUetTagsByIdsResponse.getUetTags();

            // If you do not already have a UET tag that can be used, or if you need another UET tag, 
            // call the AddUetTags service operation to create a new UET tag. If the call is successful, 
            // the tracking script that you should add to your website is included in a corresponding 
            // UetTag within the response message. 

            if (uetTags == null || uetTags.getUetTags().size() < 1)
            {
                UetTag uetTag = new UetTag();
                uetTag.setDescription("My First Uet Tag");
                uetTag.setName("New Uet Tag");
                uetTags.getUetTags().add(uetTag);
                outputStatusMessage("-----\nAddUetTags:");
                uetTags = CampaignManagementExampleHelper.addUetTags(
                    uetTags).getUetTags();
            }

            if (uetTags == null || uetTags.getUetTags().size() < 1)
            {
                outputStatusMessage(
                    String.format("You do not have any UET tags registered for CustomerId {0}.", authorizationData.getCustomerId())
                );
                return;
            }

            outputStatusMessage("List of all UET Tags:");
            CampaignManagementExampleHelper.outputArrayOfUetTag(uetTags);

            // After you retreive the tracking script from the AddUetTags or GetUetTagsByIds operation, 
            // the next step is to add the UET tag tracking code to your website. 

            // We will use the same UET tag for the remainder of this example.
            java.lang.Long tagId = uetTags.getUetTags().get(0).getId();

            // Add remarketing lists that depend on the UET Tag Id retreived above.

            ArrayOfAudience addAudiences = new ArrayOfAudience();
            RemarketingList customEventsList = new RemarketingList();
            customEventsList.setDescription("New list with CustomEventsRule");
            customEventsList.setMembershipDuration(30);
            customEventsList.setName("Remarketing List with CustomEventsRule " + System.currentTimeMillis());
            customEventsList.setParentId(authorizationData.getAccountId());
            // The rule definition is translated to the following logical expression: 
            // (Category Equals video) and (Action Equals play) and (Label Equals trailer) 
            // and (Value Equals 5)
            CustomEventsRule customEventsRule = new CustomEventsRule();
            // The type of user interaction you want to track.
            customEventsRule.setAction("play");
            customEventsRule.setActionOperator(StringOperator.EQUALS);
            // The category of event you want to track. 
            customEventsRule.setCategory("video");
            customEventsRule.setCategoryOperator(StringOperator.EQUALS);
            // The name of the element that caused the action.
            customEventsRule.setLabel("trailer");
            customEventsRule.setLabelOperator(StringOperator.EQUALS);
            // A numerical value associated with that event. 
            // Could be length of the video played etc.
            customEventsRule.setValue(new BigDecimal(5.00));
            customEventsRule.setValueOperator(NumberOperator.EQUALS);
            customEventsList.setRule(customEventsRule);
            customEventsList.setScope(EntityScope.ACCOUNT);
            customEventsList.setTagId(tagId);            
            addAudiences.getAudiences().add(customEventsList);
                        
            RemarketingList pageVisitorsList = new RemarketingList();  
            pageVisitorsList.setDescription("New list with PageVisitorsRule");
            pageVisitorsList.setMembershipDuration(30);
            pageVisitorsList.setName("Remarketing List with PageVisitorsRule " + System.currentTimeMillis());
            pageVisitorsList.setParentId(authorizationData.getAccountId());
            // The rule definition is translated to the following logical expression: 
            // ((Url Contains X) and (ReferrerUrl DoesNotContain Z)) or ((Url DoesNotBeginWith Y)) 
            // or ((ReferrerUrl Equals Z))
            PageVisitorsRule pageVisitorsRule = new PageVisitorsRule();
            ArrayOfRuleItemGroup pageVisitorsRuleItemGroups = new ArrayOfRuleItemGroup();
            RuleItemGroup pageVisitorsRuleItemGroupA = new RuleItemGroup();
            ArrayOfRuleItem pageVisitorsRuleItemsA = new ArrayOfRuleItem();
            StringRuleItem pageVisitorsRuleItemA = new StringRuleItem();
            pageVisitorsRuleItemA.setOperand("Url");
            pageVisitorsRuleItemA.setOperator(StringOperator.CONTAINS);
            pageVisitorsRuleItemA.setValue("X");
            pageVisitorsRuleItemsA.getRuleItems().add(pageVisitorsRuleItemA);   
            StringRuleItem pageVisitorsRuleItemAA = new StringRuleItem();
            pageVisitorsRuleItemAA.setOperand("ReferrerUrl");
            pageVisitorsRuleItemAA.setOperator(StringOperator.DOES_NOT_CONTAIN);
            pageVisitorsRuleItemAA.setValue("Z");
            pageVisitorsRuleItemsA.getRuleItems().add(pageVisitorsRuleItemAA);    
            pageVisitorsRuleItemGroupA.setItems(pageVisitorsRuleItemsA);
            pageVisitorsRuleItemGroups.getRuleItemGroups().add(pageVisitorsRuleItemGroupA);
            RuleItemGroup pageVisitorsRuleItemGroupB = new RuleItemGroup();
            ArrayOfRuleItem pageVisitorsRuleItemsB = new ArrayOfRuleItem();
            StringRuleItem pageVisitorsRuleItemB = new StringRuleItem();
            pageVisitorsRuleItemB.setOperand("Url");
            pageVisitorsRuleItemB.setOperator(StringOperator.DOES_NOT_BEGIN_WITH);
            pageVisitorsRuleItemB.setValue("Y");
            pageVisitorsRuleItemsB.getRuleItems().add(pageVisitorsRuleItemB);            
            pageVisitorsRuleItemGroupB.setItems(pageVisitorsRuleItemsB);
            pageVisitorsRuleItemGroups.getRuleItemGroups().add(pageVisitorsRuleItemGroupB);
            RuleItemGroup pageVisitorsRuleItemGroupC = new RuleItemGroup();
            ArrayOfRuleItem pageVisitorsRuleItemsC = new ArrayOfRuleItem();
            StringRuleItem pageVisitorsRuleItemC = new StringRuleItem();
            pageVisitorsRuleItemC.setOperand("ReferrerUrl");
            pageVisitorsRuleItemC.setOperator(StringOperator.EQUALS);
            pageVisitorsRuleItemC.setValue("Z");
            pageVisitorsRuleItemsC.getRuleItems().add(pageVisitorsRuleItemC);            
            pageVisitorsRuleItemGroupC.setItems(pageVisitorsRuleItemsC);
            pageVisitorsRuleItemGroups.getRuleItemGroups().add(pageVisitorsRuleItemGroupC);
            pageVisitorsRule.setRuleItemGroups(pageVisitorsRuleItemGroups);
            pageVisitorsList.setRule(pageVisitorsRule);
            pageVisitorsList.setScope(EntityScope.ACCOUNT);
            pageVisitorsList.setTagId(tagId); 
            addAudiences.getAudiences().add(pageVisitorsList);
            
            RemarketingList pageVisitorsWhoDidNotVisitAnotherPageList = new RemarketingList();        
            pageVisitorsWhoDidNotVisitAnotherPageList.setDescription("New list with PageVisitorsWhoDidNotVisitAnotherPageRule");
            pageVisitorsWhoDidNotVisitAnotherPageList.setMembershipDuration(30);
            pageVisitorsWhoDidNotVisitAnotherPageList.setName("Remarketing List with PageVisitorsWhoDidNotVisitAnotherPageRule " + System.currentTimeMillis());
            pageVisitorsWhoDidNotVisitAnotherPageList.setParentId(authorizationData.getAccountId());
            // The rule definition is translated to the following logical expression: 
            // (((Url Contains X) and (ReferrerUrl DoesNotContain Z)) or ((Url DoesNotBeginWith Y)) 
            // or ((ReferrerUrl Equals Z))) 
            // and not (((Url BeginsWith A) and (ReferrerUrl BeginsWith B)) or ((Url Contains C)))
            PageVisitorsWhoDidNotVisitAnotherPageRule pageVisitorsWhoDidNotVisitAnotherPageRule = new PageVisitorsWhoDidNotVisitAnotherPageRule();            
            ArrayOfRuleItemGroup pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroups = new ArrayOfRuleItemGroup();
            RuleItemGroup pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroupA = new RuleItemGroup();
            ArrayOfRuleItem pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsA = new ArrayOfRuleItem();
            StringRuleItem pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemA = new StringRuleItem();
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemA.setOperand("Url");
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemA.setOperator(StringOperator.BEGINS_WITH);
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemA.setValue("A");
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsA.getRuleItems().add(pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemA);   
            StringRuleItem pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemAA = new StringRuleItem();
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemAA.setOperand("ReferrerUrl");
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemAA.setOperator(StringOperator.BEGINS_WITH);
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemAA.setValue("B");
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsA.getRuleItems().add(pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemAA);    
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroupA.setItems(pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsA);
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroups.getRuleItemGroups().add(pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroupA);
            RuleItemGroup pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroupB = new RuleItemGroup();
            ArrayOfRuleItem pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsB = new ArrayOfRuleItem();
            StringRuleItem pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemB = new StringRuleItem();
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemB.setOperand("Url");
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemB.setOperator(StringOperator.CONTAINS);
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemB.setValue("C");
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsB.getRuleItems().add(pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemB);            
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroupB.setItems(pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsB);
            pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroups.getRuleItemGroups().add(pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroupB);
            pageVisitorsWhoDidNotVisitAnotherPageRule.setExcludeRuleItemGroups(pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroups);            
            ArrayOfRuleItemGroup pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroups = new ArrayOfRuleItemGroup();
            RuleItemGroup pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupA = new RuleItemGroup();
            ArrayOfRuleItem pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsA = new ArrayOfRuleItem();
            StringRuleItem pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemA = new StringRuleItem();
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemA.setOperand("Url");
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemA.setOperator(StringOperator.CONTAINS);
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemA.setValue("X");
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsA.getRuleItems().add(pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemA);   
            StringRuleItem pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemAA = new StringRuleItem();
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemAA.setOperand("ReferrerUrl");
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemAA.setOperator(StringOperator.DOES_NOT_CONTAIN);
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemAA.setValue("Z");
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsA.getRuleItems().add(pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemAA);    
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupA.setItems(pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsA);
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroups.getRuleItemGroups().add(pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupA);
            RuleItemGroup pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupB = new RuleItemGroup();
            ArrayOfRuleItem pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsB = new ArrayOfRuleItem();
            StringRuleItem pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemB = new StringRuleItem();
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemB.setOperand("Url");
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemB.setOperator(StringOperator.DOES_NOT_BEGIN_WITH);
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemB.setValue("Y");
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsB.getRuleItems().add(pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemB);            
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupB.setItems(pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsB);
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroups.getRuleItemGroups().add(pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupB);
            RuleItemGroup pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupC = new RuleItemGroup();
            ArrayOfRuleItem pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsC = new ArrayOfRuleItem();
            StringRuleItem pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemC = new StringRuleItem();
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemC.setOperand("ReferrerUrl");
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemC.setOperator(StringOperator.EQUALS);
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemC.setValue("Z");
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsC.getRuleItems().add(pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemC);            
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupC.setItems(pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsC);
            pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroups.getRuleItemGroups().add(pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupC);
            pageVisitorsWhoDidNotVisitAnotherPageRule.setIncludeRuleItemGroups(pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroups);
            pageVisitorsWhoDidNotVisitAnotherPageList.setRule(pageVisitorsWhoDidNotVisitAnotherPageRule);
            pageVisitorsWhoDidNotVisitAnotherPageList.setScope(EntityScope.ACCOUNT);
            pageVisitorsWhoDidNotVisitAnotherPageList.setTagId(tagId);   
            addAudiences.getAudiences().add(pageVisitorsWhoDidNotVisitAnotherPageList);

            RemarketingList pageVisitorsWhoVisitedAnotherPageList = new RemarketingList();  
            pageVisitorsWhoVisitedAnotherPageList.setDescription("New list with PageVisitorsWhoVisitedAnotherPageRule");
            pageVisitorsWhoVisitedAnotherPageList.setMembershipDuration(30);
            pageVisitorsWhoVisitedAnotherPageList.setName("Remarketing List with PageVisitorsWhoVisitedAnotherPageRule " + System.currentTimeMillis());
            pageVisitorsWhoVisitedAnotherPageList.setParentId(authorizationData.getAccountId());
            // The rule definition is translated to the following logical expression: 
            // (((Url Contains X) and (ReferrerUrl NotEquals Z)) or ((Url DoesNotBeginWith Y)) or 
            // ((ReferrerUrl Equals Z))) 
            // and (((Url BeginsWith A) and (ReferrerUrl BeginsWith B)) or ((Url Contains C)))
            PageVisitorsWhoVisitedAnotherPageRule pageVisitorsWhoVisitedAnotherPageRule = new PageVisitorsWhoVisitedAnotherPageRule();            
            ArrayOfRuleItemGroup pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroups = new ArrayOfRuleItemGroup();
            RuleItemGroup pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroupA = new RuleItemGroup();
            ArrayOfRuleItem pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsA = new ArrayOfRuleItem();
            StringRuleItem pageVisitorsWhoVisitedAnotherPageAnotherRuleItemA = new StringRuleItem();
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemA.setOperand("Url");
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemA.setOperator(StringOperator.BEGINS_WITH);
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemA.setValue("A");
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsA.getRuleItems().add(pageVisitorsWhoVisitedAnotherPageAnotherRuleItemA);   
            StringRuleItem pageVisitorsWhoVisitedAnotherPageAnotherRuleItemAA = new StringRuleItem();
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemAA.setOperand("ReferrerUrl");
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemAA.setOperator(StringOperator.BEGINS_WITH);
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemAA.setValue("B");
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsA.getRuleItems().add(pageVisitorsWhoVisitedAnotherPageAnotherRuleItemAA);    
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroupA.setItems(pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsA);
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroups.getRuleItemGroups().add(pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroupA);
            RuleItemGroup pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroupB = new RuleItemGroup();
            ArrayOfRuleItem pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsB = new ArrayOfRuleItem();
            StringRuleItem pageVisitorsWhoVisitedAnotherPageAnotherRuleItemB = new StringRuleItem();
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemB.setOperand("Url");
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemB.setOperator(StringOperator.CONTAINS);
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemB.setValue("C");
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsB.getRuleItems().add(pageVisitorsWhoVisitedAnotherPageAnotherRuleItemB);            
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroupB.setItems(pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsB);
            pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroups.getRuleItemGroups().add(pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroupB);
            pageVisitorsWhoVisitedAnotherPageRule.setAnotherRuleItemGroups(pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroups);            
            ArrayOfRuleItemGroup pageVisitorsWhoVisitedAnotherPageRuleItemGroups = new ArrayOfRuleItemGroup();
            RuleItemGroup pageVisitorsWhoVisitedAnotherPageRuleItemGroupA = new RuleItemGroup();
            ArrayOfRuleItem pageVisitorsWhoVisitedAnotherPageRuleItemsA = new ArrayOfRuleItem();
            StringRuleItem pageVisitorsWhoVisitedAnotherPageRuleItemA = new StringRuleItem();
            pageVisitorsWhoVisitedAnotherPageRuleItemA.setOperand("Url");
            pageVisitorsWhoVisitedAnotherPageRuleItemA.setOperator(StringOperator.CONTAINS);
            pageVisitorsWhoVisitedAnotherPageRuleItemA.setValue("X");
            pageVisitorsWhoVisitedAnotherPageRuleItemsA.getRuleItems().add(pageVisitorsWhoVisitedAnotherPageRuleItemA);   
            StringRuleItem pageVisitorsWhoVisitedAnotherPageRuleItemAA = new StringRuleItem();
            pageVisitorsWhoVisitedAnotherPageRuleItemAA.setOperand("ReferrerUrl");
            pageVisitorsWhoVisitedAnotherPageRuleItemAA.setOperator(StringOperator.DOES_NOT_CONTAIN);
            pageVisitorsWhoVisitedAnotherPageRuleItemAA.setValue("Z");
            pageVisitorsWhoVisitedAnotherPageRuleItemsA.getRuleItems().add(pageVisitorsWhoVisitedAnotherPageRuleItemAA);    
            pageVisitorsWhoVisitedAnotherPageRuleItemGroupA.setItems(pageVisitorsWhoVisitedAnotherPageRuleItemsA);
            pageVisitorsWhoVisitedAnotherPageRuleItemGroups.getRuleItemGroups().add(pageVisitorsWhoVisitedAnotherPageRuleItemGroupA);
            RuleItemGroup pageVisitorsWhoVisitedAnotherPageRuleItemGroupB = new RuleItemGroup();
            ArrayOfRuleItem pageVisitorsWhoVisitedAnotherPageRuleItemsB = new ArrayOfRuleItem();
            StringRuleItem pageVisitorsWhoVisitedAnotherPageRuleItemB = new StringRuleItem();
            pageVisitorsWhoVisitedAnotherPageRuleItemB.setOperand("Url");
            pageVisitorsWhoVisitedAnotherPageRuleItemB.setOperator(StringOperator.DOES_NOT_BEGIN_WITH);
            pageVisitorsWhoVisitedAnotherPageRuleItemB.setValue("Y");
            pageVisitorsWhoVisitedAnotherPageRuleItemsB.getRuleItems().add(pageVisitorsWhoVisitedAnotherPageRuleItemB);            
            pageVisitorsWhoVisitedAnotherPageRuleItemGroupB.setItems(pageVisitorsWhoVisitedAnotherPageRuleItemsB);
            pageVisitorsWhoVisitedAnotherPageRuleItemGroups.getRuleItemGroups().add(pageVisitorsWhoVisitedAnotherPageRuleItemGroupB);
            RuleItemGroup pageVisitorsWhoVisitedAnotherPageRuleItemGroupC = new RuleItemGroup();
            ArrayOfRuleItem pageVisitorsWhoVisitedAnotherPageRuleItemsC = new ArrayOfRuleItem();
            StringRuleItem pageVisitorsWhoVisitedAnotherPageRuleItemC = new StringRuleItem();
            pageVisitorsWhoVisitedAnotherPageRuleItemC.setOperand("ReferrerUrl");
            pageVisitorsWhoVisitedAnotherPageRuleItemC.setOperator(StringOperator.EQUALS);
            pageVisitorsWhoVisitedAnotherPageRuleItemC.setValue("Z");
            pageVisitorsWhoVisitedAnotherPageRuleItemsC.getRuleItems().add(pageVisitorsWhoVisitedAnotherPageRuleItemC);            
            pageVisitorsWhoVisitedAnotherPageRuleItemGroupC.setItems(pageVisitorsWhoVisitedAnotherPageRuleItemsC);
            pageVisitorsWhoVisitedAnotherPageRuleItemGroups.getRuleItemGroups().add(pageVisitorsWhoVisitedAnotherPageRuleItemGroupC);
            pageVisitorsWhoVisitedAnotherPageRule.setRuleItemGroups(pageVisitorsWhoVisitedAnotherPageRuleItemGroups);  
            pageVisitorsWhoVisitedAnotherPageList.setRule(pageVisitorsWhoVisitedAnotherPageRule);
            pageVisitorsWhoVisitedAnotherPageList.setScope(EntityScope.ACCOUNT);
            pageVisitorsWhoVisitedAnotherPageList.setTagId(tagId);   
            addAudiences.getAudiences().add(pageVisitorsWhoVisitedAnotherPageList);    

            // RemarketingList extends the Audience base class. 
            // We manage remarketing lists with Audience operations.

            outputStatusMessage("-----\nAddAudiences:");
            AddAudiencesResponse addAudiencesResponse = CampaignManagementExampleHelper.addAudiences(
                addAudiences);
            ArrayOfNullableOflong audienceIds = addAudiencesResponse.getAudienceIds();
            ArrayOfBatchError audienceErrors = addAudiencesResponse.getPartialErrors();
            outputStatusMessage("AudienceIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(audienceIds);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(audienceErrors);
                            
            // Add an ad group in a campaign. The ad group will later be associated with remarketing lists.

            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);
            
            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);
            // Applicable for all remarketing lists that are associated with this ad group. TargetAndBid indicates 
            // that you want to show ads only to people included in the remarketing list, with the option to change
            // the bid amount. Ads in this ad group will only show to people included in the remarketing list.
            ArrayOfSetting settings = new ArrayOfSetting();
            TargetSetting targetSetting = new TargetSetting();
            ArrayOfTargetSettingDetail targetSettingDetails = new ArrayOfTargetSettingDetail();
            TargetSettingDetail adGroupAudienceTargetSettingDetail = new TargetSettingDetail();
            adGroupAudienceTargetSettingDetail.setCriterionTypeGroup(CriterionTypeGroup.AUDIENCE);
            adGroupAudienceTargetSettingDetail.setTargetAndBid(Boolean.TRUE);
            targetSettingDetails.getTargetSettingDetails().add(adGroupAudienceTargetSettingDetail);
            targetSetting.setDetails(targetSettingDetails);
            settings.getSettings().add(targetSetting);
            adGroup.setSettings(settings);
            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("AdGroupIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(adGroupIds);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(adGroupErrors); 
            
            // Associate all of the remarketing lists created above with the new ad group.

            ArrayOfAdGroupCriterion adGroupRemarketingListAssociations = new ArrayOfAdGroupCriterion();
            ArrayList<AudienceType> audienceTypes = new ArrayList<AudienceType>();
            audienceTypes.add(AudienceType.REMARKETING_LIST);
            
            for (java.lang.Long audienceId : audienceIds.getLongs())
            {
                if (audienceId != null)
                {
                    BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion();
                    biddableAdGroupCriterion.setAdGroupId(adGroupIds.getLongs().get(0));
                    AudienceCriterion audienceCriterion = new AudienceCriterion();
                    audienceCriterion.setAudienceId(audienceId);
                    audienceCriterion.setAudienceType(audienceTypes);
                    biddableAdGroupCriterion.setCriterion(audienceCriterion);
                    BidMultiplier bidMultiplier = new BidMultiplier();
                    bidMultiplier.setMultiplier(20D);
                    biddableAdGroupCriterion.setCriterionBid(bidMultiplier);
                    biddableAdGroupCriterion.setStatus(AdGroupCriterionStatus.ACTIVE);                                        
                    adGroupRemarketingListAssociations.getAdGroupCriterions().add(biddableAdGroupCriterion);
                }
            }
            
            ArrayList<AdGroupCriterionType> criterionType = new ArrayList<AdGroupCriterionType>();
            criterionType.add(AdGroupCriterionType.AUDIENCE);
            
            ArrayList<AdGroupCriterionType> getCriterionType = new ArrayList<AdGroupCriterionType>();
            getCriterionType.add(AdGroupCriterionType.REMARKETING_LIST);

            outputStatusMessage("-----\nAddAdGroupCriterions:");
            AddAdGroupCriterionsResponse addAdGroupCriterionsResponse = CampaignManagementExampleHelper.addAdGroupCriterions(
                    adGroupRemarketingListAssociations,
                    criterionType);
            outputStatusMessage("AdGroupCriterionIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(addAdGroupCriterionsResponse.getAdGroupCriterionIds());
            ArrayOfBatchErrorCollection adGroupCriterionErrors = addAdGroupCriterionsResponse.getNestedPartialErrors();
            outputStatusMessage("NestedPartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchErrorCollection(adGroupCriterionErrors);

            // 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 %s", deleteCampaignIds.getLongs().get(0))); 

            // Delete the remarketing lists.

            outputStatusMessage("-----\nDeleteAudiences:");
            ArrayOflong deleteAudienceIds = new ArrayOflong();
            deleteAudienceIds.getLongs().add(audienceIds.getLongs().get(0));
            CampaignManagementExampleHelper.deleteAudiences(
                deleteAudienceIds);
            outputStatusMessage(String.format("Deleted Audience Id %s", deleteAudienceIds.getLongs().get(0)));
        } 
        catch (Exception ex) {
            String faultXml = ExampleExceptionHelper.getBingAdsExceptionFaultXml(ex, System.out);
            outputStatusMessage(faultXml);
            String message = ExampleExceptionHelper.handleBingAdsSDKException(ex, System.out);
            outputStatusMessage(message);
        }
    }
 }
<?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\AdGroup;
use Microsoft\BingAds\V13\CampaignManagement\BiddableAdGroupCriterion;
use Microsoft\BingAds\V13\CampaignManagement\AdGroupCriterion;
use Microsoft\BingAds\V13\CampaignManagement\AdGroupCriterionType;
use Microsoft\BingAds\V13\CampaignManagement\AdGroupCriterionStatus;
use Microsoft\BingAds\V13\CampaignManagement\Audience;
use Microsoft\BingAds\V13\CampaignManagement\AudienceCriterion;
use Microsoft\BingAds\V13\CampaignManagement\BidMultiplier;
use Microsoft\BingAds\V13\CampaignManagement\AudienceType;
use Microsoft\BingAds\V13\CampaignManagement\RemarketingList;
use Microsoft\BingAds\V13\CampaignManagement\CustomEventsRule;
use Microsoft\BingAds\V13\CampaignManagement\PageVisitorsRule;
use Microsoft\BingAds\V13\CampaignManagement\PageVisitorsWhoDidNotVisitAnotherPageRule;
use Microsoft\BingAds\V13\CampaignManagement\PageVisitorsWhoVisitedAnotherPageRule;
use Microsoft\BingAds\V13\CampaignManagement\RuleItemGroup;
use Microsoft\BingAds\V13\CampaignManagement\StringRuleItem;
use Microsoft\BingAds\V13\CampaignManagement\EntityScope;
use Microsoft\BingAds\V13\CampaignManagement\BudgetLimitType;
use Microsoft\BingAds\V13\CampaignManagement\Bid;
use Microsoft\BingAds\V13\CampaignManagement\Date;
use Microsoft\BingAds\V13\CampaignManagement\Setting;
use Microsoft\BingAds\V13\CampaignManagement\TargetSettingDetail;
use Microsoft\BingAds\V13\CampaignManagement\TargetSetting;
use Microsoft\BingAds\V13\CampaignManagement\CriterionTypeGroup;

// Specify the Microsoft\BingAds\V13\CustomerManagement classes that will be used.
use Microsoft\BingAds\V13\CustomerManagement\Account;
use Microsoft\BingAds\V13\CustomerManagement\User;

// 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;

try
{
    // Authenticate user credentials and set the account ID for the sample.  
    AuthHelper::Authenticate();

    // Before you can track conversions or target audiences using a remarketing list 
    // you need to create a UET tag, and then add the UET tag tracking code to every page of your website.
    // For more information, please see Universal Event Tracking at https://go.microsoft.com/fwlink/?linkid=829965.

    // First you should call the GetUetTagsByIds operation to check whether a tag has already been created. 
    // You can leave the TagIds element null or empty to request all UET tags available for the customer.

    print("-----\r\nGetUetTagsByIds:\r\n");
    $uetTags = CampaignManagementExampleHelper::GetUetTagsByIds(
        null
    )->UetTags;

    // If you do not already have a UET tag that can be used, or if you need another UET tag, 
    // call the AddUetTags service operation to create a new UET tag. If the call is successful, 
    // the tracking script that you should add to your website is included in a corresponding 
    // UetTag within the response message. 

    if (count($uetTags) < 1)
    {
        $uetTag = new UetTag();
        $uetTag->Description = "My First Uet Tag";
        $uetTag->Name = "New Uet Tag";
        print("-----\r\nAddUetTags:\r\n");
        $uetTags = CampaignManagementExampleHelper::AddUetTags(
            array($uetTag)
        )->UetTags;
    }

    if (count($uetTags) < 1)
    {
        printf(
            "You do not have any UET tags registered for CustomerId {0}.", 
            $GLOBALS['AuthorizationData']->CustomerId
        );
        return;
    }

    print("List of all UET Tags:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfUetTag($uetTags);

    // After you retreive the tracking script from the AddUetTags or GetUetTagsByIds operation, 
    // the next step is to add the UET tag tracking code to your website. 

    // We will use the same UET tag for the remainder of this example.
    $tagId = $uetTags->UetTag[0]->Id;
    
    // Add remarketing lists that depend on the UET Tag Id retreived above.

    $audiences = array();
    $customEventsList = new RemarketingList();
    $customEventsList->Description="New list with CustomEventsRule";
    $customEventsList->MembershipDuration=30;
    $customEventsList->Name="Remarketing List with CustomEventsRule " . $_SERVER['REQUEST_TIME'];
    $customEventsList->ParentId = $GLOBALS['AuthorizationData']->AccountId;
    // The rule definition is translated to the following logical expression: 
    // (Category Equals video) and (Action Equals play) and (Label Equals trailer) 
    // and (Value Equals 5)
    $customEventsRule = new CustomEventsRule();
    // The type of user interaction you want to track.
    $customEventsRule->Action="play";
    $customEventsRule->ActionOperator='Equals';
    // The category of event you want to track. 
    $customEventsRule->Category="video";
    $customEventsRule->CategoryOperator='Equals';
    // The name of the element that caused the action.
    $customEventsRule->Label="trailer";
    $customEventsRule->LabelOperator='Equals';
    // A numerical value associated with that event. 
    // Could be length of the video played etc.
    $customEventsRule->Value=5.00;
    $customEventsRule->ValueOperator='Equals';
    $customEventsList->Rule = new SoapVar(
        $customEventsRule, 
        SOAP_ENC_OBJECT, 
        'CustomEventsRule', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );  
    $customEventsList->Scope='Account';
    $customEventsList->TagId = $tagId;     
    $audiences[] = new SoapVar(
        $customEventsList, 
        SOAP_ENC_OBJECT, 
        'RemarketingList', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );       
                
    $pageVisitorsList = new RemarketingList();  
    $pageVisitorsList->Description="New list with PageVisitorsRule";
    $pageVisitorsList->MembershipDuration=30;
    $pageVisitorsList->Name="Remarketing List with PageVisitorsRule " . $_SERVER['REQUEST_TIME'];
    $pageVisitorsList->ParentId = $GLOBALS['AuthorizationData']->AccountId;
    // The rule definition is translated to the following logical expression: 
    // ((Url Contains X) and (ReferrerUrl DoesNotContain Z)) or ((Url DoesNotBeginWith Y)) 
    // or ((ReferrerUrl Equals Z))
    $pageVisitorsRule = new PageVisitorsRule();
    $pageVisitorsRuleItemGroups = array();
    $pageVisitorsRuleItemGroupA = new RuleItemGroup();
    $pageVisitorsRuleItemsA = array();
    $pageVisitorsRuleItemA = new StringRuleItem();
    $pageVisitorsRuleItemA->Operand = "Url";
    $pageVisitorsRuleItemA->Operator = 'Contains';
    $pageVisitorsRuleItemA->Value = "X";
    $pageVisitorsRuleItemsA[] = new SoapVar(
        $pageVisitorsRuleItemA, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );        
    $pageVisitorsRuleItemAA = new StringRuleItem();
    $pageVisitorsRuleItemAA->Operand = "ReferrerUrl";
    $pageVisitorsRuleItemAA->Operator = 'DoesNotContain';
    $pageVisitorsRuleItemAA->Value = "Z";
    $pageVisitorsRuleItemsA[] = new SoapVar(
        $pageVisitorsRuleItemAA, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );    
    $pageVisitorsRuleItemGroupA->Items = $pageVisitorsRuleItemsA;
    $pageVisitorsRuleItemGroups[] = $pageVisitorsRuleItemGroupA;
    $pageVisitorsRuleItemGroupB = new RuleItemGroup();
    $pageVisitorsRuleItemsB = array();
    $pageVisitorsRuleItemB = new StringRuleItem();
    $pageVisitorsRuleItemB->Operand = "Url";
    $pageVisitorsRuleItemB->Operator = 'DoesNotBeginWith';
    $pageVisitorsRuleItemB->Value = "Y";
    $pageVisitorsRuleItemsB[] = new SoapVar(
        $pageVisitorsRuleItemB, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );          
    $pageVisitorsRuleItemGroupB->Items = $pageVisitorsRuleItemsB;
    $pageVisitorsRuleItemGroups[] = $pageVisitorsRuleItemGroupB;
    $pageVisitorsRuleItemGroupC = new RuleItemGroup();
    $pageVisitorsRuleItemsC = array();
    $pageVisitorsRuleItemC = new StringRuleItem();
    $pageVisitorsRuleItemC->Operand = "ReferrerUrl";
    $pageVisitorsRuleItemC->Operator = 'Equals';
    $pageVisitorsRuleItemC->Value = "Z";
    $pageVisitorsRuleItemsC[] = new SoapVar(
        $pageVisitorsRuleItemC, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );                   
    $pageVisitorsRuleItemGroupC->Items = $pageVisitorsRuleItemsC;
    $pageVisitorsRuleItemGroups[] = $pageVisitorsRuleItemGroupC;
    $pageVisitorsRule->RuleItemGroups = $pageVisitorsRuleItemGroups;
    $pageVisitorsList->Rule = new SoapVar(
        $pageVisitorsRule, 
        SOAP_ENC_OBJECT, 
        'PageVisitorsRule', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );  
    $pageVisitorsList->Scope='Account';
    $pageVisitorsList->TagId = $tagId; 
    $audiences[] = new SoapVar(
        $pageVisitorsList, 
        SOAP_ENC_OBJECT, 
        'RemarketingList', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );  
    
    $pageVisitorsWhoDidNotVisitAnotherPageList = new RemarketingList();        
    $pageVisitorsWhoDidNotVisitAnotherPageList->Description="New list with PageVisitorsWhoDidNotVisitAnotherPageRule";
    $pageVisitorsWhoDidNotVisitAnotherPageList->MembershipDuration=30;
    $pageVisitorsWhoDidNotVisitAnotherPageList->Name="Remarketing List with PageVisitorsWhoDidNotVisitAnotherPageRule " 
        . $_SERVER['REQUEST_TIME'];
    $pageVisitorsWhoDidNotVisitAnotherPageList->ParentId = $GLOBALS['AuthorizationData']->AccountId;
    // The rule definition is translated to the following logical expression: 
    // (((Url Contains X) and (ReferrerUrl DoesNotContain Z)) or ((Url DoesNotBeginWith Y)) 
    // or ((ReferrerUrl Equals Z))) 
    // and not (((Url BeginsWith A) and (ReferrerUrl BeginsWith B)) or ((Url Contains C)))
    $pageVisitorsWhoDidNotVisitAnotherPageRule = new PageVisitorsWhoDidNotVisitAnotherPageRule();            
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroups = array();
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroupA = new RuleItemGroup();
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsA = array();
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemA = new StringRuleItem();
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemA->Operand = "Url";
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemA->Operator = 'BeginsWith';
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemA->Value = "A";
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsA[] = new SoapVar(
        $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemA, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );   
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemAA = new StringRuleItem();
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemAA->Operand = "ReferrerUrl";
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemAA->Operator = 'BeginsWith';
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemAA->Value = "B";
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsA[] = new SoapVar(
        $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemAA, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );   
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroupA->Items = $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsA;
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroups[] = $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroupA;
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroupB = new RuleItemGroup();
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsB = array();
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemB = new StringRuleItem();
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemB->Operand = "Url";
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemB->Operator = 'Contains';
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemB->Value = "C";
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsB[] = new SoapVar(
        $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemB, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );            
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroupB->Items = $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemsB;
    $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroups[] = $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroupB;
    $pageVisitorsWhoDidNotVisitAnotherPageRule->ExcludeRuleItemGroups = $pageVisitorsWhoDidNotVisitAnotherPageExcludeRuleItemGroups;            
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroups = array();
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupA = new RuleItemGroup();
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsA = array();
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemA = new StringRuleItem();
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemA->Operand = "Url";
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemA->Operator = 'Contains';
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemA->Value = "X";
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsA[] = new SoapVar(
        $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemA, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );   
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemAA = new StringRuleItem();
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemAA->Operand = "ReferrerUrl";
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemAA->Operator = 'DoesNotContain';
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemAA->Value = "Z";
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsA[] = new SoapVar(
        $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemAA, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );   
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupA->Items = $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsA;
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroups[] = $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupA;
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupB = new RuleItemGroup();
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsB = array();
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemB = new StringRuleItem();
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemB->Operand = "Url";
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemB->Operator = 'DoesNotBeginWith';
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemB->Value = "Y";
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsB[] = new SoapVar(
        $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemB, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );          
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupB->Items = $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsB;
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroups[] = $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupB;
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupC = new RuleItemGroup();
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsC = array();
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemC = new StringRuleItem();
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemC->Operand = "ReferrerUrl";
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemC->Operator = 'Equals';
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemC->Value = "Z";
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsC[] = new SoapVar(
        $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemC, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );             
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupC->Items = $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemsC;
    $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroups[] = $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroupC;
    $pageVisitorsWhoDidNotVisitAnotherPageRule->IncludeRuleItemGroups = $pageVisitorsWhoDidNotVisitAnotherPageIncludeRuleItemGroups;
    $pageVisitorsWhoDidNotVisitAnotherPageList->Rule = new SoapVar(
        $pageVisitorsWhoDidNotVisitAnotherPageRule, 
        SOAP_ENC_OBJECT, 
        'PageVisitorsWhoDidNotVisitAnotherPageRule', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );  
    $pageVisitorsWhoDidNotVisitAnotherPageList->Scope='Account';
    $pageVisitorsWhoDidNotVisitAnotherPageList->TagId = $tagId;   
    $audiences[] = new SoapVar(
        $pageVisitorsWhoDidNotVisitAnotherPageList, 
        SOAP_ENC_OBJECT, 
        'RemarketingList', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    ); 

    $pageVisitorsWhoVisitedAnotherPageList = new RemarketingList();  
    $pageVisitorsWhoVisitedAnotherPageList->Description="New list with PageVisitorsWhoVisitedAnotherPageRule";
    $pageVisitorsWhoVisitedAnotherPageList->MembershipDuration=30;
    $pageVisitorsWhoVisitedAnotherPageList->Name="Remarketing List with PageVisitorsWhoVisitedAnotherPageRule " 
        . $_SERVER['REQUEST_TIME'];
    $pageVisitorsWhoVisitedAnotherPageList->ParentId = $GLOBALS['AuthorizationData']->AccountId;
    // The rule definition is translated to the following logical expression: 
    // (((Url Contains X) and (ReferrerUrl NotEquals Z)) or ((Url DoesNotBeginWith Y)) or 
    // ((ReferrerUrl Equals Z))) 
    // and (((Url BeginsWith A) and (ReferrerUrl BeginsWith B)) or ((Url Contains C)))
    $pageVisitorsWhoVisitedAnotherPageRule = new PageVisitorsWhoVisitedAnotherPageRule();         
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroups = array();
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroupA = new RuleItemGroup();
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsA = array();
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemA = new StringRuleItem();
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemA->Operand = "Url";
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemA->Operator = 'BeginsWith';
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemA->Value = "A";
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsA[] = new SoapVar(
        $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemA, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );   
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemAA = new StringRuleItem();
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemAA->Operand = "ReferrerUrl";
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemAA->Operator = 'BeginsWith';
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemAA->Value = "B";
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsA[] = new SoapVar(
        $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemAA, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );    
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroupA->Items = $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsA;
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroups[] = $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroupA;
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroupB = new RuleItemGroup();
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsB = array();
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemB = new StringRuleItem();
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemB->Operand = "Url";
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemB->Operator = 'Contains';
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemB->Value = "C";
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsB[] = new SoapVar(
        $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemB, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );            
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroupB->Items = $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemsB;
    $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroups[] = $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroupB;
    $pageVisitorsWhoVisitedAnotherPageRule->AnotherRuleItemGroups = $pageVisitorsWhoVisitedAnotherPageAnotherRuleItemGroups;            
    $pageVisitorsWhoVisitedAnotherPageRuleItemGroups = array();
    $pageVisitorsWhoVisitedAnotherPageRuleItemGroupA = new RuleItemGroup();
    $pageVisitorsWhoVisitedAnotherPageRuleItemsA = array();
    $pageVisitorsWhoVisitedAnotherPageRuleItemA = new StringRuleItem();
    $pageVisitorsWhoVisitedAnotherPageRuleItemA->Operand = "Url";
    $pageVisitorsWhoVisitedAnotherPageRuleItemA->Operator = 'Contains';
    $pageVisitorsWhoVisitedAnotherPageRuleItemA->Value = "X";
    $pageVisitorsWhoVisitedAnotherPageRuleItemsA[] = new SoapVar(
        $pageVisitorsWhoVisitedAnotherPageRuleItemA, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );    
    $pageVisitorsWhoVisitedAnotherPageRuleItemAA = new StringRuleItem();
    $pageVisitorsWhoVisitedAnotherPageRuleItemAA->Operand = "ReferrerUrl";
    $pageVisitorsWhoVisitedAnotherPageRuleItemAA->Operator = 'DoesNotContain';
    $pageVisitorsWhoVisitedAnotherPageRuleItemAA->Value = "Z";
    $pageVisitorsWhoVisitedAnotherPageRuleItemsA[] = new SoapVar(
        $pageVisitorsWhoVisitedAnotherPageRuleItemAA, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );     
    $pageVisitorsWhoVisitedAnotherPageRuleItemGroupA->Items = $pageVisitorsWhoVisitedAnotherPageRuleItemsA;
    $pageVisitorsWhoVisitedAnotherPageRuleItemGroups[] = $pageVisitorsWhoVisitedAnotherPageRuleItemGroupA;
    $pageVisitorsWhoVisitedAnotherPageRuleItemGroupB = new RuleItemGroup();
    $pageVisitorsWhoVisitedAnotherPageRuleItemsB = array();
    $pageVisitorsWhoVisitedAnotherPageRuleItemB = new StringRuleItem();
    $pageVisitorsWhoVisitedAnotherPageRuleItemB->Operand = "Url";
    $pageVisitorsWhoVisitedAnotherPageRuleItemB->Operator = 'DoesNotBeginWith';
    $pageVisitorsWhoVisitedAnotherPageRuleItemB->Value = "Y";
    $pageVisitorsWhoVisitedAnotherPageRuleItemsB[] = new SoapVar(
        $pageVisitorsWhoVisitedAnotherPageRuleItemB, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );            
    $pageVisitorsWhoVisitedAnotherPageRuleItemGroupB->Items = $pageVisitorsWhoVisitedAnotherPageRuleItemsB;
    $pageVisitorsWhoVisitedAnotherPageRuleItemGroups[] = $pageVisitorsWhoVisitedAnotherPageRuleItemGroupB;
    $pageVisitorsWhoVisitedAnotherPageRuleItemGroupC = new RuleItemGroup();
    $pageVisitorsWhoVisitedAnotherPageRuleItemsC = array();
    $pageVisitorsWhoVisitedAnotherPageRuleItemC = new StringRuleItem();
    $pageVisitorsWhoVisitedAnotherPageRuleItemC->Operand = "ReferrerUrl";
    $pageVisitorsWhoVisitedAnotherPageRuleItemC->Operator = 'Equals';
    $pageVisitorsWhoVisitedAnotherPageRuleItemC->Value = "Z";
    $pageVisitorsWhoVisitedAnotherPageRuleItemsC[] = new SoapVar(
        $pageVisitorsWhoVisitedAnotherPageRuleItemC, 
        SOAP_ENC_OBJECT, 
        'StringRuleItem', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );             
    $pageVisitorsWhoVisitedAnotherPageRuleItemGroupC->Items = $pageVisitorsWhoVisitedAnotherPageRuleItemsC;
    $pageVisitorsWhoVisitedAnotherPageRuleItemGroups[] = $pageVisitorsWhoVisitedAnotherPageRuleItemGroupC;
    $pageVisitorsWhoVisitedAnotherPageRule->RuleItemGroups = $pageVisitorsWhoVisitedAnotherPageRuleItemGroups;
    $pageVisitorsWhoVisitedAnotherPageList->Rule = new SoapVar(
        $pageVisitorsWhoVisitedAnotherPageRule, 
        SOAP_ENC_OBJECT, 
        'PageVisitorsWhoVisitedAnotherPageRule', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );  
    $pageVisitorsWhoVisitedAnotherPageList->Scope='Account';
    $pageVisitorsWhoVisitedAnotherPageList->TagId = $tagId;   
    $audiences[] = new SoapVar(
        $pageVisitorsWhoVisitedAnotherPageList, 
        SOAP_ENC_OBJECT, 
        'RemarketingList', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    ); 

    // RemarketingList extends the Audience base class. 
    // We manage remarketing lists with Audience operations.

    print("-----\r\nAddAudiences:\r\n");
    $addAudiencesResponse = CampaignManagementExampleHelper::AddAudiences(
        $audiences
    );
    $audienceIds = $addAudiencesResponse->AudienceIds;
    print("AudienceIds:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLong($audienceIds);
    print("PartialErrors:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfBatchError($addAudiencesResponse->PartialErrors);
                
    // Add an ad group in a campaign. The ad group will later be associated with remarketing lists. 
    
    $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;    
    // Applicable for all remarketing lists that are associated with this ad group. TargetAndBid indicates 
    // that you want to show ads only to people included in the remarketing list, with the option to change
    // the bid amount. Ads in this ad group will only show to people included in the remarketing list. 
    $adGroupSettings = array();
    $adGroupTargetSetting = new TargetSetting();
    $adGroupAudienceTargetSettingDetail = new TargetSettingDetail();
    $adGroupAudienceTargetSettingDetail->CriterionTypeGroup = CriterionTypeGroup::Audience;
    $adGroupAudienceTargetSettingDetail->TargetAndBid = True;
    $adGroupTargetSetting->Details = array();
    $adGroupTargetSetting->Details[] = $adGroupAudienceTargetSettingDetail;
    $encodedAdGroupTargetSetting = new SoapVar(
        $adGroupTargetSetting, 
        SOAP_ENC_OBJECT, 
        'TargetSetting', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $adGroupSettings[] = $encodedAdGroupTargetSetting;
    $adGroup->Settings=$adGroupSettings;
    $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);

    // Associate all of the remarketing lists created above with the new ad group.

    $adGroupCriterions = array();

    foreach ($audienceIds->long as $audienceId)
    {
        if ($audienceId != null)
        {
            $adGroupCriterion = new BiddableAdGroupCriterion();
            
            $criterion = new AudienceCriterion();
            $criterion->AudienceId = $audienceId;
            $criterion->AudienceType = AudienceType::RemarketingList;
            $adGroupCriterion->Criterion = new SoapVar(
                $criterion, 
                SOAP_ENC_OBJECT, 
                'AudienceCriterion', 
                $GLOBALS['CampaignManagementProxy']->GetNamespace()
            );

            $criterionBid = new BidMultiplier();
            $criterionBid->Multiplier = 20.00;
            $adGroupCriterion->CriterionBid = new SoapVar(
                $criterionBid, 
                SOAP_ENC_OBJECT, 
                'BidMultiplier', 
                $GLOBALS['CampaignManagementProxy']->GetNamespace()
            );

            $adGroupCriterion->AdGroupId = $adGroupIds->long[0];
            $adGroupCriterion->Status = AdGroupCriterionStatus::Active;
            
            $adGroupCriterions[] = new SoapVar(
                $adGroupCriterion, 
                SOAP_ENC_OBJECT, 
                'BiddableAdGroupCriterion', 
                $GLOBALS['CampaignManagementProxy']->GetNamespace()
            );
        }
    }

    print("-----\r\nAddAdGroupCriterions:\r\n");
    $addAdGroupCriterionsResponse = CampaignManagementExampleHelper::AddAdGroupCriterions(
        $adGroupCriterions, 
        AdGroupCriterionType::Audience
    );
    $adGroupCriterionIds = $addAdGroupCriterionsResponse->AdGroupCriterionIds;
    print("AdGroupCriterionIds:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLong($adGroupCriterionIds);
    $adGroupCriterionErrors = $addAdGroupCriterionsResponse->NestedPartialErrors;
    print("NestedPartialErrors:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfBatchErrorCollection($adGroupCriterionErrors);
    
    // 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";
    }
}
import uuid
from auth_helper import *
from openapi_client.models.campaign import *

def main(authorization_data):
    try:
        # Check if UET tags already exist
        print("Checking for existing UET tags...")
        
        get_uet_tags_request = GetUetTagsByIdsRequest(
            tag_ids=None  # Get all UET tags
        )
        
        get_uet_tags_response = campaign_service.get_uet_tags_by_ids(
            get_uet_tags_by_ids_request=get_uet_tags_request
        )
        
        uet_tags = get_uet_tags_response.UetTags if get_uet_tags_response.UetTags else []
        
        print(f"Found {len(uet_tags)} existing UET tags")
        
        if get_uet_tags_response.PartialErrors:
            print(f"Partial Errors: {get_uet_tags_response.PartialErrors}")
        
        # Create a new UET tag if none exist
        if len(uet_tags) == 0:
            print("\nCreating new UET tag...")
            print("Before you can track conversions or target audiences using a remarketing list,")
            print("you need to create a UET tag, and then add the UET tag tracking code to every page of your website.")
            
            uet_tag = UetTag(
                name="New UET Tag" + str(uuid.uuid4())[:8],
                description="My First UET Tag" + str(uuid.uuid4())[:8]
            )
            
            add_uet_tags_request = AddUetTagsRequest(
                uet_tags=[uet_tag]
            )
            
            add_uet_tags_response = campaign_service.add_uet_tags(
                add_uet_tags_request=add_uet_tags_request
            )
            
            uet_tags = add_uet_tags_response.UetTags
            print(f"Created UET Tag ID: {uet_tags[0].Id}")
            
            if add_uet_tags_response.PartialErrors:
                print(f"Partial Errors: {add_uet_tags_response.PartialErrors}")
        else:
            print("Using existing UET tag")
        
        tag_id = uet_tags[0].Id
        print(f"\nUsing UET Tag ID: {tag_id}")
        
        # Create remarketing lists with different rule types
        print("\nCreating remarketing lists...")
        
        audiences = []
        
        # 1. Custom Events Rule
        custom_events_rule = CustomEventsRule(
            action="play",
            action_operator=StringOperator.EQUALS,
            category="video",
            category_operator=StringOperator.EQUALS,
            label="trailer",
            label_operator=StringOperator.EQUALS,
            value=5.0,
            value_operator=StringOperator.EQUALS
        )
        
        custom_events_list = RemarketingList(
            description="New list with CustomEventsRule",
            membership_duration=30,
            name="Remarketing List with CustomEventsRule " + str(uuid.uuid4())[:8],
            parent_id=authorization_data.account_id,
            scope=EntityScope.ACCOUNT,
            tag_id=tag_id,
            rule=custom_events_rule
        )
        audiences.append(custom_events_list)
        
        # 2. Page Visitors Rule
        page_visitors_rule = PageVisitorsRule(
            rule_item_groups=[
                RuleItemGroup(
                    items=[
                        StringRuleItem(
                            operand="Url",
                            operator=StringOperator.CONTAINS,
                            value="X"
                        ),
                        StringRuleItem(
                            operand="ReferrerUrl",
                            operator=StringOperator.DOESNOTCONTAIN,
                            value="Z"
                        )
                    ]
                ),
                RuleItemGroup(
                    items=[
                        StringRuleItem(
                            operand="Url",
                            operator=StringOperator.DOESNOTBEGINWITH,
                            value="Y"
                        )
                    ]
                ),
                RuleItemGroup(
                    items=[
                        StringRuleItem(
                            operand="ReferrerUrl",
                            operator=StringOperator.EQUALS,
                            value="Z"
                        )
                    ]
                )
            ]
        )
        
        page_visitors_list = RemarketingList(
            description="New list with PageVisitorsRule",
            membership_duration=30,
            name="Remarketing List with PageVisitorsRule " + str(uuid.uuid4())[:8],
            parent_id=authorization_data.account_id,
            scope=EntityScope.ACCOUNT,
            tag_id=tag_id,
            rule=page_visitors_rule
        )
        audiences.append(page_visitors_list)
        
        # 3. Page Visitors Who Did Not Visit Another Page Rule
        page_visitors_who_did_not_visit_rule = PageVisitorsWhoDidNotVisitAnotherPageRule(
            include_rule_item_groups=[
                RuleItemGroup(
                    items=[
                        StringRuleItem(
                            operand="Url",
                            operator=StringOperator.CONTAINS,
                            value="X"
                        ),
                        StringRuleItem(
                            operand="ReferrerUrl",
                            operator=StringOperator.DOESNOTCONTAIN,
                            value="Z"
                        )
                    ]
                ),
                RuleItemGroup(
                    items=[
                        StringRuleItem(
                            operand="ReferrerUrl",
                            operator=StringOperator.EQUALS,
                            value="Z"
                        )
                    ]
                )
            ],
            exclude_rule_item_groups=[
                RuleItemGroup(
                    items=[
                        StringRuleItem(
                            operand="Url",
                            operator=StringOperator.BEGINSWITH,
                            value="A"
                        ),
                        StringRuleItem(
                            operand="ReferrerUrl",
                            operator=StringOperator.BEGINSWITH,
                            value="B"
                        )
                    ]
                ),
                RuleItemGroup(
                    items=[
                        StringRuleItem(
                            operand="Url",
                            operator=StringOperator.CONTAINS,
                            value="C"
                        )
                    ]
                )
            ]
        )
        
        page_visitors_who_did_not_visit_list = RemarketingList(
            description="New list with PageVisitorsWhoDidNotVisitAnotherPageRule",
            membership_duration=30,
            name="Remarketing List with PageVisitorsWhoDidNotVisitAnotherPageRule " + str(uuid.uuid4())[:8],
            parent_id=authorization_data.account_id,
            scope=EntityScope.ACCOUNT,
            tag_id=tag_id,
            rule=page_visitors_who_did_not_visit_rule
        )
        audiences.append(page_visitors_who_did_not_visit_list)
        
        # 4. Page Visitors Who Visited Another Page Rule
        page_visitors_who_visited_rule = PageVisitorsWhoVisitedAnotherPageRule(
            rule_item_groups=[
                RuleItemGroup(
                    items=[
                        StringRuleItem(
                            operand="Url",
                            operator=StringOperator.CONTAINS,
                            value="X"
                        ),
                        StringRuleItem(
                            operand="ReferrerUrl",
                            operator=StringOperator.DOESNOTCONTAIN,
                            value="Z"
                        )
                    ]
                ),
                RuleItemGroup(
                    items=[
                        StringRuleItem(
                            operand="ReferrerUrl",
                            operator=StringOperator.EQUALS,
                            value="Z"
                        ),
                        StringRuleItem(
                            operand="Url",
                            operator=StringOperator.DOESNOTBEGINWITH,
                            value="Y"
                        )
                    ]
                )
            ],
            another_rule_item_groups=[
                RuleItemGroup(
                    items=[
                        StringRuleItem(
                            operand="Url",
                            operator=StringOperator.BEGINSWITH,
                            value="A"
                        ),
                        StringRuleItem(
                            operand="ReferrerUrl",
                            operator=StringOperator.BEGINSWITH,
                            value="B"
                        )
                    ]
                ),
                RuleItemGroup(
                    items=[
                        StringRuleItem(
                            operand="Url",
                            operator=StringOperator.CONTAINS,
                            value="C"
                        )
                    ]
                )
            ]
        )
        
        page_visitors_who_visited_list = RemarketingList(
            description="New list with PageVisitorsWhoVisitedAnotherPageRule",
            membership_duration=30,
            name="Remarketing List with PageVisitorsWhoVisitedAnotherPageRule " + str(uuid.uuid4())[:8],
            parent_id=authorization_data.account_id,
            scope=EntityScope.ACCOUNT,
            tag_id=tag_id,
            rule=page_visitors_who_visited_rule
        )
        audiences.append(page_visitors_who_visited_list)
        
        # Add all remarketing lists
        add_audiences_request = AddAudiencesRequest(
            audiences=audiences
        )
        
        add_audiences_response = campaign_service.add_audiences(
            add_audiences_request=add_audiences_request
        )
        
        audience_ids = add_audiences_response.AudienceIds
        print(f"Created Audience IDs: {audience_ids}")
        
        if add_audiences_response.PartialErrors:
            print(f"Partial Errors: {add_audiences_response.PartialErrors}")
        else:
            print(f"Successfully created {len(audience_ids)} remarketing lists")
        
        # Create a campaign for remarketing
        print("\nCreating remarketing campaign...")
        
        campaign = Campaign(
            name="Remarketing Campaign " + str(uuid.uuid4())[:8],
            budget_type=BudgetLimitType.DAILYBUDGETSTANDARD,
            daily_budget=50.00,
            languages=['All'],
            time_zone='PacificTimeUSCanadaTijuana'
        )
        
        add_campaigns_request = AddCampaignsRequest(
            account_id=authorization_data.account_id,
            campaigns=[campaign]
        )
        
        add_campaigns_response = campaign_service.add_campaigns(
            add_campaigns_request=add_campaigns_request
        )
        
        campaign_ids = add_campaigns_response.CampaignIds
        print(f"Created Campaign ID: {campaign_ids[0]}")
        
        # Create an ad group with audience targeting
        print("\nCreating ad group with audience targeting...")
        
        current_year = datetime.now().year
        
        target_setting = TargetSetting(
            details=[
                TargetSettingDetail(
                    criterion_type_group=CriterionTypeGroup.AUDIENCE,
                    target_and_bid=True
                )
            ]
        )
        
        ad_group = AdGroup(
            name="Remarketing Ad Group" + str(uuid.uuid4())[:8],
            cpc_bid=Bid(amount=0.09),
            start_date=None,
            end_date=Date(day=31, month=12, year=current_year),
            settings=[target_setting]
        )
        
        add_ad_groups_request = AddAdGroupsRequest(
            campaign_id=campaign_ids[0],
            ad_groups=[ad_group]
        )
        
        add_ad_groups_response = campaign_service.add_ad_groups(
            add_ad_groups_request=add_ad_groups_request
        )
        
        ad_group_ids = add_ad_groups_response.AdGroupIds
        print(f"Created Ad Group ID: {ad_group_ids[0]}")
        
        # Associate remarketing lists with ad group
        print("\nAssociating remarketing lists with ad group...")
        
        ad_group_criterions = []
        
        for audience_id in audience_ids:
            criterion = AudienceCriterion(
                audience_id=audience_id,
                audience_type=AudienceType.REMARKETINGLIST
            )
            
            ad_group_criterion = BiddableAdGroupCriterion(
                ad_group_id=ad_group_ids[0],
                criterion=criterion,
                criterion_bid=BidMultiplier(multiplier=20.0),
                status=AdGroupCriterionStatus.ACTIVE
            )
            
            ad_group_criterions.append(ad_group_criterion)
        
        add_ad_group_criterions_request = AddAdGroupCriterionsRequest(
            ad_group_criterions=ad_group_criterions,
            criterion_type=AdGroupCriterionType.AUDIENCE
        )
        
        add_ad_group_criterions_response = campaign_service.add_ad_group_criterions(
            add_ad_group_criterions_request=add_ad_group_criterions_request
        )
        
        criterion_ids = add_ad_group_criterions_response.AdGroupCriterionIds
        print(f"Created Ad Group Criterion IDs: {criterion_ids}")
        
        if add_ad_group_criterions_response.NestedPartialErrors:
            print(f"Nested Partial Errors: {add_ad_group_criterions_response.NestedPartialErrors}")
        else:
            print("Successfully associated remarketing lists with ad group")
        
        # Delete campaign
        print("\nDeleting campaign...")
        
        delete_campaigns_request = DeleteCampaignsRequest(
            account_id=authorization_data.account_id,
            campaign_ids=campaign_ids
        )
        
        campaign_service.delete_campaigns(
            delete_campaigns_request=delete_campaigns_request
        )
        
        print(f"Deleted Campaign ID {campaign_ids[0]}")
        
        print("\n" + "="*80)
        print("Test completed successfully!")
        print(f"Note: The remarketing lists and UET tag remain in your account and can be reused.")
        print("="*80)
        
    except Exception as ex:
        print(f"Error occurred: {str(ex)}")
        import traceback
        traceback.print_exc()

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

See Also

Get Started with the Bing Ads API