Extensions Samples

The code samples below provide examples of common extension functions using the AdWords API. Client Library.

Associate a Google My Business feed to that of a customer

' Copyright 2018 Google LLC
'
' Licensed under the Apache License, Version 2.0 (the "License")
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
'     http:'www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201809
Imports Google.Api.Ads.Common.Lib

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example adds a feed that syncs feed items from a Google
    ''' My Business (GMB) account and associates the feed with a customer.
    ''' </summary>
    Public Class AddGoogleMyBusinessLocationExtensions
        Inherits ExampleBase

        ''' <summary>
        ''' The placeholder type for location extensions. See the Placeholder
        ''' reference page for a list of all the placeholder types and fields.
        '''
        ''' https://developers.google.com/adwords/api/docs/appendix/placeholders
        ''' </summary>
        Private Const PLACEHOLDER_LOCATION As Integer = 7

        ''' <summary>
        ''' Main method, to run this code example as a standalone application.
        ''' </summary>
        ''' <param name="args">The command line arguments.</param>
        Public Shared Sub Main(ByVal args As String())
            Dim codeExample As New AddGoogleMyBusinessLocationExtensions
            Console.WriteLine(codeExample.Description)

            Dim user As New AdWordsUser

            Try
                ' The email address of either an owner or a manager of the GMB account.
                Dim gmbEmailAddress As String = "INSERT_GMB_EMAIL_ADDRESS_HERE"

                ' Refresh the access token so that there's a valid access token.
                user.OAuthProvider.RefreshAccessToken()

                ' If the gmbEmailAddress above is the same user you used to generate
                ' your AdWords API refresh token, leave the assignment below unchanged.
                ' Otherwise, to obtain an access token for your GMB account, run the
                ' OAuth Token generator utility while logged in as the same user as
                ' gmbEmailAddress. Copy and paste the AccessToken value into the
                ' assignment below.
                Dim gmbAccessToken As String = user.Config.OAuth2AccessToken

                ' If the gmbEmailAddress above is for a GMB manager instead of the GMB
                ' account owner, then set businessAccountIdentifier to the +Page ID of
                ' a location for which the manager has access. See the location
                ' extensions guide at
                ' https://developers.google.com/adwords/api/docs/guides/feed-services-locations
                ' for details.
                Dim businessAccountIdentifier As String = Nothing
                codeExample.Run(user, gmbEmailAddress, gmbAccessToken,
                                businessAccountIdentifier)
            Catch e As Exception
                Console.WriteLine("An exception occurred while running this code example. {0}",
                                  ExampleUtilities.FormatException(e))
            End Try
        End Sub

        ''' <summary>
        ''' Returns a description about the code example.
        ''' </summary>
        Public Overrides ReadOnly Property Description() As String
            Get
                Return "This code example adds a feed that syncs feed items from a Google my " &
                       " Business (GMB) account and associates the feed with a customer."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="gmbEmailAddress">The email address for Google My Business
        ''' account.</param>
        ''' <param name="gmbAccessToken">The OAuth2 access token for Google
        ''' My Business account.</param>
        ''' <param name="businessAccountIdentifier">The account identifier for
        ''' Google My Business account.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal gmbEmailAddress As String,
                       ByVal gmbAccessToken As String, ByVal businessAccountIdentifier As String)
            Dim gmbFeed As Feed = CreateGmbFeed(user, gmbEmailAddress, gmbAccessToken,
                                                businessAccountIdentifier)
            AddCustomerFeed(user, gmbFeed)
        End Sub

        ''' <summary>
        ''' Create a feed that will sync to the Google My Business account
        ''' specified by gmbEmailAddress.
        ''' </summary>
        ''' <param name="user">The user.</param>
        ''' <param name="gmbEmailAddress">The GMB email address.</param>
        ''' <param name="gmbAccessToken">The GMB access token.</param>
        ''' <param name="businessAccountIdentifier">The GMB account identifier.</param>
        ''' <returns>The newly created GMB feed.</returns>
        Private Shared Function CreateGmbFeed(ByVal user As AdWordsUser,
                                              ByVal gmbEmailAddress As String,
                                              ByVal gmbAccessToken As String,
                                              ByVal businessAccountIdentifier As String) As Feed
            Using feedService As FeedService = CType(
                user.GetService(
                    AdWordsService.v201809.FeedService),
                FeedService)

                ' Create a feed that will sync to the Google My Business account
                ' specified by gmbEmailAddress. Do not add FeedAttributes to this object,
                ' as AdWords will add them automatically because this will be a
                ' system generated feed.
                Dim gmbFeed As New Feed()
                gmbFeed.name = String.Format("Google My Business feed #{0}",
                                             ExampleUtilities.GetRandomString())

                Dim feedData As New PlacesLocationFeedData()
                feedData.emailAddress = gmbEmailAddress
                feedData.businessAccountIdentifier = businessAccountIdentifier

                ' Optional: specify labels to filter Google My Business listings. If
                ' specified, only listings that have any of the labels set are
                ' synchronized into FeedItems.
                feedData.labelFilters = New String() {"Stores in New York City"}

                Dim oAuthInfo As New OAuthInfo()
                oAuthInfo.httpMethod = "GET"

                ' Permissions for the AdWords API scope will also cover GMB.
                oAuthInfo.httpRequestUrl = user.Config.GetDefaultOAuth2Scope()
                oAuthInfo.httpAuthorizationHeader = String.Format("Bearer {0}", gmbAccessToken)
                feedData.oAuthInfo = oAuthInfo

                gmbFeed.systemFeedGenerationData = feedData

                ' Since this feed's feed items will be managed by AdWords,
                ' you must set its origin to ADWORDS.
                gmbFeed.origin = FeedOrigin.ADWORDS

                ' Create an operation to add the feed.
                Dim feedOperation As New FeedOperation()
                feedOperation.operand = gmbFeed
                feedOperation.operator = [Operator].ADD

                Try
                    ' Add the feed. Since it is a system generated feed, AdWords will
                    ' automatically:
                    ' 1. Set up the FeedAttributes on the feed.
                    ' 2. Set up a FeedMapping that associates the FeedAttributes of the
                    ' Feed with the placeholder fields of the LOCATION placeholder type.
                    Dim addFeedResult As FeedReturnValue = feedService.mutate(
                        New FeedOperation() {feedOperation})
                    Dim addedFeed As Feed = addFeedResult.value(0)
                    Console.WriteLine("Added GMB feed with ID {0}", addedFeed.id)
                    Return addedFeed
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to create GMB feed.", e)
                End Try
            End Using
        End Function

        ''' <summary>
        ''' Add a CustomerFeed that associates the feed with this customer for
        ''' the LOCATION placeholder type.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="feed">The GMB feed.</param>
        Sub AddCustomerFeed(ByVal user As AdWordsUser, ByVal feed As Feed)
            Using customerFeedService As CustomerFeedService = CType(
                user.GetService(
                    AdWordsService.v201809.CustomerFeedService),
                CustomerFeedService)

                ' Add a CustomerFeed that associates the feed with this customer for
                ' the LOCATION placeholder type.
                Dim customerFeed As New CustomerFeed()
                customerFeed.feedId = feed.id
                customerFeed.placeholderTypes = New Integer() {PLACEHOLDER_LOCATION}

                ' Create a matching function that will always evaluate to true.
                Dim customerMatchingFunction As New [Function]()
                Dim constOperand As New ConstantOperand()
                constOperand.type = ConstantOperandConstantType.BOOLEAN
                constOperand.booleanValue = True
                customerMatchingFunction.lhsOperand = New FunctionArgumentOperand() {constOperand}
                customerMatchingFunction.operator = FunctionOperator.IDENTITY
                customerFeed.matchingFunction = customerMatchingFunction

                ' Create an operation to add the customer feed.
                Dim customerFeedOperation As New CustomerFeedOperation()
                customerFeedOperation.operand = customerFeed
                customerFeedOperation.operator = [Operator].ADD

                ' After the completion of the Feed ADD operation above the added feed
                ' will not be available for usage in a CustomerFeed until the sync
                ' between the AdWords and GMB accounts completes.  The loop below
                ' will retry adding the CustomerFeed up to ten times with an
                ' exponential back-off policy.
                Dim addedCustomerFeed As CustomerFeed = Nothing

                Dim config As New AdWordsAppConfig()
                config.RetryCount = 10

                Dim errorHandler As New ErrorHandler(config)
                Try
                    Do
                        Try
                            Dim customerFeedResult As CustomerFeedReturnValue =
                                    customerFeedService.mutate(
                                        New CustomerFeedOperation() _
                                                                  {customerFeedOperation})
                            addedCustomerFeed = customerFeedResult.value(0)

                            Console.WriteLine(
                                "Added CustomerFeed for feed ID {0} and placeholder type {1}",
                                addedCustomerFeed.feedId, addedCustomerFeed.placeholderTypes(0))
                            Exit Do
                        Catch e As AdWordsApiException
                            Dim apiException As ApiException = CType(e.ApiException, ApiException)
                            For Each apiError As ApiError In apiException.errors
                                If TypeOf apiError Is CustomerFeedError Then
                                    If (DirectCast(apiError, CustomerFeedError).reason =
                                        CustomerFeedErrorReason.
                                            MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE) Then
                                        errorHandler.DoExponentialBackoff()
                                        errorHandler.IncrementRetriedAttempts()
                                    Else
                                        Throw
                                    End If
                                End If
                            Next

                        End Try
                    Loop While (errorHandler.HaveMoreRetryAttemptsLeft())

                    ' OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at
                    ' the Campaign level.  This will be similar to the CampaignFeed in the
                    ' AddSiteLinks example, except you can also filter based on the
                    ' business name and category of each FeedItem by using a
                    ' FeedAttributeOperand in your matching function.

                    ' OPTIONAL: Create an AdGroupFeed for even more fine grained control
                    ' over which feed items are used at the AdGroup level.
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to create customer feed.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Associate a price extension to an account

