Export (0) Print
Expand All

Exclude Locations from a Location Target in C#

The following example shows how to exclude locations from a target using the following Campaign Management service operations.

This example has been developed and run within the environment described in Getting Started Using C# and Visual Basic with Bing Ads Services.

System_CLiX_note Note

This example uses the UserName and Password elements for authentication. For Managing User Authentication with OAuth, replace the UserName and Password elements with the AuthenticationToken, which is your OAuth access token.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

// BingAds.CampaignManagement is the application-defined namespace that 
// this example used when it added the Campaign Management service reference. 

using LocationExclusions.BingAds.CampaignManagement;

namespace LocationExclusions
{
    class Program
    {
        private static CampaignManagementServiceClient service = null;

        // Specify your credentials.

        private static string m_password = "<passwordgoeshere>";
        private static string m_username = "<usernamegoeshere>";
        private static string m_token = "<devtokengoeshere>";

        // Specify the account to which the exclusions apply.

        private static long m_accountId = <accountidgoeshere>;
        private static long m_customerId = <customeridgoeshere>;


        // Note that the SetExclusion and GetExclusions methods contain the calls
        // to the exclusion operations. 

        static void Main(string[] args)
        {
            long targetId = -1; 
            EntityToExclusionsAssociation[] associations = null;

            try
            {
                service = new CampaignManagementServiceClient();

                targetId = CreateTarget(m_customerId);

                ApplyExclusion(m_customerId, m_accountId, targetId);

                associations = GetExclusions(m_customerId, m_accountId, targetId);

                if (null != associations)
                {
                    PrintExclusions(associations);

                }

                RemoveExclusion(m_customerId, m_accountId, targetId);

                associations = GetExclusions(m_customerId, m_accountId, targetId);

                if (null != associations)
                {
                    PrintExclusions(associations);

                }

                RemoveTarget(m_customerId, targetId);

                service.Close();
            }
            catch (CommunicationException e)
            {
                Console.WriteLine(e.Message);

                if (null != e.InnerException)
                {
                    Console.WriteLine("\n" + e.InnerException.Message);
                }

                if (service != null)
                {
                    service.Abort();
                }
            }
            catch (TimeoutException e)
            {
                Console.WriteLine(e.Message);

                if (service != null)
                {
                    service.Abort();
                }
            }
            catch (Exception e)
            {
                // Ignore fault exceptions that we already caught.

                if (e.InnerException is FaultException)
                {
                    ;
                }
                else
                {
                    Console.WriteLine(e.Message);
                }

                if (service != null)
                {
                    service.Abort();
                }
            }
        }

        // Adds an exclusion to the specified location target. 

        static void ApplyExclusion(long customerId, long accountId, long targetId)
        {
            SetExclusionsToAssociatedEntitiesRequest request = new SetExclusionsToAssociatedEntitiesRequest();

            // Specify the locations to exclude. You can exclude any 
            // geography that does not conflict with the target location.
            // For example, if you target US-WA, you cannot exclude US.
            // Ensure that the location code matches the specified type.

            Exclusion exclusion = new LocationExclusion
            {
                ExcludedGeoTargets = new ExcludedGeoLocation[] {
                    new ExcludedGeoLocation() {
                        LocationName = "US-ND",
                        LocationType = GeoLocationType.SubGeography
                    },
                    new ExcludedGeoLocation() {
                        LocationName = "US-SD",
                        LocationType = GeoLocationType.SubGeography
                    }
                }
            };

            // Associate the exclusion with a target entity.
            // Ensure that the ID identifies an entity of the specified type.

            ExclusionToEntityAssociation[] associations = new ExclusionToEntityAssociation[] {
                new ExclusionToEntityAssociation() {
                    AssociatedEntity = new Entity()
                    {
                        Id = targetId,
                        EntityType = EntityType.Target
                    },
                    Exclusion = exclusion
                }
            };

            // Set the request header information. 

            request.CustomerId = customerId.ToString();
            request.CustomerAccountId = accountId.ToString();
            request.DeveloperToken = m_token;
            request.UserName = m_username;
            request.Password = m_password;

            // Set the request information.

            request.ExclusionToEntityAssociations = associations;

            SetExclusion(request);

            Console.WriteLine("Added location exclusion to target {0}.", targetId);
        }


