Export (0) Print
Expand All

Get Ad Extensions from Library in C#

The following example shows how to get the IDs of the extensions in the account's extension library, and then use the IDs to get the extensions 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 GetExtensions.BingAds.CampaignManagement;


namespace GetExtensions
{
    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 that contains the extensions.

        private static long m_accountId = <accountidgoeshere>;


        // This example shows how to get the IDs of the extensions in the account's 
        // extension library. It then uses the IDs to get the extensions and print them.

        static void Main(string[] args)
        {
            long[] ids = null;
            AdExtension2[] extensions = null;

            try
            {
                service = new CampaignManagementServiceClient();

                ids = GetExtensionIds(m_accountId);
                extensions = GetExtensions(m_accountId, ids);
                PrintExtensions(m_accountId, extensions, ids);

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

        // Get the IDs of the extensions in the specified account's
        // ad extension library. You must specify the types of extensions 
        // to get. You can get all extensions or only those associated
        // with a campaign.
        
        static long[] GetExtensionIds(long accountId)
        {
            GetAdExtensionIdsByAccountIdRequest request = new GetAdExtensionIdsByAccountIdRequest();
            GetAdExtensionIdsByAccountIdResponse response = null;

            // Set the header information.

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

            // Set the request information.

            request.AccountId = accountId;
            request.AssociationFilter = AssociationFilter.All; 
            request.AdExtensionType |= AdExtensionsTypeFilter.SiteLinksAdExtension  |
                AdExtensionsTypeFilter.LocationAdExtension |
                AdExtensionsTypeFilter.CallAdExtension |
                AdExtensionsTypeFilter.ProductsAdExtension;

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

                Console.WriteLine("GetAdExtensionIdsByAccountId 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("GetAdExtensionIdsByAccountId 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 1030: //  CampaignServiceAccountIdHasToBeSpecified
                            Console.WriteLine("The CustomerAccountId header element cannot be null or empty.");
                            break;

                        case 1102: //  CampaignServiceInvalidAccountId
                            Console.WriteLine("The account ID is not valid.");
                            break;

                        case 3814: //  CampaignServiceInvalidAdExtensionTypeFilter
                            Console.WriteLine("The ad extension type filter is null or is not one of the allowed extension types.");
                            break;

                        case 3856: //  CampaignServiceLocationAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To get location extensions, you must be a member of the location ad extensions v2 pilot program.");
                            break;

                        case 3857: //  CampaignServiceCallAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To get call extensions, you must be a member of the call ad extensions v2 pilot program.");
                            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.AdExtensionIds;
        }

        // Gets the specified ad extensions from the specified account.

        static AdExtension2[] GetExtensions(long accountId, long[] ids)
        {
            GetAdExtensionsByIdsRequest request = new GetAdExtensionsByIdsRequest();
            GetAdExtensionsByIdsResponse response = null;

            // Set the header information.

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

            // Set the request information.

            request.AccountId = accountId;
            request.AdExtensionIds = ids;
            request.AdExtensionType |= AdExtensionsTypeFilter.SiteLinksAdExtension |
                AdExtensionsTypeFilter.LocationAdExtension |
                AdExtensionsTypeFilter.CallAdExtension | 
                AdExtensionsTypeFilter.ProductsAdExtension;

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

                Console.WriteLine("GetAdExtensionsByIds 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("GetAdExtensionsByIds 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 1030: //  CampaignServiceAccountIdHasToBeSpecified
                            Console.WriteLine("The CustomerAccountId header element cannot be null or empty.");
                            break;

                        case 1102: //  CampaignServiceInvalidAccountId
                            Console.WriteLine("The account ID is not valid.");
                            break;

                        case 3814: //  CampaignServiceInvalidAdExtensionTypeFilter
                            Console.WriteLine("The ad extension type filter is null or is not one of the allowed extension types.");
                            break;

                        case 3815: //  CampaignServiceAdExtensionIdArrayShouldNotBeNullOrEmpty
                            Console.WriteLine("The list of extension IDs cannot be null or empty.");
                            break;

                        case 3816: //  CampaignServiceAdExtensionIdsArrayExceedsLimit
                            Console.WriteLine("The list of ad extension IDs is too long.");
                            break;

                        case 3856: //  CampaignServiceLocationAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To get location extensions, you must be a member of the location ad extensions v2 pilot program.");
                            break;

                        case 3857: //  CampaignServiceCallAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To get call extensions, you must be a member of the call ad extensions v2 pilot program.");
                            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 3817: //  CampaignServiceDuplicateInAdExtensionIds
                            Console.WriteLine("The list of extension IDs contains duplicates. Id {0} is a duplicate.",
                                request.AdExtensionIds[error.Index]);
                            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);
            }

            return response.AdExtensions;
        }

        // Prints the contents of the ad extensions.

        static void PrintExtensions(long accountId, AdExtension2[] extensions, long[] ids)
        {
            int i = 0;  // Index into ids

            foreach (AdExtension2 extension in extensions)
            {
                if (null == extension)
                {
                    Console.WriteLine("Extension ID {0} is not a valid ID or the extension does not match the request type.", ids[i]);
                }
                else
                {
                    Console.WriteLine("Ad extension ID: " + extension.Id);
                    Console.WriteLine("Ad extension Status: " + extension.Status);
                    Console.WriteLine("Ad extension Type: " + extension.Type);

                    if (extension is SiteLinksAdExtension)
                    {
                        foreach (SiteLink siteLink in ((SiteLinksAdExtension)extension).SiteLinks)
                        {
                            Console.WriteLine("  Display URL: " + siteLink.DisplayText);
                            Console.WriteLine("  Destination URL: " + siteLink.DestinationUrl);
                            Console.WriteLine();
                        }
                    }
                    else if (extension is CallAdExtension)
                    {
                        Console.WriteLine("Phone number: " + ((CallAdExtension)extension).PhoneNumber);
                        Console.WriteLine("Country: " + ((CallAdExtension)extension).CountryCode);
                        Console.WriteLine("Is only clickable item: " + ((CallAdExtension)extension).IsCallOnly);
                        Console.WriteLine();
                    }
                    else if (extension is LocationAdExtension)
                    {
                        Console.WriteLine("Company name: " + ((LocationAdExtension)extension).CompanyName);
                        Console.WriteLine("Phone number: " + ((LocationAdExtension)extension).PhoneNumber);
                        Console.WriteLine("Street: " + ((LocationAdExtension)extension).Address.StreetAddress);
                        Console.WriteLine("City: " + ((LocationAdExtension)extension).Address.CityName);
                        Console.WriteLine("State: " + ((LocationAdExtension)extension).Address.ProvinceName);
                        Console.WriteLine("Country: " + ((LocationAdExtension)extension).Address.CountryCode);
                        Console.WriteLine("Zip code: " + ((LocationAdExtension)extension).Address.PostalCode);
                        Console.WriteLine("Business coordinates determined?: " + ((LocationAdExtension)extension).GeoCodeStatus);

                        if (BusinessGeoCodeStatus.Complete == ((LocationAdExtension)extension).GeoCodeStatus)
                        {
                            Console.WriteLine("  Latitude: " + ((LocationAdExtension)extension).GeoPoint.LatitudeInMicroDegrees);
                            Console.WriteLine("  Longitude: " + ((LocationAdExtension)extension).GeoPoint.LongitudeInMicroDegrees);
                        }

                        Console.WriteLine("Map icon ID: " + ((LocationAdExtension)extension).IconMediaId);
                        Console.WriteLine("Business image ID: " + ((LocationAdExtension)extension).ImageMediaId);
                        Console.WriteLine();
                    }
                    else if (extension is ProductAdExtension)
                    {
                        Console.WriteLine("Product collection ID: " + ((ProductAdExtension)extension).ProductCollectionId);
                        Console.WriteLine("Product selection filters: ");

                        if (null == ((ProductAdExtension)extension).ProductSelection || 0 == ((ProductAdExtension)extension).ProductSelection.Length)
                        {
                            Console.WriteLine("  There are no filters specified; all products are selected.");
                        }
                        else
                        {
                            foreach (ProductConditionCollection collection in ((ProductAdExtension)extension).ProductSelection)
                            {
                                Console.Write("  Filter: ");

                                int length = collection.Conditions.Length;

                                for (int j = 0; j < length; j++)
                                {
                                    Console.Write("{0}={1}{2}", collection.Conditions[j].Operand,
                                        collection.Conditions[j].Attribute,
                                        (j + 1 < length) ? " AND " : "\n");
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("  Unknown extension type");
                    }
                }

                Console.WriteLine();
                i++;
            }
        }
    }
}

Community Additions

Show:
© 2015 Microsoft