Extensions Samples

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

Add Google My Business location extensions

' Copyright 2017, Google Inc. All Rights Reserved.
'
' 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.v201705
Imports Google.Api.Ads.Common.Lib

Imports System
Imports System.Collections.Generic
Imports System.IO

Namespace Google.Api.Ads.AdWords.Examples.VB.v201705
  ''' <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.OAuthProvider.AccessToken

        ' 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)
      ' Get the FeedService.
      Dim feedService As FeedService = CType(user.GetService( _
          AdWordsService.v201705.FeedService), FeedService)

      ' Get the CustomerFeedService.
      Dim customerFeedService As CustomerFeedService = CType(user.GetService( _
          AdWordsService.v201705.CustomerFeedService), CustomerFeedService)

      ' 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)

        ' Add a CustomerFeed that associates the feed with this customer for
        ' the LOCATION placeholder type.
        Dim customerFeed As New CustomerFeed()
        customerFeed.feedId = addedFeed.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)
        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 Sub
  End Class

End Namespace

Add prices

' Copyright 2017, Google Inc. All Rights Reserved.
'
' 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.v201705

Imports System
Imports System.Collections.Generic
Imports System.IO

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201705

  ''' <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)
      ' Get the CustomerExtensionSettingService.
      Dim customerExtensionSettingService As CustomerExtensionSettingService = _
          DirectCast(user.GetService(AdWordsService.v201705.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 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 2017, Google Inc. All Rights Reserved.
'
' 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.v201705

Imports System
Imports System.Collections.Generic
Imports System.IO

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201705

  ''' <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)
      ' Get the CampaignExtensionSettingService.
      Dim campaignExtensionSettingService As CampaignExtensionSettingService = _
          DirectCast(user.GetService(AdWordsService.v201705.CampaignExtensionSettingService),  _
                                    CampaignExtensionSettingService)

      Dim customerService As CustomerService = _
          DirectCast(user.GetService(AdWordsService.v201705.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 Sub
  End Class

End Namespace

Add sitelinks to a campaign using feeds

' Copyright 2017, Google Inc. All Rights Reserved.
'
' 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.v201705

Imports System
Imports System.Collections.Generic
Imports System.IO

Namespace Google.Api.Ads.AdWords.Examples.VB.v201705

  ''' <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 feedName As String = "INSERT_FEED_NAME_HERE"
        codeExample.Run(New AdWordsUser, campaignId, feedName)
      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="feedName">Name of the feed.</param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long, ByVal feedName As String)
      Dim siteLinksData As New SitelinksDataHolder
      createSitelinksFeed(user, siteLinksData, feedName)
      createSitelinksFeedItems(user, siteLinksData)
      createSitelinksFeedMapping(user, siteLinksData)
      createSitelinksCampaignFeed(user, siteLinksData, campaignId)
    End Sub

    Private Sub createSitelinksFeed( _
      ByVal user As AdWordsUser, ByVal sitelinksData As SitelinksDataHolder, _
      ByVal feedName As String)
      ' Get the FeedService.
      Dim feedService As FeedService = CType(user.GetService( _
          AdWordsService.v201705.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 Sub

    Private Sub createSitelinksFeedItems( _
        ByVal user As AdWordsUser, ByVal sitelinksData As SitelinksDataHolder)
      ' Get the FeedItemService.
      Dim feedItemService As FeedItemService = CType(user.GetService( _
          AdWordsService.v201705.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 by specifying the
      ' criterion ID for California.
      Dim aboutUs As FeedItemOperation = newSitelinkFeedItemAddOperation(sitelinksData, _
          "About Us", "http://www.example.com/about", "About Us line 2", "About Us line 3", 21137)

      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
    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)
      ' Get the FeedItemService.
      Dim feedMappingService As FeedMappingService = CType(user.GetService( _
          AdWordsService.v201705.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 Sub

    Private Sub createSitelinksCampaignFeed(ByVal user As AdWordsUser, _
      ByVal sitelinksData As SitelinksDataHolder, ByVal campaignId As Long)
      ' Get the CampaignFeedService.
      Dim campaignFeedService As CampaignFeedService = CType(user.GetService( _
          AdWordsService.v201705.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 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, Nothing)
    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 locationId As Nullable(Of Long)) _
        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: Use geographical targeting on a feed item.
      ' The IDs can be found in the documentation or retrieved with the
      ' LocationCriterionService.

      If locationId.HasValue Then
        item.geoTargeting = New Location()
        item.geoTargeting.id = locationId.Value

        ' OPTIONAL: Restrict targeting only to people physically within the location.
        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

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.