Export (0) Print
Expand All

Target Devices in C#

The following example shows how to target specific devices and operating systems 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 of 
// the service reference used for this example. 

using DeviceTargeting.BingAds.CampaignManagement;

namespace DeviceTargeting
{
    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 advertiser's account ID and customer ID.

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

        // The ID of the campaign that you want to target to specific devices.
        // The campaign must already be associated with a target.

        private static long m_campaignId = <campaignidgoeshere>; 


        static void Main(string[] args)
        {
            Target[] targets = null;

            try
            {
                service = new CampaignManagementServiceClient();

                targets = GetCampaignTargets(m_customerId, m_accountId, m_campaignId);

                if (null == targets[0])
                {
                    Console.WriteLine("Campaign {0} is not associated with a target.", m_campaignId);
                }
                else
                {
                    // Indexing targets array because a campaign can be associated
                    // with only one target object.

                    TargetDevices(m_customerId, (long)targets[0].Id);
                    PrintDeviceTargets(m_customerId, m_accountId, (long)targets[0].Id);
                    RemoveDeviceTarget(m_customerId, (long)targets[0].Id);
                }

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


        // Gets the target associated with the specified campaign. Because most
        // campaigns target a location, this example assumes that the campaign is 
        // already associated with a target object.

        // If the campaign is not associated with a target, you would need to create a
        // Target object that sets the Device element to computers or smartphones
        // (it doesn't matter which one). After calling the AddTargetsToLibrary 
        // operation to add the target to the target library, you would call the 
        // SetTargetToCampaign operation to associate the target with the campaign.

        static Target[] GetCampaignTargets(long customerId, long accountId, long campaignId)
        {
            GetTargetsByCampaignIdsRequest request = new GetTargetsByCampaignIdsRequest();
            GetTargetsByCampaignIdsResponse response = null;

            // Set the 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.CampaignIds = new long[] { campaignId };

            try
            {
                Console.WriteLine("Getting target associated with campaign {0}.", campaignId);

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

                Console.WriteLine("GetTargetsByCampaignIds 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("GetTargetsByCampaignIds failed with the following faults:\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 1029: //  CampaignServiceCustomerIdHasToBeSpecified
                            Console.WriteLine("The CustomerId header element cannot be null or empty.");
                            break;

                        case 1030: //  CampaignServiceAccountIdHasToBeSpecified
                            Console.WriteLine("The CustomerAccountId header element " +
                                "cannot be null or empty.");
                            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)
                    {
                        default:
                            Console.WriteLine("Error code: {0} ({1})\nIndex: {2}\nMessage: {3}\nDetail: {4}\n",
                                error.ErrorCode, error.Code, error.Index, error.Message, error.Details);
                            break;
                    }
                }

                throw new Exception("", fault);
            }

            return response.Targets;
        }


        // To target devices or operating systems, call the UpdateDeviceOSTargets
        // operation. Because the operation overwrites the current list 
        // of devices being targeted, you must specify all devices to target. 

        // This example targets only smartphones running the Windows operation system.
        // To target all operating systems of a device type, set OSName to null.  
        // If DeviceName is set to Computers, OSName must be set to null. 

        static void TargetDevices(long customerId, long targetId)
        {
            UpdateDeviceOSTargetsRequest request = new UpdateDeviceOSTargetsRequest();
            UpdateDeviceOSTargetsResponse response = null;

            // Define devices and operating systems to target.

            TargetAssociation[] targets = new TargetAssociation[] {
                new TargetAssociation {
                    DeviceOSTarget = new DeviceOSTarget() {
                        DeviceOSList = new DeviceOS[] {
                            new DeviceOS() {
                                DeviceName = "Smartphones",
                                OSName = "Windows"
                            }
                        }
                    },
                    Id = targetId
                }
            };

            // Set the header information.

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

            // Set the request information.

            request.TargetAssociations = targets;

            try
            {
                response = service.UpdateDeviceOSTargets(request);
                Console.WriteLine("Added device OS targets to target {0}.", targetId);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("UpdateDeviceOSTargets 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("UpdateDeviceOSTargets failed with the following faults:\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 1029: //  CampaignServiceCustomerIdHasToBeSpecified
                            Console.WriteLine("The CustomerId header element cannot be null or empty.");
                            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 2922: //  CampaignServiceInvalidDeviceTarget
                            Console.WriteLine("The device name and/or operating system name is not valid. " +
                                "The name cannot be null or empty and must be one of the predefined names. " +
                                "In addition, the combination of device name and operating system must be valid.\n");
                            break;

                        case 2923: //  CampaignServiceDuplicateDeviceTarget
                            Console.WriteLine("The list of devices cannot contain duplicate device and operating system combinations.\n");
                            break;

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

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


        // Gets the target associated with the specified campaign and prints the devices 
        // and operating systems that it targets. 

        static void PrintDeviceTargets(long customerId, long accountId, long targetId)
        {
            TargetAssociation[] deviceTargets = null;

            deviceTargets = GetDeviceTargets(customerId, (long)targetId);

            if (null == deviceTargets[0].DeviceOSTarget)
            {
                Console.WriteLine("The campaign targets all devices.");
            }
            else
            {
                Console.WriteLine("The campaign targets the following devices.");

                foreach (TargetAssociation deviceTarget in deviceTargets)
                {
                    foreach (DeviceOS device in deviceTarget.DeviceOSTarget.DeviceOSList)
                    {
                        Console.WriteLine("  {0} - {1}",
                            device.DeviceName,
                            (null == device.OSName) ? "All operating systems" : device.OSName);
                    }
                }
            }
        }

        // Gets the list of devices and operating systems being targeted.

        static TargetAssociation[] GetDeviceTargets(long customerId, long targetId)
        {
            GetDeviceOSTargetsByIdsRequest request = new GetDeviceOSTargetsByIdsRequest();
            GetDeviceOSTargetsByIdsResponse response = null;

            // Set the header information.

            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.GetDeviceOSTargetsByIds(request);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("GetDeviceOSTargetsByIds 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("GetDeviceOSTargetsByIds failed with the following faults:\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 206: //  NullArrayArgument
                            Console.WriteLine("The list of targets IDs cannot be null or empty.");
                            break;

                        case 1029: //  CampaignServiceCustomerIdHasToBeSpecified
                            Console.WriteLine("The CustomerId header element cannot be null or empty.");
                            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)
                    {
                        default:
                            Console.WriteLine("Error code: {0} ({1})\nIndex: {2}\nMessage: {3}\nDetail: {4}\n",
                                error.ErrorCode, error.Code, error.Index, error.Message, error.Details);
                            break;
                    }
                }

                throw new Exception("", fault);
            }

            return response.TargetAssociations;
        }

        // Removes the device targeting from the target object.

        static void RemoveDeviceTarget(long customerId, long targetId)
        {
            UpdateTargetsInLibraryRequest request = new UpdateTargetsInLibraryRequest();
            UpdateTargetsInLibraryResponse response = null;

            Target[] targets = GetTarget(customerId, targetId);

            targets[0].IsLibraryTarget = null;
            targets[0].Device = null;

            // Set the header information.

            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.UpdateTargetsInLibrary(request);
                Console.WriteLine("Removed device targeting from target {0}.", targetId);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("UpdateTargetsInLibrary 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("UpdateTargetsInLibrary failed with the following faults:\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 1029: //  CampaignServiceCustomerIdHasToBeSpecified
                            Console.WriteLine("The CustomerId header element cannot be null or empty.");
                            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)
                    {
                        default:
                            Console.WriteLine("Error code: {0} ({1})\nIndex: {2}\nMessage: {3}\nDetail: {4}\n",
                                error.ErrorCode, error.Code, error.Index, error.Message, error.Details);
                            break;
                    }
                }

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

        // Get the specified target from the library. 

        static Target[] GetTarget(long customerId, long targetId)
        {
            GetTargetsByIdsRequest request = new GetTargetsByIdsRequest();
            GetTargetsByIdsResponse response = null;

            // Set the header information.

            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 };
            request.LocationTargetVersion = "Latest"; 

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

                Console.WriteLine("GetTargetsByIds 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("GetTargetsByIds failed with the following faults:\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 1029: //  CampaignServiceCustomerIdHasToBeSpecified
                            Console.WriteLine("The CustomerId header element cannot be null or empty.");
                            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)
                    {
                        default:
                            Console.WriteLine("Error code: {0} ({1})\nIndex: {2}\nMessage: {3}\nDetail: {4}\n",
                                error.ErrorCode, error.Code, error.Index, error.Message, error.Details);
                            break;
                    }
                }

                throw new Exception("", fault);
            }

            return response.Targets;
        }

    }
}


Community Additions

Show:
© 2014 Microsoft