' Copyright 2018 Google LLC
'
' Licensed under the Apache License, Version 2.0 (the "License")
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
'     http:'www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201809

Imports DayOfWeek = Google.Api.Ads.AdWords.v201809.DayOfWeek

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example adds a price extension and associates it with an
    ''' account. Campaign targeting is also set using the specified campaign ID.
    ''' To get campaigns, run AddCampaigns.vb.
    ''' </summary>
    Public Class AddPrices
        Inherits ExampleBase

        ''' <summary>
        ''' Main method, to run this code example as a standalone application.
        ''' </summary>
        ''' <param name="args">The command line arguments.</param>
        Public Shared Sub Main(ByVal args As String())
            Dim codeExample As New AddPrices
            Console.WriteLine(codeExample.Description)
            Try
                Dim campaignId As Long = Long.Parse("INSERT_CAMPAIGN_ID_HERE")
                codeExample.Run(New AdWordsUser, campaignId)
            Catch e As Exception
                Console.WriteLine("An exception occurred while running this code example. {0}",
                                  ExampleUtilities.FormatException(e))
            End Try
        End Sub

        ''' <summary>
        ''' Returns a description about the code example.
        ''' </summary>
        Public Overrides ReadOnly Property Description() As String
            Get
                Return _
                    "This code example adds a price extension and associates it with an account. " &
                    "Campaign targeting is also set using the specified campaign ID. To get " &
                    "campaigns, run AddCampaigns.vb."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="campaignId">Id of the campaign with which sitelinks are associated.
        ''' </param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long)
            Using customerExtensionSettingService As CustomerExtensionSettingService =
                DirectCast(user.GetService(AdWordsService.v201809.CustomerExtensionSettingService),
                           CustomerExtensionSettingService)

                ' Create the price extension feed item.
                Dim priceFeedItem As New PriceFeedItem
                priceFeedItem.priceExtensionType = PriceExtensionType.SERVICES

                ' Price qualifier is optional.
                priceFeedItem.priceQualifier = PriceExtensionPriceQualifier.FROM
                priceFeedItem.trackingUrlTemplate = "http://tracker.example.com/?u={lpurl}"
                priceFeedItem.language = "en"

                priceFeedItem.campaignTargeting = New FeedItemCampaignTargeting()
                priceFeedItem.campaignTargeting.TargetingCampaignId = campaignId

                Dim saturdaySchedule As New FeedItemSchedule
                saturdaySchedule.dayOfWeek = DayOfWeek.SATURDAY
                saturdaySchedule.startHour = 10
                saturdaySchedule.startMinute = MinuteOfHour.ZERO
                saturdaySchedule.endHour = 22
                saturdaySchedule.endMinute = MinuteOfHour.ZERO

                Dim sundaySchedule As New FeedItemSchedule
                sundaySchedule.dayOfWeek = DayOfWeek.SUNDAY
                sundaySchedule.startHour = 10
                sundaySchedule.startMinute = MinuteOfHour.ZERO
                sundaySchedule.endHour = 18
                sundaySchedule.endMinute = MinuteOfHour.ZERO

                priceFeedItem.scheduling = New FeedItemSchedule() {saturdaySchedule, sundaySchedule}

                ' To create a price extension, at least three table rows are needed.
                Dim priceTableRows As New List(Of PriceTableRow)

                Dim currencyCode As String = "USD"

                priceTableRows.Add(
                    CreatePriceTableRow(
                        "Scrubs",
                        "Body Scrub, Salt Scrub",
                        "http://www.example.com/scrubs",
                        "http://m.example.com/scrubs",
                        60000000,
                        currencyCode,
                        PriceExtensionPriceUnit.PER_HOUR))
                priceTableRows.Add(
                    CreatePriceTableRow(
                        "Hair Cuts",
                        "Once a month",
                        "http://www.example.com/haircuts",
                        "http://m.example.com/haircuts",
                        75000000,
                        currencyCode,
                        PriceExtensionPriceUnit.PER_MONTH))
                priceTableRows.Add(
                    CreatePriceTableRow(
                        "Skin Care Package",
                        "Four times a month",
                        "http://www.example.com/skincarepackage",
                        Nothing,
                        250000000,
                        currencyCode,
                        PriceExtensionPriceUnit.PER_MONTH))

                priceFeedItem.tableRows = priceTableRows.ToArray()

                ' Create your campaign extension settings. This associates the sitelinks
                ' to your campaign.
                Dim customerExtensionSetting As New CustomerExtensionSetting
                customerExtensionSetting.extensionType = FeedType.PRICE
                customerExtensionSetting.extensionSetting = New ExtensionSetting
                customerExtensionSetting.extensionSetting.extensions =
                    New ExtensionFeedItem() {priceFeedItem}

                Dim operation As New CustomerExtensionSettingOperation
                operation.operand = customerExtensionSetting
                operation.operator = [Operator].ADD

                Try
                    ' Add the extensions.
                    Dim retVal As CustomerExtensionSettingReturnValue =
                            customerExtensionSettingService.mutate(
                                New CustomerExtensionSettingOperation() {operation})
                    If Not (retVal.value Is Nothing) AndAlso retVal.value.Length > 0 Then
                        Dim newExtensionSetting As CustomerExtensionSetting = retVal.value(0)
                        Console.WriteLine("Extension setting with type '{0}' was added.",
                                          newExtensionSetting.extensionType)
                    Else
                        Console.WriteLine("No extension settings were created.")
                    End If
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to create extension settings.", e)
                End Try
            End Using
        End Sub

        ''' <summary>
        ''' Creates a price table row.
        ''' </summary>
        ''' <param name="header">The row header.</param>
        ''' <param name="description">The description text.</param>
        ''' <param name="finalUrl">The final URL.</param>
        ''' <param name="finalMobileUrl">The mobile final URL, or null if this field
        ''' should not be set.</param>
        ''' <param name="priceInMicros">The price in micros.</param>
        ''' <param name="currencyCode">The currency code.</param>
        ''' <param name="priceUnit">The price unit.</param>
        ''' <returns>A price table row for creating price extension.</returns>
        Private Shared Function CreatePriceTableRow(ByVal header As String,
                                                    ByVal description As String,
                                                    ByVal finalUrl As String,
                                                    ByVal finalMobileUrl As String,
                                                    ByVal priceInMicros As Long,
                                                    ByVal currencyCode As String,
                                                    ByVal priceUnit As PriceExtensionPriceUnit) _
            As PriceTableRow

            Dim retval As New PriceTableRow
            retval.header = header
            retval.description = description
            retval.finalUrls = New UrlList()
            retval.finalUrls.urls = New String() {finalUrl}

            Dim moneyWithCurrency As New MoneyWithCurrency
            moneyWithCurrency.currencyCode = currencyCode
            moneyWithCurrency.money = New Money
            moneyWithCurrency.money.microAmount = priceInMicros

            retval.price = moneyWithCurrency
            retval.priceUnit = priceUnit

            ' Optional: Set the mobile final URLs.
            If Not String.IsNullOrEmpty(finalMobileUrl) Then
                retval.finalMobileUrls = New UrlList()
                retval.finalMobileUrls.urls = New String() {finalMobileUrl}
            End If

            Return retval
        End Function
    End Class
End Namespace

Add sitelinks to a campaign

' Copyright 2018 Google LLC
'
' Licensed under the Apache License, Version 2.0 (the "License")
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
'     http:'www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201809

Imports DayOfWeek = Google.Api.Ads.AdWords.v201809.DayOfWeek

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example adds sitelinks to a campaign. To create a campaign,
    ''' run AddCampaign.vb.
    ''' </summary>
    Public Class AddSitelinks
        Inherits ExampleBase

        ''' <summary>
        ''' Main method, to run this code example as a standalone application.
        ''' </summary>
        ''' <param name="args">The command line arguments.</param>
        Public Shared Sub Main(ByVal args As String())
            Dim codeExample As New AddSitelinks
            Console.WriteLine(codeExample.Description)
            Try
                Dim campaignId As Long = Long.Parse("INSERT_CAMPAIGN_ID_HERE")
                codeExample.Run(New AdWordsUser, campaignId)
            Catch e As Exception
                Console.WriteLine("An exception occurred while running this code example. {0}",
                                  ExampleUtilities.FormatException(e))
            End Try
        End Sub

        ''' <summary>
        ''' Returns a description about the code example.
        ''' </summary>
        Public Overrides ReadOnly Property Description() As String
            Get
                Return _
                    "This code example adds sitelinks to a campaign. To create a campaign, run " &
                    "AddCampaign.vb."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="campaignId">Id of the campaign with which sitelinks are associated.
        ''' </param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long)
            Using campaignExtensionSettingService As CampaignExtensionSettingService =
                DirectCast(user.GetService(AdWordsService.v201809.CampaignExtensionSettingService),
                           CampaignExtensionSettingService)

                Dim customerService As CustomerService =
                        DirectCast(user.GetService(AdWordsService.v201809.CustomerService),
                                   CustomerService)

                ' Find the matching customer and its time zone. The getCustomers method
                ' will return a single Customer object corresponding to the session's
                ' clientCustomerId.
                Dim customer As Customer = customerService.getCustomers()(0)
                Console.WriteLine("Found customer ID {0:###-###-####} with time zone '{1}'.",
                                  customer.customerId, customer.dateTimeZone)

                Dim extensions As New List(Of ExtensionFeedItem)

                ' Create your sitelinks.
                Dim sitelink1 As New SitelinkFeedItem()
                sitelink1.sitelinkText = "Store Hours"
                sitelink1.sitelinkFinalUrls = New UrlList()
                sitelink1.sitelinkFinalUrls.urls = New String() _
                    {"http://www.example.com/storehours"}
                extensions.Add(sitelink1)

                Dim startOfThanksGiving As New DateTime(DateTime.Now.Year, 11, 20, 0, 0, 0)
                Dim endOfThanksGiving As New DateTime(DateTime.Now.Year, 11, 27, 23, 59, 59)

                ' Add check to make sure we don't create a sitelink with end date in the
                ' past.
                If DateTime.Now < endOfThanksGiving Then
                    ' Show the Thanksgiving specials link only from 20 - 27 Nov.
                    Dim sitelink2 As New SitelinkFeedItem()
                    sitelink2.sitelinkText = "Thanksgiving Specials"
                    sitelink2.sitelinkFinalUrls = New UrlList()
                    sitelink2.sitelinkFinalUrls.urls = New String() _
                        {"http://www.example.com/thanksgiving"}

                    sitelink2.startTime = String.Format("{0}1120 000000 {1}", DateTime.Now.Year,
                                                        customer.dateTimeZone)
                    sitelink2.endTime = String.Format("{0}1127 235959 {1}", DateTime.Now.Year,
                                                      customer.dateTimeZone)

                    ' Target this sitelink for United States only. See
                    ' https://developers.google.com/adwords/api/docs/appendix/geotargeting
                    ' for valid geolocation codes.
                    sitelink2.geoTargeting = New Location()
                    sitelink2.geoTargeting.id = 2840

                    ' Restrict targeting only to people physically within the United States.
                    ' Otherwise, this could also show to people interested in the United States
                    ' but not physically located there.
                    Dim geoTargetingRestriction As New FeedItemGeoRestriction()
                    geoTargetingRestriction.geoRestriction = GeoRestriction.LOCATION_OF_PRESENCE
                    sitelink2.geoTargetingRestriction = geoTargetingRestriction

                    extensions.Add(sitelink2)
                End If

                ' Show the wifi details primarily for high end mobile users.
                Dim sitelink3 As New SitelinkFeedItem()
                sitelink3.sitelinkText = "Wifi available"
                sitelink3.sitelinkFinalUrls = New UrlList()
                sitelink3.sitelinkFinalUrls.urls = New String() _
                    {"http://www.example.com/mobile/wifi"}
                sitelink3.devicePreference = New FeedItemDevicePreference()
                sitelink3.devicePreference.devicePreference = 30001
                extensions.Add(sitelink3)

                ' Show the happy hours link only during Mon - Fri 6PM to 9PM.
                Dim sitelink4 As New SitelinkFeedItem()
                sitelink4.sitelinkText = "Happy hours"
                sitelink4.sitelinkFinalUrls = New UrlList()
                sitelink4.sitelinkFinalUrls.urls = New String() _
                    {"http://www.example.com/happyhours"}
                extensions.Add(sitelink4)

                Dim schedule1 As New FeedItemSchedule()
                schedule1.dayOfWeek = DayOfWeek.MONDAY
                schedule1.startHour = 18
                schedule1.startMinute = MinuteOfHour.ZERO
                schedule1.endHour = 21
                schedule1.endMinute = MinuteOfHour.ZERO

                Dim schedule2 As New FeedItemSchedule()
                schedule2.dayOfWeek = DayOfWeek.TUESDAY
                schedule2.startHour = 18
                schedule2.startMinute = MinuteOfHour.ZERO
                schedule2.endHour = 21
                schedule2.endMinute = MinuteOfHour.ZERO

                Dim schedule3 As New FeedItemSchedule()
                schedule3.dayOfWeek = DayOfWeek.WEDNESDAY
                schedule3.startHour = 18
                schedule3.startMinute = MinuteOfHour.ZERO
                schedule3.endHour = 21
                schedule3.endMinute = MinuteOfHour.ZERO

                Dim schedule4 As New FeedItemSchedule()
                schedule4.dayOfWeek = DayOfWeek.THURSDAY
                schedule4.startHour = 18
                schedule4.startMinute = MinuteOfHour.ZERO
                schedule4.endHour = 21
                schedule4.endMinute = MinuteOfHour.ZERO

                Dim schedule5 As New FeedItemSchedule()
                schedule5.dayOfWeek = DayOfWeek.FRIDAY
                schedule5.startHour = 18
                schedule5.startMinute = MinuteOfHour.ZERO
                schedule5.endHour = 21
                schedule5.endMinute = MinuteOfHour.ZERO

                sitelink4.scheduling = New FeedItemSchedule() { _
                                                                  schedule1, schedule2, schedule3,
                                                                  schedule4, schedule5
                                                              }

                ' Create your campaign extension settings. This associates the sitelinks
                ' to your campaign.
                Dim campaignExtensionSetting As New CampaignExtensionSetting()
                campaignExtensionSetting.campaignId = campaignId
                campaignExtensionSetting.extensionType = FeedType.SITELINK
                campaignExtensionSetting.extensionSetting = New ExtensionSetting()
                campaignExtensionSetting.extensionSetting.extensions = extensions.ToArray

                Dim extensionOperation As New CampaignExtensionSettingOperation()
                extensionOperation.operand = campaignExtensionSetting
                extensionOperation.operator = [Operator].ADD

                Try
                    ' Add the extensions.
                    Dim retVal As CampaignExtensionSettingReturnValue =
                            campaignExtensionSettingService.mutate(
                                New CampaignExtensionSettingOperation() _
                                                                      {extensionOperation})

                    ' Display the results.
                    If Not (retVal.value Is Nothing) AndAlso retVal.value.Length > 0 Then
                        Dim newExtensionSetting As CampaignExtensionSetting = retVal.value(0)
                        Console.WriteLine(
                            "Extension setting with type = {0} was added to campaign ID {1}.",
                            newExtensionSetting.extensionType, newExtensionSetting.campaignId)
                    Else
                        Console.WriteLine("No extension settings were created.")
                    End If
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to create extension settings.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Add sitelinks to a campaign using feeds

' Copyright 2018 Google LLC
'
' Licensed under the Apache License, Version 2.0 (the "License")
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
'     http:'www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201809

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' Holds data about sitelinks in a feed.
    ''' </summary>
    Public Class SitelinksDataHolder
        Dim feedIdField As Long
        Dim feedItemIdsField As New List(Of Long)

        Dim linkTextFeedAttributeIdField As Long
        Dim linkFinalUrlFeedAttributeIdField As Long
        Dim line2FeedAttributeIdField As Long
        Dim line3FeedAttributeIdField As Long

        ''' <summary>
        ''' Gets or sets the feed ID.
        ''' </summary>
        Public Property FeedId As Long
            Get
                Return feedIdField
            End Get
            Set(ByVal value As Long)
                feedIdField = value
            End Set
        End Property

        ''' <summary>
        ''' Gets the sitelink feed item IDs.
        ''' </summary>
        Public ReadOnly Property FeedItemIds As List(Of Long)
            Get
                Return feedItemIdsField
            End Get
        End Property

        ''' <summary>
        ''' Gets or sets the link text feed attribute ID.
        ''' </summary>
        Public Property LinkTextFeedAttributeId As Long
            Get
                Return linkTextFeedAttributeIdField
            End Get
            Set(ByVal value As Long)
                linkTextFeedAttributeIdField = value
            End Set
        End Property

        ''' <summary>
        ''' Gets or sets the link URL feed attribute ID.
        ''' </summary>
        Public Property LinkFinalUrlFeedAttributeId As Long
            Get
                Return linkFinalUrlFeedAttributeIdField
            End Get
            Set(ByVal value As Long)
                linkFinalUrlFeedAttributeIdField = value
            End Set
        End Property

        ''' <summary>
        ''' Gets or sets the line 2 feed attribute ID.
        ''' </summary>
        Public Property Line2FeedAttributeId As Long
            Get
                Return line2FeedAttributeIdField
            End Get
            Set(ByVal value As Long)
                line2FeedAttributeIdField = value
            End Set
        End Property

        ''' <summary>
        ''' Gets or sets the line 3 feed attribute ID.
        ''' </summary>
        Public Property Line3FeedAttributeId As Long
            Get
                Return line3FeedAttributeIdField
            End Get
            Set(ByVal value As Long)
                line3FeedAttributeIdField = value
            End Set
        End Property
    End Class

    ''' <summary>
    ''' This code example adds a sitelinks feed and associates it with a campaign.
    ''' To create a campaign, run AddCampaign.cs.
    ''' </summary>
    Public Class AddSitelinksUsingFeeds
        Inherits ExampleBase

        ''' <summary>
        ''' Main method, to run this code example as a standalone application.
        ''' </summary>
        ''' <param name="args">The command line arguments.</param>
        Public Shared Sub Main(ByVal args As String())
            Dim codeExample As New AddSitelinksUsingFeeds
            Console.WriteLine(codeExample.Description)
            Try
                Dim campaignId As Long = Long.Parse("INSERT_CAMPAIGN_ID_HERE")
                Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
                Dim feedName As String = "INSERT_FEED_NAME_HERE"
                codeExample.Run(New AdWordsUser, campaignId, feedName, adGroupId)
            Catch e As Exception
                Console.WriteLine("An exception occurred while running this code example. {0}",
                                  ExampleUtilities.FormatException(e))
            End Try
        End Sub

        ''' <summary>
        ''' Returns a description about the code example.
        ''' </summary>
        Public Overrides ReadOnly Property Description() As String
            Get
                Return "This code example adds a sitelinks feed and associates it with a campaign."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="campaignId">Id of the campaign with which sitelinks are associated.
        ''' </param>
        ''' <param name="adGroupId">Id of the adgroup to restrict targeting to.</param>
        ''' <param name="feedName">Name of the feed.</param>
        Public Sub Run(ByVal user As AdWordsUser,
                       ByVal campaignId As Long,
                       ByVal feedName As String,
                       ByVal adGroupId As Long?)
            Dim siteLinksData As New SitelinksDataHolder
            CreateSitelinksFeed(user, siteLinksData, feedName)
            CreateSitelinksFeedItems(user, siteLinksData)
            CreateSitelinksFeedMapping(user, siteLinksData)
            CreateSitelinksCampaignFeed(user, siteLinksData, campaignId)
            RestrictFeedItemToAdGroup(user, siteLinksData, adGroupId)
        End Sub

        Private Sub RestrictFeedItemToAdGroup(user As AdWordsUser,
                                              siteLinksData As SitelinksDataHolder,
                                              adGroupId As Long?)

            Dim adGroupTarget As New FeedItemAdGroupTarget()
            adGroupTarget.feedId = siteLinksData.FeedId
            adGroupTarget.feedItemId = siteLinksData.FeedItemIds(0)
            adGroupTarget.adGroupId = adGroupId.Value

            Using feedItemTargetService As FeedItemTargetService = CType(
                user.GetService(
                    AdWordsService.v201809.FeedItemTargetService),
                FeedItemTargetService)
                Dim operation As New FeedItemTargetOperation()
                operation.operator = [Operator].ADD
                operation.operand = adGroupTarget

                Dim retval As FeedItemTargetReturnValue = feedItemTargetService.mutate(
                    New FeedItemTargetOperation() {operation})
                Dim newAdGroupTarget As FeedItemAdGroupTarget =
                        CType(retval.value(0), FeedItemAdGroupTarget)
                Console.WriteLine("Feed item target for feed ID {0} and feed item ID {1}" +
                                  " was created to restrict serving to ad group ID {2}",
                                  newAdGroupTarget.feedId, newAdGroupTarget.feedItemId,
                                  newAdGroupTarget.adGroupId)
            End Using
        End Sub

        Private Shared Sub RestrictFeedItemToGeoTarget(ByVal user As AdWordsUser,
                                                       ByVal feedItem As FeedItem,
                                                       ByVal locationId As Long)
            ' Optional: Restrict the first feed item to only serve with ads for the
            ' specified geo target.
            Dim criterionTarget As New FeedItemCriterionTarget()
            criterionTarget.feedId = feedItem.feedId
            criterionTarget.feedItemId = feedItem.feedItemId
            ' The IDs can be found in the documentation or retrieved with the
            ' LocationCriterionService.
            Dim location As New Location()
            location.id = locationId
            criterionTarget.criterion = location

            Using feedItemTargetService As FeedItemTargetService = CType(
                user.GetService(
                    AdWordsService.v201809.FeedItemTargetService),
                FeedItemTargetService)
                Dim operation As New FeedItemTargetOperation()
                operation.operator = [Operator].ADD
                operation.operand = criterionTarget

                Dim retval As FeedItemTargetReturnValue = feedItemTargetService.mutate(
                    New FeedItemTargetOperation() {operation})
                Dim newLocationTarget As FeedItemCriterionTarget = CType(retval.value(0),
                                                                         FeedItemCriterionTarget)
                Console.WriteLine("Feed item target for feed ID {0} and feed item ID {1}" &
                                  " was created to restrict serving to location ID {2}",
                                  newLocationTarget.feedId, newLocationTarget.feedItemId,
                                  newLocationTarget.criterion.id)
            End Using
        End Sub

        Private Sub CreateSitelinksFeed(
                                        ByVal user As AdWordsUser,
                                        ByVal sitelinksData As SitelinksDataHolder,
                                        ByVal feedName As String)
            Using feedService As FeedService = CType(
                user.GetService(
                    AdWordsService.v201809.FeedService),
                FeedService)

                ' Create attributes.
                Dim textAttribute As New FeedAttribute
                textAttribute.type = FeedAttributeType.STRING
                textAttribute.name = "Link Text"

                Dim finalUrlAttribute As New FeedAttribute
                finalUrlAttribute.type = FeedAttributeType.URL_LIST
                finalUrlAttribute.name = "Link Final URLs"

                Dim line2Attribute As New FeedAttribute
                line2Attribute.type = FeedAttributeType.STRING
                line2Attribute.name = "Line 2"

                Dim line3Attribute As New FeedAttribute
                line3Attribute.type = FeedAttributeType.STRING
                line3Attribute.name = "Line 3"

                ' Create the feed.
                Dim sitelinksFeed As New Feed
                sitelinksFeed.name = feedName
                sitelinksFeed.attributes = New FeedAttribute() { _
                                                                   textAttribute, finalUrlAttribute,
                                                                   line2Attribute, line3Attribute}
                sitelinksFeed.origin = FeedOrigin.USER

                ' Create operation.
                Dim operation As New FeedOperation
                operation.operand = sitelinksFeed
                operation.operator = [Operator].ADD

                ' Add the feed.
                Dim result As FeedReturnValue = feedService.mutate(New FeedOperation() {operation})

                Dim savedFeed As Feed = result.value(0)

                sitelinksData.FeedId = savedFeed.id

                Dim savedAttributes As FeedAttribute() = savedFeed.attributes
                sitelinksData.LinkTextFeedAttributeId = savedAttributes(0).id
                sitelinksData.LinkFinalUrlFeedAttributeId = savedAttributes(1).id
                sitelinksData.Line2FeedAttributeId = savedAttributes(2).id
                sitelinksData.Line3FeedAttributeId = savedAttributes(3).id

                Console.WriteLine("Feed with name {0}, ID {1} with linkTextAttributeId {2}, " &
                                  "linkFinalUrlAttributeId {3}, line2AttributeId {4}, " &
                                  "line3AttributeId {5} was created.",
                                  savedFeed.name, savedFeed.id, savedAttributes(0).id,
                                  savedAttributes(1).id,
                                  savedAttributes(2).id, savedAttributes(3).id)
            End Using
        End Sub

        Private Sub CreateSitelinksFeedItems(
                                             ByVal user As AdWordsUser,
                                             ByVal sitelinksData As SitelinksDataHolder)
            Using feedItemService As FeedItemService = CType(
                user.GetService(
                    AdWordsService.v201809.FeedItemService),
                FeedItemService)

                ' Create operations to add FeedItems.
                Dim home As FeedItemOperation =
                        NewSitelinkFeedItemAddOperation(sitelinksData,
                                                        "Home",
                                                        "http://www.example.com",
                                                        "Home line 2",
                                                        "Home line 3")
                Dim stores As FeedItemOperation =
                        NewSitelinkFeedItemAddOperation(sitelinksData,
                                                        "Stores",
                                                        "http://www.example.com/stores",
                                                        "Stores line 2",
                                                        "Stores line 3")
                Dim onSale As FeedItemOperation =
                        NewSitelinkFeedItemAddOperation(sitelinksData,
                                                        "On Sale",
                                                        "http://www.example.com/sale",
                                                        "On Sale line 2",
                                                        "On sale line 3")
                Dim support As FeedItemOperation =
                        NewSitelinkFeedItemAddOperation(sitelinksData,
                                                        "Support",
                                                        "http://www.example.com/support",
                                                        "Support line 2",
                                                        "Support line 3")
                Dim products As FeedItemOperation =
                        NewSitelinkFeedItemAddOperation(sitelinksData,
                                                        "Products",
                                                        "http://www.example.com/prods",
                                                        "Products line 2",
                                                        "Products line 3")

                ' This site link is using geographical targeting to use LOCATION_OF_PRESENCE.
                Dim aboutUs As FeedItemOperation =
                        NewSitelinkFeedItemAddOperation(sitelinksData,
                                                        "About Us",
                                                        "http://www.example.com/about",
                                                        "About Us line 2",
                                                        "About Us line 3",
                                                        True)

                Dim operations As FeedItemOperation() =
                        New FeedItemOperation() {home, stores, onSale, support, products, aboutUs}

                Dim result As FeedItemReturnValue = feedItemService.mutate(operations)

                For Each item As FeedItem In result.value
                    Console.WriteLine("FeedItem with feedItemId {0} was added.", item.feedItemId)
                    sitelinksData.FeedItemIds.Add(item.feedItemId)
                Next

                ' Target the "aboutUs" sitelink to geographically target California.
                RestrictFeedItemToGeoTarget(user, result.value(5), 21137)

            End Using
        End Sub

        ' See the Placeholder reference page for a list of all the placeholder types and fields.
        ' https://developers.google.com/adwords/api/docs/appendix/placeholders.html
        Private Const PLACEHOLDER_SITELINKS As Integer = 1

        ' See the Placeholder reference page for a list of all the placeholder types and fields.
        Private Const PLACEHOLDER_FIELD_SITELINK_LINK_TEXT As Integer = 1

        Private Const PLACEHOLDER_FIELD_SITELINK_FINAL_URL As Integer = 5
        Private Const PLACEHOLDER_FIELD_SITELINK_LINE_2_TEXT As Integer = 3
        Private Const PLACEHOLDER_FIELD_SITELINK_LINE_3_TEXT As Integer = 4

        Private Sub CreateSitelinksFeedMapping(
                                               ByVal user As AdWordsUser,
                                               ByVal sitelinksData As SitelinksDataHolder)
            Using feedMappingService As FeedMappingService = CType(
                user.GetService(
                    AdWordsService.v201809.FeedMappingService),
                FeedMappingService)

                ' Map the FeedAttributeIds to the fieldId constants.
                Dim linkTextFieldMapping As New AttributeFieldMapping
                linkTextFieldMapping.feedAttributeId = sitelinksData.LinkTextFeedAttributeId
                linkTextFieldMapping.fieldId = PLACEHOLDER_FIELD_SITELINK_LINK_TEXT

                Dim linkFinalUrlFieldMapping As New AttributeFieldMapping
                linkFinalUrlFieldMapping.feedAttributeId = sitelinksData.LinkFinalUrlFeedAttributeId
                linkFinalUrlFieldMapping.fieldId = PLACEHOLDER_FIELD_SITELINK_FINAL_URL

                Dim line2FieldMapping As New AttributeFieldMapping
                line2FieldMapping.feedAttributeId = sitelinksData.Line2FeedAttributeId
                line2FieldMapping.fieldId = PLACEHOLDER_FIELD_SITELINK_LINE_2_TEXT

                Dim line3FieldMapping As New AttributeFieldMapping
                line3FieldMapping.feedAttributeId = sitelinksData.Line3FeedAttributeId
                line3FieldMapping.fieldId = PLACEHOLDER_FIELD_SITELINK_LINE_3_TEXT

                ' Create the FieldMapping and operation.
                Dim feedMapping As New FeedMapping
                feedMapping.placeholderType = PLACEHOLDER_SITELINKS
                feedMapping.feedId = sitelinksData.FeedId
                feedMapping.attributeFieldMappings =
                    New AttributeFieldMapping() { _
                                                    linkTextFieldMapping,
                                                    linkFinalUrlFieldMapping,
                                                    line2FieldMapping,
                                                    line3FieldMapping}

                Dim operation As New FeedMappingOperation
                operation.operand = feedMapping
                operation.operator = [Operator].ADD

                ' Save the field mapping.
                Dim result As FeedMappingReturnValue =
                        feedMappingService.mutate(New FeedMappingOperation() {operation})

                For Each savedFeedMapping As FeedMapping In result.value
                    Console.WriteLine(
                        "Feed mapping with ID {0} and placeholderType {1} was saved for " &
                        "feed with ID {2}.", savedFeedMapping.feedMappingId,
                        savedFeedMapping.placeholderType,
                        savedFeedMapping.feedId)
                Next
            End Using
        End Sub

        Private Sub CreateSitelinksCampaignFeed(ByVal user As AdWordsUser,
                                                ByVal sitelinksData As SitelinksDataHolder,
                                                ByVal campaignId As Long)
            Using campaignFeedService As CampaignFeedService = CType(
                user.GetService(
                    AdWordsService.v201809.CampaignFeedService),
                CampaignFeedService)

                ' Construct a matching function that associates the sitelink feeditems to
                ' the campaign, and set the device preference to Mobile. See the matching
                ' function guide at
                ' https://developers.google.com/adwords/api/docs/guides/feed-matching-functions
                ' for more details.
                Dim matchingFunctionString As String = String.Format(
                    "AND(" &
                    "  IN(FEED_ITEM_ID, {{{0}}})," &
                    "  EQUALS(CONTEXT.DEVICE, 'Mobile')" &
                    ")",
                    String.Join(",", sitelinksData.FeedItemIds))

                Dim campaignFeed As New CampaignFeed()
                campaignFeed.feedId = sitelinksData.FeedId
                campaignFeed.campaignId = campaignId
                campaignFeed.matchingFunction = New [Function]()
                campaignFeed.matchingFunction.functionString = matchingFunctionString

                ' Specifying placeholder types on the CampaignFeed allows the same feed
                ' to be used for different placeholders in different Campaigns.
                campaignFeed.placeholderTypes = New Integer() {PLACEHOLDER_SITELINKS}

                Dim operation As New CampaignFeedOperation
                operation.operand = campaignFeed
                operation.operator = [Operator].ADD

                Dim result As CampaignFeedReturnValue =
                        campaignFeedService.mutate(New CampaignFeedOperation() {operation})

                For Each savedCampaignFeed As CampaignFeed In result.value
                    Console.WriteLine("Campaign with ID {0} was associated with feed with ID {1}",
                                      savedCampaignFeed.campaignId, savedCampaignFeed.feedId)
                Next
            End Using
        End Sub

        Function NewSitelinkFeedItemAddOperation(ByVal sitelinksData As SitelinksDataHolder,
                                                 ByVal text As String, ByVal finalUrl As String,
                                                 ByVal line2 As String,
                                                 ByVal line3 As String) As FeedItemOperation
            Return _
                NewSitelinkFeedItemAddOperation(sitelinksData, text, finalUrl, line2, line3, False)
        End Function

        Function NewSitelinkFeedItemAddOperation(ByVal sitelinksData As SitelinksDataHolder,
                                                 ByVal text As String,
                                                 ByVal finalUrl As String,
                                                 ByVal line2 As String,
                                                 ByVal line3 As String,
                                                 ByVal targetLop As Boolean) _
            As FeedItemOperation
            ' Create the FeedItemAttributeValues for our text values.
            Dim linkTextAttributeValue As New FeedItemAttributeValue
            linkTextAttributeValue.feedAttributeId = sitelinksData.LinkTextFeedAttributeId
            linkTextAttributeValue.stringValue = text

            Dim linkFinalUrlAttributeValue As New FeedItemAttributeValue
            linkFinalUrlAttributeValue.feedAttributeId = sitelinksData.LinkFinalUrlFeedAttributeId
            linkFinalUrlAttributeValue.stringValues = New String() {finalUrl}

            Dim line2AttributeValue As New FeedItemAttributeValue
            line2AttributeValue.feedAttributeId = sitelinksData.Line2FeedAttributeId
            line2AttributeValue.stringValue = line2

            Dim line3AttributeValue As New FeedItemAttributeValue
            line3AttributeValue.feedAttributeId = sitelinksData.Line3FeedAttributeId
            line3AttributeValue.stringValue = line3

            ' Create the feed item and operation.
            Dim item As New FeedItem
            item.feedId = sitelinksData.FeedId

            ' OPTIONAL: Restrict targeting only to people physically within the location.
            If targetLop Then
                Dim geoTargetingRestriction As New FeedItemGeoRestriction()
                geoTargetingRestriction.geoRestriction = GeoRestriction.LOCATION_OF_PRESENCE
                item.geoTargetingRestriction = geoTargetingRestriction
            End If

            item.attributeValues = New FeedItemAttributeValue() { _
                                                                    linkTextAttributeValue,
                                                                    linkFinalUrlAttributeValue,
                                                                    line2AttributeValue,
                                                                    line3AttributeValue}

            Dim operation As New FeedItemOperation
            operation.operand = item
            operation.operator = [Operator].ADD
            Return operation
        End Function
    End Class
End Namespace

フィードバックを送信...

ご不明な点がありましたら、Google のサポートページをご覧ください。