        // Removes a location exclusion from the specified location target. 

        static void RemoveExclusion(long customerId, long accountId, long targetId)
        {
            SetExclusionsToAssociatedEntitiesRequest request = new SetExclusionsToAssociatedEntitiesRequest();

            // To remove exclusions, pass an empty exclusion.

            Exclusion exclusion = new LocationExclusion { };

            // Associate the exclusion with a target entity.
            // Ensure that the ID identifies an entity of the specified type.

            ExclusionToEntityAssociation[] associations = new ExclusionToEntityAssociation[] {
                new ExclusionToEntityAssociation() {
                    AssociatedEntity = new Entity()
                    {
                        Id = targetId,
                        EntityType = EntityType.Target
                    },
                    Exclusion = exclusion
                }
            };

            // Set the request header information.

            request.CustomerId = customerId.ToString();
            request.CustomerAccountId = accountId.ToString();
            request.DeveloperToken = m_token;
            request.UserName = m_username;
            request.Password = m_password;

            // Set the request information.

            request.ExclusionToEntityAssociations = associations;

            SetExclusion(request);

            Console.WriteLine("Removed location exclusion from target {0}.", targetId);
        }

        // Calls the SetExclusionsToAssociatedEntities operation to add the
        // exclusion to the location target specified in the request. 

