Export (0) Print
Expand All

Ad Extensions in C#

The following example shows how to add extensions to an account’s ad extension library, get extensions from the library, associate the extensions with a campaign, get the extensions that are associated 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# 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 AdExtensions.BingAds.CampaignManagement;


namespace AdExtensions
{
    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>;

        // Specify the identifier of the campaign to associate
        // the ad extensions with.

        private static long m_campaignId = <campaignidgoeshere>;


        // This example shows how to perform the following calls.
        //
        //   -  Call the AddAdExtensions operation to add a call, 
        //      location, and site links ad extension to an 
        //      account's ad extension library. 
        //
        //   -  Call the GetAdExtensionsByIds operation to get the 
        //      extensions from an account's ad extension library.
        // 
        //   -  Call the SetAdExtensionsToCampaigns operation to 
        //      associate extensions with a campaign. 
        //
        //   -  Call the GetAdExtensionsByCampaignIds operation to 
        //      get extensions that are associated with a campaign.
        //
        //   -  Call the GetAdExtensionsEditorialReasonsByCampaignIds
        //      operation to get the reasons for and editorial failure.

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

            try
            {
                service = new CampaignManagementServiceClient();

                ids = AddExtensions(m_customerId, m_accountId);
                PrintExtensions(m_accountId, ids);
                AssociateExtensionsWithCampaign(m_accountId, m_campaignId, ids);
                PrintExtensionsAssociatedWithCampaigns(m_customerId, m_accountId, new long[] { m_campaignId });

                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 and ad extension of each type (for example, a location ad
        // extension and a call ad extension) to the account's
        // ad extension library.

        static long[] AddExtensions(long customerId, long accountId)
        {
            AddAdExtensionsRequest request = new AddAdExtensionsRequest();
            AddAdExtensionsResponse response = null;
            long[] ids = null;

            // Specify the extensions.

            AdExtension2[] extensions = new AdExtension2[] {
                new SiteLinksAdExtension {
                    SiteLinks = new [] {
                        new SiteLink {
                            DestinationUrl = "AplineSkiHouse.com/WinterGloveSale",
                            DisplayText = "Winter Glove Sale"
                        }
                    }
                },
                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", // Can contain the state name or code (i.e. WA)
                        CountryCode = "US",
                        PostalCode = "98608",
                    }
                }
            };

            // Set the header information.

            request.CustomerId = customerId.ToString();  // Required for image/icon
            request.CustomerAccountId = accountId.ToString();
            request.DeveloperToken = m_token;
            request.UserName = m_username;
            request.Password = m_password;

            // Set the request information.

            request.AccountId = accountId;
            request.AdExtensions = extensions;

            try
            {
                response = service.AddAdExtensions(request);

                ids = new long[response.AdExtensionIdentities.Length];

                for (int i = 0; i < response.AdExtensionIdentities.Length; i++)
                {
                    ids[i] = response.AdExtensionIdentities[i].Id;
                }
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("AddAdExtensions 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("AddAdExtensions 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 3862: // CampaignServiceLocationAdExtensionsEntityLimitExceeded
                            Console.WriteLine("The number of location ad extensions in the " +
                                "ad extensions list exceeds the maximum allowed.\n");
                            break;

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

                // This list of errors codes is just a sampling of the possible errors that 
                // AddAdExtensions can throw.

                // Note that the Details element of BatchErrors contains the zero-based
                // index of the site link in the list of site links that caused the error.

                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    switch (error.Code)
                    {
                        case 3804: // CampaignServiceSiteLinkDestinationUrlNullOrEmpty
                            Console.WriteLine("The destination URL of site link #{0} in " +
                                "extension #{1} cannot be null or empty.\n",
                                error.Details, 
                                error.Index);
                            break;

                        case 3805: // CampaignServiceSiteLinkDisplayTextNullOrEmpty
                            Console.WriteLine("The display URL of site link #{0} in " +
                                "extension #{1} cannot be null or empty.\n",
                                error.Details, 
                                error.Index);
                            break;

                        case 3806: // CampaignServiceSiteLinkDestinationUrlTooLong
                            Console.WriteLine("The destination URL of site link #{0} in " +
                                "extension #{1} is too long.\n",
                                error.Details, 
                                error.Index);
                            break;

                        case 3807: // CampaignServiceSiteLinkDisplayTextTooLong
                            Console.WriteLine("The display URL of site link #{0} in " +
                                "extension #{1} is too long.\n",
                                error.Details, 
                                error.Index);
                            break;

                        case 3809: // CampaignServiceTooManySiteLinks
                            Console.WriteLine("The list of site links contains too many items.\n");
                            break;

                        case 3828: // CampaignServiceAdExtensionAddressIsNull
                            Console.WriteLine("The address in extension #{0} cannot be null.\n",
                                error.Index);
                            break;

                        case 3829: // CampaignServiceAdExtensionStreetAddressNullOrEmpty
                            Console.WriteLine("The first line of the street address in " +
                                "extension #{0} cannot be null or empty.\n",
                                error.Index);
                            break;

                        case 3830: // CampaignServiceAdExtensionStreetAddressTooLong
                            Console.WriteLine("The first line of the street address in " +
                                "extension #{0} is too long.\n",
                                error.Index);
                            break;

                        case 3834: // CampaignServiceAdExtensionCityNameNullOrEmpty
                            Console.WriteLine("The city name in extension #{0} cannot be " +
                                "null or empty.\n",
                                error.Index);
                            break;

                        case 3839: // CampaignServiceAdExtensionPostalCodeNullOrEmpty
                            Console.WriteLine("The postal code in extension #{0} cannot " +
                                "be null or empty.\n",
                                error.Index + 1);
                            break;

                        case 3842: // CampaignServiceAdExtensionCountryCodeNullOrEmpty
                            Console.WriteLine("The country code in extension #{0} cannot " +
                                "be null or empty.\n",
                                error.Index);
                            break;

                        case 3844: // CampaignServiceAdExtensionCountryCodeInvalid
                            Console.WriteLine("The country code in extension #{0} is not valid.\n",
                                error.Index);
                            break;

                        case 3847: // CampaignServiceAdExtensionCompanyNameNullOrEmpty
                            Console.WriteLine("The company name in extension #{0} cannot " +
                                "be null or empty.\n",
                                error.Index);
                            break;

                        case 3850: // CampaignServiceAdExtensionPhoneNumberTooLong
                            Console.WriteLine("The phone number in extension #{0} is too long.\n",
                                error.Index);
                            break;

                        case 3851: // CampaignServiceAdExtensionPhoneNumberInvalid
                            Console.WriteLine("The phone number in extension #{0} is not valid.\n",
                                error.Index);
                            break;

                        case 3852: // CampaignServiceAdExtensionIconMediaIdInvalid
                            Console.WriteLine("The icon in extension #{0} was not " +
                                "found in the account’s media library.\n",
                                error.Index);
                            break;

                        case 3853: // CampaignServiceAdExtensionIconTooLarge
                            Console.WriteLine("The width and height of the icon in " +
                                "extension #{0} is greater than the maximum allowed.\n",
                                error.Index);
                            break;

                        case 3854: // CampaignServiceAdExtensionImageMediaIdInvalid
                            Console.WriteLine("The image in extension #{0} was not found " +
                                "in the account’s media library.\n",
                                error.Index);
                            break;

                        case 3855: // CampaignServiceAdExtensionImageTooLarge
                            Console.WriteLine("The width and height of the image in " +
                                "extension #{0} is greater than the maximum allowed.\n",
                                error.Index);
                            break;

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

                        case 3857: //  CampaignServiceCallAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To add call extensions, the customer must be a " +
                                "member of the call ad extensions v2 pilot program.");
                            break;

                        case 3859: // CampaignServiceAdExtensionProvinceCodeInvalid
                            Console.WriteLine("The province code in extension #{0} " +
                                "is not valid.\n",
                                error.Index);
                            break;

                        case 3860: // CampaignServiceAdExtensionProvinceCodeRequiredIfProvinceNameEmpty
                            Console.WriteLine("The province code in extension #{0} is " +
                                "required if the province name is empty.\n",
                                error.Index);
                            break;

                        case 3861: // CampaignServiceAdExtensionPhoneNumberNullOrEmpty
                            Console.WriteLine("The phone number in extension #{0} " +
                                "cannot be null or empty.\n",
                                error.Index);
                            break;

                        default:
                            Console.WriteLine("Unable to add extension #{0}", 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);
            }

            return ids;
        }

        // Gets the specified ad extensions from the account's library
        // and prints their contents.

        static void PrintExtensions(long accountId, long[] ids)
        {
            GetAdExtensionsByIdsRequest request = new GetAdExtensionsByIdsRequest();
            GetAdExtensionsByIdsResponse response = null;
            int i = 0;

            // 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.CallAdExtension |
                AdExtensionsTypeFilter.LocationAdExtension;

            try
            {
                response = service.GetAdExtensionsByIds(request);

                foreach (AdExtension2 extension in response.AdExtensions)
                {
                    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 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)
                        {
                            // Ads will not include the location extension until the business' coordinates 
                            // (longitude and latitude) are determined using the business' address. The GeoCodeStatus
                            // field indicates the progress. It can take from seconds to minutes to determine
                            // the coordinates.

                            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
                        {
                            Console.WriteLine("  Unknown extension type");
                        }
                    }

                    Console.WriteLine();
                    i++;
                }
            }
            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);
                    }
                }

            }
            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, the customer must " +
                                "be a member of the location ad extensions v2 pilot program.");
                            break;

                        case 3857: //  CampaignServiceCallAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To get call extensions, the customer 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;
                    }
                }

            }
        }

        // Associates one or more extensions with a campaign.

        static void AssociateExtensionsWithCampaign(long accountId, long campaignId, long[] extensionIds)
        {
            SetAdExtensionsToCampaignsRequest request = new SetAdExtensionsToCampaignsRequest();
            SetAdExtensionsToCampaignsResponse response = null;

            if (0 == extensionIds.Length)
            {
                return;
            }

            // Loop through the list of extension IDs and build
            // the association objects.

            AdExtensionIdToCampaignIdAssociation[] associations = new AdExtensionIdToCampaignIdAssociation[extensionIds.Length];

            for (int i = 0; i < extensionIds.Length; i++)
            {
                associations[i] = new AdExtensionIdToCampaignIdAssociation
                {
                    AdExtensionId = extensionIds[i],
                    CampaignId = campaignId
                };
            };

            // 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.AdExtensionIdToCampaignIdAssociations = associations;

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

                Console.WriteLine("SetAdExtensionsToCampaigns 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("SetAdExtensionsToCampaigns 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 3810: //  CampaignServiceAdExtensionIdToCampaignIdAssociationArrayShouldNotBeN
                            Console.WriteLine("The list of ad extension to campaign " +
                                "associations 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 1100: //  CampaignServiceInvalidCampaignId
                            Console.WriteLine("The campaign ID specified in ad extension " +
                                "to campaign association #{0} is not valid.",
                                error.Index);
                            break;

                        case 1397: //  CampaignServiceEditorialGenericError
                            Console.WriteLine("The ad extension specified in ad extension " +
                                "to campaign association #{0} failed editorial review. " +
                                "The term that failed review is \"{1}\".",
                                error.Index,
                                error.Details);
                            break;

                        case 3812: //  CampaignServiceInvalidAdExtensionId
                            Console.WriteLine("The ad extension ID specified in ad " +
                                "extension to campaign association #{0} is not valid.",
                                error.Index);
                            break;

                        case 3818: //  CampaignServiceCannotAssignMoreThanOneAdExtensionTypeToAnEntity
                            Console.WriteLine("The campaign specified in ad extension to " +
                                "campaign association #{0} can contain only one extension of " +
                                "the specified type.",
                                error.Index);
                            break;

                        case 3825: //  CampaignServiceDuplicateInAdExtensionIdToCampaignIdAssociations
                            Console.WriteLine("The list of ad extension to campaign " +
                                "associations contains a duplicate ad extension ID " +
                                "for the same campaign. Association #{0} contains the duplicate.",
                                error.Index);
                            break;

                        case 3856: //  CampaignServiceLocationAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To call this operation, the customer must be a " +
                                "member of the location ad extensions pilot program.");
                            break;

                        case 3857: //  CampaignServiceCallAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To call this operation, the customer must be a " +
                                "member of the call ad extensions pilot program.");
                            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 extensions associated with the specified campaigns
        // and print the extensions ID, type, and editorial status.

        private static void PrintExtensionsAssociatedWithCampaigns(long customerId, long accountId, long[] campaignIds)
        {
            GetAdExtensionsByCampaignIdsRequest request = new GetAdExtensionsByCampaignIdsRequest();
            GetAdExtensionsByCampaignIdsResponse response = null;
            AdExtensionEditorialReasonCollection[] editorialCollection = null;
            int i = 0;

            // 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.CampaignIds = campaignIds;
            request.AdExtensionType |= AdExtensionsTypeFilter.SiteLinksAdExtension |
                AdExtensionsTypeFilter.CallAdExtension |
                AdExtensionsTypeFilter.LocationAdExtension;

            try
            {
                response = service.GetAdExtensionsByCampaignIds(request);

                // Loop through the results for each campaign.

                foreach (CampaignAdExtensionCollection campaign in response.CampaignAdExtensionCollection)
                {
                    if (null == campaign)
                    {
                        Console.WriteLine("Campaign ID {0} is not valid.", campaignIds[i]);
                    }
                    else
                    {
                        // If the campaign contains extensions of the specified type...

                        if (campaign.CampaignAdExtensions.Length > 0)
                        {
                            Console.WriteLine("Ad extensions associated with campaign ID {0}:", campaign.CampaignAdExtensions[0].CampaignId);

                            foreach (CampaignAdExtension extension in campaign.CampaignAdExtensions)
                            {
                                Console.WriteLine("Ad extension ID: " + extension.AdExtension.Id);
                                Console.WriteLine("Ad extension Type: " + extension.AdExtension.Type);
                                Console.WriteLine("Ad extension Editorial Status: {0}",
                                    (extension.EditorialStatus == CampaignAdExtensionEditorialStatus.Inactive) ?
                                        "Under review" : extension.EditorialStatus.ToString()
                                    );

                                // If the extension failed editorial review, find out why and which 
                                // publisher countries were affected.

                                if (extension.EditorialStatus == CampaignAdExtensionEditorialStatus.ActiveLimited ||
                                    extension.EditorialStatus == CampaignAdExtensionEditorialStatus.Disapproved)
                                {
                                    editorialCollection = GetEditorialReasons(customerId,
                                        accountId,
                                        campaign.CampaignAdExtensions[0].CampaignId,
                                        (long)extension.AdExtension.Id,
                                        (AdExtensionsTypeFilter)Enum.Parse(typeof(AdExtensionsTypeFilter), extension.AdExtension.Type));

                                    foreach (AdExtensionEditorialReason editorialReason in editorialCollection[0].Reasons)
                                    {
                                        Console.WriteLine("  Reason code: " + editorialReason.ReasonCode);
                                        Console.WriteLine("  Term : " + editorialReason.Term);
                                        Console.WriteLine("  Location : " + editorialReason.Location);
                                        Console.Write("  Publisher countries: ");

                                        int j = 1;
                                        int length = editorialReason.PublisherCountries.Length;
                                        foreach (string country in editorialReason.PublisherCountries)
                                        {
                                            Console.Write("{0}{1}", country, (j++ < length) ? ", " : "\n");
                                        }
                                    }
                                }

                                Console.WriteLine();
                            }
                        }
                        else
                        {
                            Console.WriteLine("Campaign ID {0} does not contain ad extensions " +
                                "that match the specified extension types.",
                                campaignIds[i]);
                        }
                    }

                    i++;
                }
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("GetAdExtensionsByCampaignIds 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("GetAdExtensionsByCampaignIds 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 1118: //  CampaignServiceCampaignIdsArrayShouldNotBeNullOrEmpty
                            Console.WriteLine("The list of campaign IDs cannot " +
                                "be null or empty.");
                            break;

                        case 1119: //  CampaignServiceCampaignIdsArrayExceedsLimit
                            Console.WriteLine("The list of campaign IDs is too long.");
                            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 call this operation, the customer must be a " +
                                "member of the location ad extensions v2 pilot program.");
                            break;

                        case 3857: //  CampaignServiceCallAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To call this operation, the customer 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 1107: //  CampaignServiceDuplicateCampaignIds
                            Console.WriteLine("The list of campaign IDs contains duplicates. " +
                                "Id {0} is a duplicate.",
                                request.CampaignIds[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);
            }
        }

        // Gets the reasons why the specified extension failed editorial
        // review. The review is performed in the context of the campaign.

        private static AdExtensionEditorialReasonCollection[] GetEditorialReasons(
            long customerId, 
            long accountId, 
            long campaignId, 
            long extensionId, 
            AdExtensionsTypeFilter extensionType)
        {
            GetAdExtensionsEditorialReasonsByCampaignIdsRequest request = new GetAdExtensionsEditorialReasonsByCampaignIdsRequest();
            GetAdExtensionsEditorialReasonsByCampaignIdsResponse response = null;

            // Specify the extension to campaign association.

            AdExtensionIdToCampaignIdAssociation[] associations = new[] { 
                new AdExtensionIdToCampaignIdAssociation {
                    AdExtensionId = extensionId,
                    CampaignId = campaignId 
                }
            };

            // Set the header information.

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

            // Set the request information.

            request.AccountId = accountId;
            request.AdExtensionIdToCampaignIdAssociations = associations;
            request.AdExtensionType |= extensionType;

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

                Console.WriteLine("GetAdExtensionsEditorialReasonsByCampaignIds 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("GetAdExtensionsEditorialReasonsByCampaignIds 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 customer ID header element is required.");
                            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 3810: //  CampaignServiceAdExtensionIdToCampaignIdAssociationArrayShouldNotBeNullOrEmpty
                            Console.WriteLine("The list of ad extension to campaign " +
                                "associations cannot be null or empty.");
                            break;

                        case 3811: //  CampaignServiceAdExtensionIdToCampaignIdAssociationArrayLimitExceeded
                            Console.WriteLine("The list of ad extension to campaign " +
                                "associations is too long.");
                            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 call this operation, the customer must be a " +
                                "member of the location ad extensions pilot program.");
                            break;

                        case 3857: //  CampaignServiceCallAdExtensionPilotNotEnabledForCustomer
                            Console.WriteLine("To call this operation, the customer must be a " +
                                "member of the call ad extensions 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.EditorialReasons;
        }
    }
}

Community Additions

Show:
© 2014 Microsoft