Export (0) Print
Expand All

Ad Extensions in C#

The following example shows how to add, get, and delete extensions for an account’s ad extension library, set, get, and delete the extension associations with a campaign, and determine why an extension failed editorial review using the following Campaign Management service operations.

This example has been developed and run within the environment described in Getting Started Using C# 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.Globalization;
using System.ServiceModel;

// BingAds.CampaignManagement is the application-defined namespace of 
// the service reference used for this example. 

using AdExtensions.BingAds.CampaignManagement;


namespace AdExtensions
{
    class Program
    {
        private static CampaignManagementServiceClient _service;

        // Specify your credentials.

        private const string UserName = "<UserNameGoesHere>";
        private const string Password = "<PasswordGoesHere>";
        private const string DeveloperToken = "<DeveloperTokenGoesHere>";
        private const long CustomerId = <CustomerIdGoesHere>;
        private const long AccountId = <AccountIdGoesHere>;
        private const long CampaignId = <CampaignIdGoesHere>;


        static void Main()
        {
            try
            {
                _service = new CampaignManagementServiceClient();

                // Specify the extensions.

                var adExtensions = new AdExtension[] {
                    new CallAdExtension {
                        CountryCode = "US",
                        PhoneNumber = "2065550100",
                        IsCallOnly = false
                    },
                    new LocationAdExtension {
                        PhoneNumber = "206-555-0100",
                        CompanyName = "Alpine Ski House",
                        IconMediaId = null,
                        ImageMediaId = null,
                        Address = new Address {
                            StreetAddress = "1234 Washington Place",
                            StreetAddress2 = "Suite 1210",
                            CityName = "Woodinville",
                            ProvinceName = "WA",
                            CountryCode = "US",
                            PostalCode = "98608"
                        }
                    },
                    new SiteLinksAdExtension {
                        SiteLinks = new [] {
                            new SiteLink {
                                DestinationUrl = "AplineSkiHouse.com/WinterGloveSale",
                                DisplayText = "Winter Glove Sale"
                            }
                        }
                    }
                };

                // Add all extensions to the account's ad extension library
                var adExtensionIdentities = AddAdExtensions(
                    AccountId,
                    adExtensions
                    );

                // DeleteAdExtensionsAssociations, SetAdExtensionsAssociations, and GetAdExtensionsEditorialReasons 
                // operations each require a list of type AdExtensionIdToEntityIdAssociation.
                var adExtensionIdToEntityIdAssociations = new AdExtensionIdToEntityIdAssociation[adExtensionIdentities.Length];

                // GetAdExtensionsByIds requires a list of type long.
                var adExtensionIds = new long[adExtensionIdentities.Length];
                
                // Loop through the list of extension IDs and build any required data structures
                // for subsequent operations. 

                for (int i = 0; i < adExtensionIdentities.Length; i++)
                {
                    adExtensionIdToEntityIdAssociations[i] = new AdExtensionIdToEntityIdAssociation
                    {
                        AdExtensionId = adExtensionIdentities[i].Id,
                        EntityId = CampaignId
                    };

                    adExtensionIds[i] = adExtensionIdentities[i].Id;
                }

                // Associate the specified ad extensions with the respective campaigns or ad groups. 
                SetAdExtensionsAssociations(
                    AccountId, 
                    adExtensionIdToEntityIdAssociations, 
                    AssociationType.Campaign
                    );

                // Get editorial rejection reasons for the respective ad extension and entity associations.
                AdExtensionEditorialReasonCollection[] adExtensionEditorialReasonCollection = GetAdExtensionsEditorialReasons(
                    CustomerId, 
                    AccountId, 
                    adExtensionIdToEntityIdAssociations, 
                    AssociationType.Campaign
                    );

                const AdExtensionsTypeFilter adExtensionsTypeFilter = AdExtensionsTypeFilter.CallAdExtension |
                                                                      AdExtensionsTypeFilter.LocationAdExtension |
                                                                      AdExtensionsTypeFilter.SiteLinksAdExtension;

                // Get the specified ad extensions from the account’s ad extension library.
                adExtensions = (AdExtension[]) GetAdExtensionsByIds(
                    AccountId,
                    adExtensionIds, 
                    adExtensionsTypeFilter
                    );

                var index = 0;

                foreach (var extension in adExtensions)
                {
                    if (extension == null || extension.Id == null)
                    {
                        Console.WriteLine("Extension is null or invalid.");
                    }
                    else
                    {
                        Console.WriteLine("Ad extension ID: " + extension.Id);
                        Console.WriteLine("Ad extension Type: " + extension.Type);
                        
                        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);
                            Console.WriteLine("Map icon ID: " + ((LocationAdExtension)extension).IconMediaId);
                            Console.WriteLine("Business image ID: " + ((LocationAdExtension)extension).ImageMediaId);
                            Console.WriteLine();
                        }
                        else 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
                        {
                            Console.WriteLine("Unknown extension type");
                        }

                        if (adExtensionEditorialReasonCollection != null 
                            && adExtensionEditorialReasonCollection.Length > 0
                            && adExtensionEditorialReasonCollection[index] != null)
                        {
                            Console.WriteLine();
                            
                            // Print any editorial rejection reasons for the corresponding extension. This sample 
                            // assumes the same list index for adExtensions and adExtensionEditorialReasonCollection
                            // as defined above.

                            foreach (var adExtensionEditorialReason in adExtensionEditorialReasonCollection[index].Reasons)
                            {
                                if (adExtensionEditorialReason != null &&
                                    adExtensionEditorialReason.PublisherCountries != null)
                                {
                                    Console.WriteLine("Editorial Rejection Location: " + adExtensionEditorialReason.Location);
                                    Console.WriteLine("Editorial Rejection PublisherCountries: ");
                                    foreach (var publisherCountry in adExtensionEditorialReason.PublisherCountries)
                                    {
                                        Console.WriteLine("  " + publisherCountry);
                                    }
                                    Console.WriteLine("Editorial Rejection ReasonCode: " + adExtensionEditorialReason.ReasonCode);
                                    Console.WriteLine("Editorial Rejection Term: " + adExtensionEditorialReason.Term);
                                    Console.WriteLine();
                                }
                            }
                        }
                    }
                    
                    Console.WriteLine();

                    index++;
                }