        static void SetExclusion(SetExclusionsToAssociatedEntitiesRequest request)
        {
            SetExclusionsToAssociatedEntitiesResponse response = null;

            try
            {
                response = service.SetExclusionsToAssociatedEntities(request);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("SetExclusionsToAssociatedEntities failed with the following faults " +
                    "(no exclusions were added):\n");

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    if (105 == error.Code) //  InvalidCredentials
                    {
                        Console.WriteLine("The specified credentials are not valid or the account is inactive.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                            error.ErrorCode, error.Code, error.Message, error.Detail);
                    }
                }

                throw new Exception("", fault);
            }
            catch (FaultException<ApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("SetExclusionsToAssociatedEntities failed with the following faults " +
                    "(no exclusions were added):\n");

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    switch (error.Code)
                    {
                        case 106: //  UserIsNotAuthorized
                            Console.WriteLine("The user is not authorized to call this operation.");
                            break;

                        case 2819: //  CampaignServiceAssociatedExclusionToEntityAssociationCollectionIsNull
                            Console.WriteLine("The list of exclusion to entity associations cannot be null.\n");
                            break;

                        default:
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {
                        case 1405: // CampaignServiceInvalidLocationTarget
                            Console.WriteLine("The target location that you specified in association object #{0} is not valid.\n",
                                error.Index + 1);
                            break;

                        case 1464: //  CampaignServiceInvalidLocationId
                            Console.WriteLine("The location code specified in association object #{0} is not valid.\n",
                                error.Index + 1);
                            break;

                        case 2811: //  CampaignServiceExcludedLocationNameIsNullOrEmpty
                            Console.WriteLine("The location code cannot be null or empty.\n");
                            break;

                        case 2813: //  CampaignServiceExclusionTypeMappedToIncorrectAssociatedEntity
                            Console.WriteLine("The exclusion cannot be applied to the entity because the entity is of the wrong type.\n");
                            break;

                        case 2816: //  CampaignServiceAssociatedEntityIsNull
                            Console.WriteLine("The entity to associate the exclusion with cannot be null.\n");
                            break;

                        case 2817: //  CampaignServiceAssociatedExclusionIsNull
                            Console.WriteLine("The exclusion cannot be null.\n");
                            break;

                        case 2820: //  CampaignServiceLocationExclusionPilotNotEnabledForCustomer
                            Console.WriteLine("The customer is not a member of the Location Exclusion pilot program.\n");
                            break;

                        case 2821: //  CampaignServiceLocationExcludedGeoTargetsBatchLimitExceeded
                            Console.WriteLine("The list of excluded geographical location targets exceeds the maximum allowed.\n");
                            break;

                        case 2822: //  CampaignServiceConflictWithLocationExclusion
                            Console.WriteLine("The exclusion conflicts with the target. For example, you cannot apply " +
                                "a U.S. exclusion to a Washington State target.\n");
                            break;

                        case 2823: //  CampaignServiceDuplicateExcludedGeoTargets
                            Console.WriteLine("The list of excluded geographical location targets cannot contain duplicates.\n");
                            break;

                        default:
                            Console.WriteLine("Association object #{0} failed with the following error.",
                                error.Index + 1);
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                throw new Exception("", fault);
            }
        }


        // Get the location exclusions associated with the location target. 

        static EntityToExclusionsAssociation[] GetExclusions(long customerId, long accountId, long targetId)
        {
            GetExclusionsByAssociatedEntityIdsRequest request = new GetExclusionsByAssociatedEntityIdsRequest();
            GetExclusionsByAssociatedEntityIdsResponse response = null;

            // Specify the entities whose exclusions you want to retrieve.
            // Ensure that the ID identifies an entity of the specified type.

            Entity[] entities = new Entity[] {
                new Entity() {
                    Id = targetId,
                    EntityType = EntityType.Target
                }
            };

            // Set the request header information.

            request.CustomerId = customerId.ToString();
            request.CustomerAccountId = accountId.ToString();
            request.DeveloperToken = m_token;
            request.UserName = m_username;
            request.Password = m_password;

            // Set the request information.

            request.Entities = entities;
            request.ExclusionType = ExclusionType.Location;

            try
            {
                response = service.GetExclusionsByAssociatedEntityIds(request);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("GetExclusionsByAssociatedEntityIds failed with the following faults:\n");

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    if (105 == error.Code) //  InvalidCredentials
                    {
                        Console.WriteLine("The specified credentials are not valid or the account is inactive.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                            error.ErrorCode, error.Code, error.Message, error.Detail);
                    }
                }

                throw new Exception("", fault);
            }
            catch (FaultException<ApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("GetExclusionsByAssociatedEntityIds failed with the following faults:\n");

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    if (106 == error.Code) //  UserIsNotAuthorized
                    {
                        Console.WriteLine("The user is not authorized to call this operation.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetails: {3}\n",
                            error.Code, error.ErrorCode, error.Message, error.Details);
                    }
                }

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {
                        case 1429: //  CampaignServiceInvalidTarget
                            Console.WriteLine("The target specified by entity #{0} is not valid.\n",
                                error.Index + 1);
                            break;

                        default:
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                throw new Exception("", fault);
            }

            return response.EntityToExclusionsAssociations;
        }

        // Print the list of exclusions that are applied to the entity.

        private static void PrintExclusions(EntityToExclusionsAssociation[] associations)
        {
            if (null != associations)
            {
                foreach (EntityToExclusionsAssociation association in associations)
                {
                    if (null == association.Exclusions)
                    {
                        Console.WriteLine("The entity does not contain the requested exclusions.");
                    }
                    else
                    {
                        // The list contains only those exclusions that you requested. If the exclusion has 
                        // not been applied to the entity, it will not be included in the list.

                        Console.WriteLine("The entity contains the following exclusions that you requested.");

                        foreach (LocationExclusion exclusion in association.Exclusions)
                        {
                            if (null != exclusion.ExcludedGeoTargets)
                            {
                                Console.WriteLine("Target {0} excludes the following geo locations.", association.AssociatedEntity.Id);

                                foreach (ExcludedGeoLocation location in exclusion.ExcludedGeoTargets)
                                {
                                    Console.WriteLine("{0} ({1})", location.LocationName, location.LocationType);
                                }
                            }
                        }
                    }
                }
            }
        }

        // Adds a single location target to the customers target library. Returns the
        // ID of the single target.

        static long CreateTarget(long customerId)
        {
            AddTargetsToLibraryRequest request = new AddTargetsToLibraryRequest();
            AddTargetsToLibraryResponse response = null;

            // Specify the location target.

            Target[] targets = new Target[] {
                new Target {
                    Location = new LocationTarget() {
                        CountryTarget = new CountryTarget() {
                            Bids = new CountryTargetBid[] {
                                new CountryTargetBid() {
                                    CountryAndRegion = "US", // "GG"
                                    IncrementalBid = IncrementalBidPercentage.ZeroPercent
                                }
                            }
                        }
                    },
                    Name = "Test Location Exclusions"
                }
            };

            // Set the request header information. To add a target, you
            // must specify the CustomerID header, which should be the 
            // advertiser's customer ID.

            request.CustomerId = customerId.ToString();
            request.DeveloperToken = m_token;
            request.UserName = m_username;
            request.Password = m_password;

            // Set the request information.

            request.Targets = targets;

            try
            {
                response = service.AddTargetsToLibrary(request);

                Console.WriteLine("Added target \"{0}\" with ID {1}.",
                    targets[0].Name, response.TargetIds[0]);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("AddTargetsToLibrary failed with the following faults " +
                    "(no targets were added):\n");

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    if (105 == error.Code) //  InvalidCredentials
                    {
                        Console.WriteLine("The specified credentials are not valid or the account is inactive.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                            error.ErrorCode, error.Code, error.Message, error.Detail);
                    }
                }

                throw new Exception("", fault);
            }
            catch (FaultException<ApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("AddTargetsToLibrary failed with the following faults " +
                    "(no targets were added):\n");

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    if (106 == error.Code) //  UserIsNotAuthorized
                    {
                        Console.WriteLine("The user is not authorized to call this operation.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetails: {3}\n",
                            error.Code, error.ErrorCode, error.Message, error.Details);
                    }
                }

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {
                        case 1405: //  CampaignServiceInvalidLocationTarget
                            Console.WriteLine("The location code that you specified for target #{0} is not valid.\n",
                                error.Index + 1);
                            break;

                        default:
                            Console.WriteLine("Unable to add target, {0}.", targets[error.Index].Name);
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                throw new Exception("", fault);
            }

            return response.TargetIds[0];
        }

        // Removes the location target added at the start of this example.
        // Removing a target also removes the exclusions applied to it.

        static void RemoveTarget(long customerId, long targetId)
        {
            DeleteTargetsFromLibraryRequest request = new DeleteTargetsFromLibraryRequest();
            DeleteTargetsFromLibraryResponse response = null;

            // Set the request header information. To remove a target, you
            // must specify the CustomerID header, which should be the 
            // advertiser's customer ID.

            request.CustomerId = customerId.ToString();
            request.DeveloperToken = m_token;
            request.UserName = m_username;
            request.Password = m_password;

            // Set the request information.

            request.TargetIds = new long[] { targetId };

            try
            {
                response = service.DeleteTargetsFromLibrary(request);

                Console.WriteLine("Removed target {0}.", targetId);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("DeleteTargetsFromLibrary failed with the following faults:\n");

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    if (105 == error.Code) //  InvalidCredentials
                    {
                        Console.WriteLine("The specified credentials are not valid or the account is inactive.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                            error.ErrorCode, error.Code, error.Message, error.Detail);
                    }
                }

                throw new Exception("", fault);
            }
            catch (FaultException<ApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("DeleteTargetsFromLibrary failed with the following faults:\n");

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    if (106 == error.Code) //  UserIsNotAuthorized
                    {
                        Console.WriteLine("The user is not authorized to call this operation.");
                    }
                    else
                    {
                        Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetails: {3}\n",
                            error.Code, error.ErrorCode, error.Message, error.Details);
                    }
                }

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {
                        case 1405: //  CampaignServiceInvalidLocationTarget
                            Console.WriteLine("The location code that you specified for target #{0} is not valid.\n",
                                error.Index + 1);
                            break;

                        default:
                            Console.WriteLine("Unable to remove target, {0}.", request.TargetIds[error.Index]);
                            Console.WriteLine("Error code: {0} ({1})\nMessage: {2}\nDetail: {3}\n",
                                error.ErrorCode, error.Code, error.Message, error.Details);
                            break;
                    }
                }

                throw new Exception("", fault);
            }
        }
    }
}

Community Additions

Show:
© 2015 Microsoft