                // Remove the specified associations from the respective campaigns or ad groups. 
                // The extesions are still available in the account's extensions library. 
                DeleteAdExtensionsAssociations(
                    AccountId,
                    adExtensionIdToEntityIdAssociations,
                    AssociationType.Campaign
                    );

                // Deletes the ad extensions from the account’s ad extension library.
                DeleteAdExtensions(
                    AccountId,
                    adExtensionIds
                    );
                
                _service.Close();
            }
            // Campaign Management service operations can throw AdApiFaultDetail.
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

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

                // If the AdApiError array is not null, the following are examples of error codes that may be found.
                foreach (AdApiError error in fault.Detail.Errors)
                {
                    Console.WriteLine("AdApiError");
                    Console.WriteLine("Code: {0}\nError Code: {1}\nMessage: {2}\n", error.Code, error.ErrorCode, error.Message);

                    switch (error.Code)
                    {
                        case 0:     // InternalError
                            break;
                        case 105:   // InvalidCredentials
                            break;
                        case 117:   // CallRateExceeded
                            break;
                        default:
                            Console.WriteLine("Please see MSDN documentation for more details about the error code output above.");
                            break;
                    }
                }
            }
            // Some Campaign Management service operations such as SetAdExtensionsAssociations can throw EditorialApiFaultDetail.
            catch (FaultException<EditorialApiFaultDetail> fault)
            {
                // Log this fault.

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

                // If the BatchError array is not null, the following are examples of error codes that may be found.
                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    Console.WriteLine("BatchError at Index: {0}", error.Index);
                    Console.WriteLine("Code: {0}\nError Code: {1}\nMessage: {2}\n", error.Code, error.ErrorCode, error.Message);

                    switch (error.Code)
                    {
                        case 0:     // InternalError
                            break;
                        default:
                            Console.WriteLine("Please see MSDN documentation for more details about the error code output above.");
                            break;
                    }
                }

                // If the EditorialError array is not null, the following are examples of error codes that may be found.
                foreach (EditorialError error in fault.Detail.EditorialErrors)
                {
                    Console.WriteLine("EditorialError at Index: {0}", error.Index);
                    Console.WriteLine("Code: {0}\nError Code: {1}\nMessage: {2}\n", error.Code, error.ErrorCode, error.Message);
                    Console.WriteLine("Appealable: {0}\nDisapproved Text: {1}\nCountry: {2}\n", error.Appealable, error.DisapprovedText, error.PublisherCountry);

                    switch (error.Code)
                    {
                        case 0:     // InternalError
                            break;
                        default:
                            Console.WriteLine("Please see MSDN documentation for more details about the error code output above.");
                            break;
                    }
                }

                // If the OperationError array is not null, the following are examples of error codes that may be found.
                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    Console.WriteLine("OperationError");
                    Console.WriteLine("Code: {0}\nError Code: {1}\nMessage: {2}\n", error.Code, error.ErrorCode, error.Message);

                    switch (error.Code)
                    {
                        case 0:     // InternalError
                            break;
                        case 106:   // UserIsNotAuthorized
                            break;
                        case 1102:  // CampaignServiceInvalidAccountId
                            break;
                        default:
                            Console.WriteLine("Please see MSDN documentation for more details about the error code output above.");
                            break;
                    }
                }
            }
            catch (CommunicationException e)
            {
                Console.WriteLine(e.Message);

                if (e.InnerException != null)
                {
                    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)
            {
                Console.WriteLine(e.Message);

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

        // Adds one or more ad extensions to the account's ad extension library.

        static AdExtensionIdentity[] AddAdExtensions(long accountId, AdExtension[] adExtensions)
        {
            var request = new AddAdExtensionsRequest
                {
                    // Set the header information.
                    UserName = UserName,
                    Password = Password,
                    DeveloperToken = DeveloperToken,
                    CustomerAccountId = accountId.ToString(CultureInfo.InvariantCulture),

                    // Set the request information.
                    AccountId = accountId,
                    AdExtensions = adExtensions
                };
            return _service.AddAdExtensions(request).AdExtensionIdentities;
        }

        // Deletes one or more ad extensions from the account’s ad extension library.

        static void DeleteAdExtensions(long accountId, long[] adExtensionIds)
        {
            var request = new DeleteAdExtensionsRequest
            {
                // Set the header information.
                UserName = UserName,
                Password = Password,
                DeveloperToken = DeveloperToken,
                CustomerAccountId = accountId.ToString(CultureInfo.InvariantCulture),

                // Set the request information.
                AccountId = accountId,
                AdExtensionIds = adExtensionIds
            };

            _service.DeleteAdExtensions(request);
        }

        // Associates one or more extensions with the corresponding campaign or ad group entities.

        static void SetAdExtensionsAssociations(long accountId, AdExtensionIdToEntityIdAssociation[] associations, AssociationType associationType)
        {
            var request = new SetAdExtensionsAssociationsRequest
                {
                    // Set the header information.
                    UserName = UserName,
                    Password = Password,
                    DeveloperToken = DeveloperToken,
                    CustomerAccountId = accountId.ToString(CultureInfo.InvariantCulture),

                    // Set the request information.
                    AccountId = accountId,
                    AdExtensionIdToEntityIdAssociations = associations,
                    AssociationType = associationType
                };

            _service.SetAdExtensionsAssociations(request);
        }

        // Removes the specified association from the respective campaigns or ad groups.

        static void DeleteAdExtensionsAssociations(long accountId, AdExtensionIdToEntityIdAssociation[] associations, AssociationType associationType)
        {
            var request = new DeleteAdExtensionsAssociationsRequest
            {
                // Set the header information.
                UserName = UserName,
                Password = Password,
                DeveloperToken = DeveloperToken,
                CustomerAccountId = accountId.ToString(CultureInfo.InvariantCulture),

                // Set the request information.
                AccountId = accountId,
                AdExtensionIdToEntityIdAssociations = associations,
                AssociationType = associationType
            };

            _service.DeleteAdExtensionsAssociations(request);
        }

        // Gets the specified ad extensions from the account's extension library.

        static IEnumerable<AdExtension> GetAdExtensionsByIds(long accountId, long[] adExtensionIds, AdExtensionsTypeFilter adExtensionsTypeFilter)
        {
            var request = new GetAdExtensionsByIdsRequest
                {
                    // Set the header information.
                    UserName = UserName,
                    Password = Password,
                    DeveloperToken = DeveloperToken,
                    CustomerAccountId = accountId.ToString(CultureInfo.InvariantCulture),

                    // Set the request information.
                    AccountId = accountId,
                    AdExtensionIds = adExtensionIds,
                    AdExtensionType = adExtensionsTypeFilter
                };
           
            return _service.GetAdExtensionsByIds(request).AdExtensions;
        }

        // Gets the reasons why the specified extension failed editorial when 
        // in the context of an associated campaign or ad group.

        private static AdExtensionEditorialReasonCollection[] GetAdExtensionsEditorialReasons(
            long customerId,
            long accountId,
            AdExtensionIdToEntityIdAssociation[] associations,
            AssociationType associationType)
        {
            var request = new GetAdExtensionsEditorialReasonsRequest
                {
                    // Set the header information.
                    UserName = UserName,
                    Password = Password,
                    DeveloperToken = DeveloperToken,
                    CustomerId = customerId.ToString(CultureInfo.InvariantCulture),
                    CustomerAccountId = accountId.ToString(CultureInfo.InvariantCulture),

                    // Set the request information.
                    AccountId = accountId,
                    AdExtensionIdToEntityIdAssociations = associations,
                    AssociationType = associationType
                };

            return _service.GetAdExtensionsEditorialReasons(request).EditorialReasons;
        }
    }
}

Community Additions

ADD
Show:
© 2014 Microsoft