Advanced Operations Samples

The code samples below provide examples of common advanced operations using the AdWords API. Client Library.

Add an ad customizer

' 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

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

  ''' <summary>
  ''' This code example adds an ad customizer feed. Then it adds an ad in two
  ''' different adgroups that uses the feed to populate dynamic data.
  ''' </summary>
  Public Class AddAdCustomizers
    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 AddAdCustomizers
      Console.WriteLine(codeExample.Description)
      Try
        Dim adGroupId1 As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
        Dim adGroupId2 As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
        Dim feedName As String = "INSERT_FEED_NAME_HERE"
        codeExample.Run(New AdWordsUser(), adGroupId1, adGroupId2, 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 an ad customizer feed. Then it adds an ad in two " & _
            "different adgroups that uses the feed to populate dynamic data."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="adGroupId1">Id of the first adgroup to which ads with ad
    ''' customizers are added.</param>
    ''' <param name="adGroupId2">Id of the second adgroup to which ads with ad
    ''' customizers are added.</param>
    ''' <param name="feedName">Name of the feed to be created.</param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId1 As Long, ByVal adGroupId2 As Long, _
                   ByVal feedName As String)
      ' Create a customizer feed. One feed per account can be used for all ads.
      Dim adCustomizerFeed As AdCustomizerFeed = CreateCustomizerFeed(user, feedName)

      ' Add feed items containing the values we'd like to place in ads.
      CreateCustomizerFeedItems(user, New Long() {adGroupId1, adGroupId2}, adCustomizerFeed)

      ' All set! We can now create ads with customizations.
      CreateAdsWithCustomizations(user, New Long() {adGroupId1, adGroupId2}, feedName)
    End Sub

    ''' <summary>
    ''' Creates a new Feed for ad customizers.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="feedName">Name of the feed to be created.</param>
    ''' <returns>An ad customizer feed.</returns>
    Private Shared Function CreateCustomizerFeed(ByVal user As AdWordsUser, _
        ByVal feedName As String) As AdCustomizerFeed
      Dim adCustomizerFeedService As AdCustomizerFeedService = DirectCast(user.GetService( _
          AdWordsService.v201705.AdCustomizerFeedService), AdCustomizerFeedService)

      Dim feed As New AdCustomizerFeed()
      feed.feedName = feedName

      Dim attribute1 As New AdCustomizerFeedAttribute
      attribute1.name = "Name"
      attribute1.type = AdCustomizerFeedAttributeType.STRING

      Dim attribute2 As New AdCustomizerFeedAttribute
      attribute2.name = "Price"
      attribute2.type = AdCustomizerFeedAttributeType.PRICE

      Dim attribute3 As New AdCustomizerFeedAttribute
      attribute3.name = "Date"
      attribute3.type = AdCustomizerFeedAttributeType.DATE_TIME

      feed.feedAttributes = New AdCustomizerFeedAttribute() { _
        attribute1, attribute2, attribute3 _
      }

      Dim feedOperation As New AdCustomizerFeedOperation()
      feedOperation.operand = feed
      feedOperation.operator = [Operator].ADD

      Dim addedFeed As AdCustomizerFeed = adCustomizerFeedService.mutate( _
          New AdCustomizerFeedOperation() {feedOperation}).value(0)

      Console.WriteLine("Created ad customizer feed with ID = {0} and name = '{1}'.", _
                        addedFeed.feedId, addedFeed.feedName)
      Return addedFeed
    End Function

    ''' <summary>
    ''' Creates FeedItems with the values to use in ad customizations for each
    ''' ad group in <code>adGroupIds</code>.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="adGroupIds">IDs of adgroups to which ad customizations are
    ''' made.</param>
    ''' <param name="adCustomizerFeed">The ad customizer feed.</param>
    Private Shared Sub CreateCustomizerFeedItems(ByVal user As AdWordsUser, _
                                                 ByVal adGroupIds As Long(), _
                                                 ByVal adCustomizerFeed As AdCustomizerFeed)
      ' Get the FeedItemService.
      Dim feedItemService As FeedItemService = CType(user.GetService( _
          AdWordsService.v201705.FeedItemService), FeedItemService)

      Dim feedItemOperations As New List(Of FeedItemOperation)

      Dim marsDate As New DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)
      feedItemOperations.Add(CreateFeedItemAddOperation(adCustomizerFeed, "Mars", "$1234.56",
          marsDate.ToString("yyyyMMdd HHmmss"), adGroupIds(0)))

      Dim venusDate As New DateTime(DateTime.Now.Year, DateTime.Now.Month, 15)
      feedItemOperations.Add(CreateFeedItemAddOperation(adCustomizerFeed, "Venus", "$1450.00",
          venusDate.ToString("yyyyMMdd HHmmss"), adGroupIds(1)))
      Dim feedItemReturnValue As FeedItemReturnValue = feedItemService.mutate( _
          feedItemOperations.ToArray)

      For Each addedFeedItem As FeedItem In feedItemReturnValue.value
        Console.WriteLine("Added feed item with ID {0}", addedFeedItem.feedItemId)
      Next
    End Sub

    ''' <summary>
    ''' Creates a FeedItemOperation that will create a FeedItem with the
    ''' specified values and ad group target when sent to
    ''' FeedItemService.mutate.
    ''' </summary>
    ''' <param name="adCustomizerFeed">The ad customizer feed.</param>
    ''' <param name="nameValue">The value for the name attribute of the
    ''' FeedItem.</param>
    ''' <param name="priceValue">The value for the price attribute of the
    ''' FeedItem.</param>
    ''' <param name="dateValue">The value for the date attribute of the
    ''' FeedItem.</param>
    ''' <param name="adGroupId">The ID of the ad group to target with the
    ''' FeedItem.</param>
    ''' <returns>A new FeedItemOperation for adding a FeedItem.</returns>
    Private Shared Function CreateFeedItemAddOperation(ByVal adCustomizerFeed As  _
        AdCustomizerFeed, ByVal nameValue As String, ByVal priceValue As String, _
        ByVal dateValue As String, ByVal adGroupId As Long) As FeedItemOperation
      Dim feedItem As New FeedItem
      feedItem.feedId = adCustomizerFeed.feedId
      Dim attributeValues As New List(Of FeedItemAttributeValue)

      ' FeedAttributes appear in the same order as they were created
      ' - Name, Price, Date. See CreateCustomizerFeed method for details.
      Dim nameAttributeValue As New FeedItemAttributeValue
      nameAttributeValue.feedAttributeId = adCustomizerFeed.feedAttributes(0).id
      nameAttributeValue.stringValue = nameValue
      attributeValues.Add(nameAttributeValue)

      Dim priceAttributeValue As New FeedItemAttributeValue
      priceAttributeValue.feedAttributeId = adCustomizerFeed.feedAttributes(1).id
      priceAttributeValue.stringValue = priceValue
      attributeValues.Add(priceAttributeValue)

      Dim dateAttributeValue As New FeedItemAttributeValue
      dateAttributeValue.feedAttributeId = adCustomizerFeed.feedAttributes(2).id
      dateAttributeValue.stringValue = dateValue
      attributeValues.Add(dateAttributeValue)

      feedItem.attributeValues = attributeValues.ToArray

      feedItem.adGroupTargeting = New FeedItemAdGroupTargeting
      feedItem.adGroupTargeting.TargetingAdGroupId = adGroupId

      Dim feedItemOperation As New FeedItemOperation
      feedItemOperation.operand = feedItem
      feedItemOperation.operator = [Operator].ADD

      Return feedItemOperation
    End Function

    ''' <summary>
    ''' Creates text ads that use ad customizations for the specified ad group
    ''' IDs.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="adGroupIds">IDs of the ad groups to which customized ads
    ''' are added.</param>
    ''' <param name="feedName">Name of the feed to use.</param>
    Private Shared Sub CreateAdsWithCustomizations(ByVal user As AdWordsUser, _
                                                   ByVal adGroupIds As Long(), _
                                                   ByVal feedName As String)
      ' Get the AdGroupAdService.
      Dim adGroupAdService As AdGroupAdService = CType(user.GetService( _
          AdWordsService.v201705.AdGroupAdService), AdGroupAdService)

      Dim expandedTextAd As New ExpandedTextAd
      expandedTextAd.headlinePart1 = String.Format("Luxury Cruise to {{={0}.Name}}", feedName)
      expandedTextAd.headlinePart2 = String.Format("Only {{={0}.Price}}", feedName)
      expandedTextAd.description = String.Format("Offer ends in {{=countdown({0}.Date)}}!", _
                                                 feedName)
      expandedTextAd.finalUrls = New String() {"http://www.example.com"}

      ' We add the same ad to both ad groups. When they serve, they will show
      ' different values, since they match different feed items.
      Dim adGroupAdOperations As New List(Of AdGroupAdOperation)
      For Each adGroupId As Long In adGroupIds
        Dim adGroupAd As New AdGroupAd
        adGroupAd.adGroupId = adGroupId
        adGroupAd.ad = expandedTextAd

        Dim adGroupAdOperation As New AdGroupAdOperation
        adGroupAdOperation.operand = adGroupAd
        adGroupAdOperation.operator = [Operator].ADD

        adGroupAdOperations.Add(adGroupAdOperation)
      Next

      Dim adGroupAdReturnValue As AdGroupAdReturnValue = adGroupAdService.mutate( _
          adGroupAdOperations.ToArray)

      For Each addedAd As AdGroupAd In adGroupAdReturnValue.value
        Console.WriteLine("Created an ad with ID {0}, type '{1}' and status '{2}'.", _
            addedAd.ad.id, addedAd.ad.AdType, addedAd.status)
      Next
    End Sub
  End Class
End Namespace

Add an ad group bid modifier

' 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>
  ''' This code example illustrates how to add ad group level mobile bid
  ''' modifier override.
  ''' </summary>
  Public Class AddAdGroupBidModifier
    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 AddAdGroupBidModifier
      Console.WriteLine(codeExample.Description)
      Try
        Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
        Dim bidModifier As Double = Double.Parse("INSERT_ADGROUP_BID_MODIFIER_HERE")
        codeExample.Run(New AdWordsUser, adGroupId, bidModifier)
      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 illustrates how to add ad group level mobile bid" & _
            " modifier override."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="adGroupId">Id of the adgroup for which bid modifier is
    ''' set.</param>
    ''' <param name="bidModifier">The mobile bid modifier for adgroup</param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long, ByVal bidModifier As Double)
      ' Get the AdGroupBidModifierService.
      Dim adGroupBidModifierService As AdGroupBidModifierService = CType(user.GetService( _
          AdWordsService.v201705.AdGroupBidModifierService), 
              AdGroupBidModifierService)

      ' Mobile criterion ID.
      Dim criterionId As Long = 30001

      ' Create the adgroup bid modifier.
      Dim adGroupBidModifier As New AdGroupBidModifier()
      adGroupBidModifier.bidModifier = bidModifier
      adGroupBidModifier.adGroupId = adGroupId

      Dim platform As New Platform()
      platform.id = criterionId

      adGroupBidModifier.criterion = platform

      Dim operation As New AdGroupBidModifierOperation()
      operation.operator = [Operator].ADD
      operation.operand = adGroupBidModifier

      Try
        ' Add ad group level mobile bid modifier.
        Dim retval As AdGroupBidModifierReturnValue = adGroupBidModifierService.mutate( _
            New AdGroupBidModifierOperation() {operation})

        ' Display the results.
        If Not retval Is Nothing AndAlso Not retval.value Is Nothing AndAlso _
            retval.value.Length > 0 Then
          Dim newBidModifier As AdGroupBidModifier = retval.value(0)
          Console.WriteLine("AdGroup ID {0}, Criterion ID {1} was updated with ad group " & _
              "level modifier: {2}", newBidModifier.adGroupId, newBidModifier.criterion.id, _
              newBidModifier.bidModifier)
        Else
          Console.WriteLine("No bid modifiers were added to the adgroup.")
        End If
      Catch e As Exception
        Throw New System.ApplicationException("Failed to add bid modifiers to adgroup.", e)
      End Try
    End Sub
  End Class

End Namespace

Add a click-to-download ad

' 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.Util

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201705
  ''' <summary>
  ''' This code example creates a click-to-download ad, also known as an
  ''' app promotion ad to a given ad group. To list ad groups, run
  ''' GetAdGroups.vb.
  ''' </summary>
  Public Class AddClickToDownloadAd
    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 AddClickToDownloadAd
      Console.WriteLine(codeExample.Description)
      Try
        Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
        codeExample.Run(New AdWordsUser, 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 creates a click-to-download ad, also known as an app " & _
            "promotion ad to a given ad group. To list ad groups, run GetAdGroups.vb."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="adGroupId">Id of the ad group to which ads are added.
    ''' </param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long)
      ' Get the AdGroupAdService.
      Dim adGroupAdService As AdGroupAdService = CType(user.GetService( _
          AdWordsService.v201705.AdGroupAdService), AdGroupAdService)

      ' Create the template ad.
      Dim clickToDownloadAppAd As New TemplateAd()

      clickToDownloadAppAd.name = "Ad for demo game"
      clickToDownloadAppAd.templateId = 353
      clickToDownloadAppAd.finalUrls = New String() { _
          "http://play.google.com/store/apps/details?id=com.example.demogame" _
      }
      clickToDownloadAppAd.displayUrl = "play.google.com"

      ' Create the template elements for the ad. You can refer to
      ' https://developers.google.com/adwords/api/docs/appendix/templateads
      ' for the list of avaliable template fields.
      Dim headline As New TemplateElementField()
      headline.name = "headline"
      headline.fieldText = "Enjoy your drive in Mars"
      headline.type = TemplateElementFieldType.TEXT

      Dim description1 As New TemplateElementField()
      description1.name = "description1"
      description1.fieldText = "Realistic physics simulation"
      description1.type = TemplateElementFieldType.TEXT

      Dim description2 As New TemplateElementField()
      description2.name = "description2"
      description2.fieldText = "Race against players online"
      description2.type = TemplateElementFieldType.TEXT

      Dim appId As New TemplateElementField()
      appId.name = "appId"
      appId.fieldText = "com.example.demogame"
      appId.type = TemplateElementFieldType.TEXT

      Dim appStore As New TemplateElementField()
      appStore.name = "appStore"
      appStore.fieldText = "2"
      appStore.type = TemplateElementFieldType.ENUM

      ' Optionally specify a landscape image. The image needs to be in a BASE64
      ' encoded form. Here we download a demo image and encode it for this ad.
      Dim imageData As Byte() = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/9JmyKk")
      Dim fieldMediaImage As New Image()
      fieldMediaImage.data = imageData
      Dim landscapeImage As New TemplateElementField()
      landscapeImage.name = "landscapeImage"
      landscapeImage.fieldMedia = fieldMediaImage
      landscapeImage.type = TemplateElementFieldType.IMAGE

      Dim adData As New TemplateElement()
      adData.uniqueName = "adData"
      adData.fields = New TemplateElementField() {headline, description1, description2, appId, _
          appStore, landscapeImage}

      clickToDownloadAppAd.templateElements = New TemplateElement() {adData}

      ' Create the adgroupad.
      Dim clickToDownloadAppAdGroupAd As New AdGroupAd()
      clickToDownloadAppAdGroupAd.adGroupId = adGroupId
      clickToDownloadAppAdGroupAd.ad = clickToDownloadAppAd

      ' Optional: Set the status.
      clickToDownloadAppAdGroupAd.status = AdGroupAdStatus.PAUSED

      ' Create the operation.
      Dim operation As New AdGroupAdOperation()
      operation.operator = [Operator].ADD
      operation.operand = clickToDownloadAppAdGroupAd

      Try
        ' Create the ads.
        Dim retval As AdGroupAdReturnValue = adGroupAdService.mutate(New AdGroupAdOperation() _
                                                                     {operation})

        ' Display the results.
        If Not retval Is Nothing AndAlso Not retval.value Is Nothing Then
          For Each adGroupAd As AdGroupAd In retval.value
            Console.WriteLine("New click-to-download ad with id = '{0}' and url = '{1}' " & _
                "was created.", adGroupAd.ad.id, adGroupAd.ad.finalUrls(0))
          Next
        Else
          Console.WriteLine("No click-to-download ads were created.")
        End If
      Catch e As Exception
        Throw New System.ApplicationException("Failed to create click-to-download ad.", e)
      End Try
    End Sub
  End Class

End Namespace

Add a page feed specifying URLs for a DSA 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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201705
  ''' <summary>
  ''' This code example adds a page feed to specify precisely which URLs to use with your
  ''' Dynamic Search Ads campaign. To create a Dynamic Search Ads campaign, run
  ''' AddDynamicSearchAdsCampaign.vb. To get campaigns, run GetCampaigns.vb.
  ''' </summary>
  Public Class AddDynamicPageFeed
    Inherits ExampleBase

    ''' <summary>
    ''' The criterion type to be used for DSA page feeds.
    ''' </summary>
    ''' <remarks>DSA page feeds use criterionType field instead of the placeholderType field unlike
    ''' most other feed types.</remarks>
    Private Const DSA_PAGE_FEED_CRITERION_TYPE As Integer = 61

    ''' <summary>
    ''' ID that corresponds to the page URLs.
    ''' </summary>
    Private Const DSA_PAGE_URLS_FIELD_ID As Integer = 1

    ''' <summary>
    ''' ID that corresponds to the labels.
    ''' </summary>
    Private Const DSA_LABEL_FIELD_ID As Integer = 2

    ''' <summary>
    ''' Class to keep track of DSA page feed details.
    ''' </summary>
    Private Class DSAFeedDetails
      Dim feedIdField As Long
      Dim urlAttributeIdField As Long
      Dim labelAttributeIdField As Long

      Public Property FeedId As Long
        Get
          Return feedIdField
        End Get
        Set(ByVal value As Long)
          feedIdField = value
        End Set
      End Property

      Public Property UrlAttributeId As Long
        Get
          Return urlAttributeIdField
        End Get
        Set(ByVal value As Long)
          urlAttributeIdField = value
        End Set
      End Property

      Public Property LabelAttributeId As Long
        Get
          Return labelAttributeIdField
        End Get
        Set(ByVal value As Long)
          labelAttributeIdField = value
        End Set
      End Property
    End Class

    ''' <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 AddDynamicSearchAdsCampaign
      Console.WriteLine(codeExample.Description)
      Try
        codeExample.Run(New AdWordsUser)
      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 page feed to specify precisely which URLs to use " +
            "with your Dynamic Search Ads campaign. To create a Dynamic Search Ads campaign, " +
            "run AddDynamicSearchAdsCampaign.vb. To get campaigns, run GetCampaigns.vb."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long, ByVal adgroupId As Long)
      Dim dsaPageUrlLabel As String = "discounts"

      ' Get the page feed details. This code example creates a new feed, but you can
      ' fetch and re-use an existing feed.
      Dim feedDetails As DSAFeedDetails = CreateFeed(user)
      CreateFeedMapping(user, feedDetails)
      CreateFeedItems(user, feedDetails, dsaPageUrlLabel)

      ' Associate the page feed with the campaign.
      UpdateCampaignDsaSetting(user, campaignId, feedDetails.feedId)

      ' Optional: Target Web pages matching the feed's label in the ad group.
      AddDsaTargeting(user, adGroupId, dsaPageUrlLabel)

      Console.WriteLine("Dynamic page feed setup is complete for campaign ID '{0}'.", campaignId)
    End Sub

    ''' <summary>
    ''' Creates the feed for DSA page URLs.
    ''' </summary>
    ''' <param name="user">The AdWords User.</param>
    ''' <returns>The feed details.</returns>
    Private Function CreateFeed(ByVal user As AdWordsUser) As DSAFeedDetails
      ' Get the FeedService.
      Dim feedService As FeedService = CType(user.GetService(
          AdWordsService.v201705.FeedService), FeedService)

      ' Create attributes.
      Dim urlAttribute As New FeedAttribute()
      urlAttribute.type = FeedAttributeType.URL_LIST
      urlAttribute.name = "Page URL"

      Dim labelAttribute As New FeedAttribute()
      labelAttribute.type = FeedAttributeType.STRING_LIST
      labelAttribute.name = "Label"

      ' Create the feed.
      Dim sitelinksFeed As New Feed()
      sitelinksFeed.name = "DSA Feed " + ExampleUtilities.GetRandomString()
      sitelinksFeed.attributes = New FeedAttribute() {urlAttribute, labelAttribute}
      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)

      Dim retval As New DSAFeedDetails
      retval.FeedId = savedFeed.id
      retval.UrlAttributeId = savedFeed.attributes(0).id
      retval.LabelAttributeId = savedFeed.attributes(1).id
      Return retval
    End Function

    ''' <summary>
    ''' Creates the feed mapping for DSA page feeds.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="feedDetails">The feed details.</param>
    Private Sub CreateFeedMapping(ByVal user As AdWordsUser, ByVal feedDetails As DSAFeedDetails)
      ' Get the FeedMappingService.
      Dim feedMappingService As FeedMappingService = CType(user.GetService(
          AdWordsService.v201705.FeedMappingService), FeedMappingService)

      ' Map the FeedAttributeIds to the fieldId constants.
      Dim urlFieldMapping As New AttributeFieldMapping()
      urlFieldMapping.feedAttributeId = feedDetails.UrlAttributeId
      urlFieldMapping.fieldId = DSA_PAGE_URLS_FIELD_ID

      Dim labelFieldMapping As New AttributeFieldMapping()
      labelFieldMapping.feedAttributeId = feedDetails.LabelAttributeId
      labelFieldMapping.fieldId = DSA_LABEL_FIELD_ID

      ' Create the fieldMapping and operation.
      Dim feedMapping As New FeedMapping()
      feedMapping.criterionType = DSA_PAGE_FEED_CRITERION_TYPE
      feedMapping.feedId = feedDetails.FeedId
      feedMapping.attributeFieldMappings = New AttributeFieldMapping() {
        urlFieldMapping, labelFieldMapping
      }

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

      ' Add the field mapping.
      feedMappingService.mutate(New FeedMappingOperation() {operation})
      Return
    End Sub

    ''' <summary>
    ''' Creates the page URLs in the DSA page feed.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="feedDetails">The feed details.</param>
    ''' <param name="labelName">The pagefeed url label.</param>
    Private Sub CreateFeedItems(ByVal user As AdWordsUser, ByVal feedDetails As DSAFeedDetails,
        ByVal labelName As String)
      ' Get the FeedItemService.
      Dim feedItemService As FeedItemService = CType(user.GetService(
          AdWordsService.v201705.FeedItemService), FeedItemService)

      Dim operations() As FeedItemOperation = {
        CreateDsaUrlAddOperation(feedDetails, "http://www.example.com/discounts/rental-cars",
            labelName),
        CreateDsaUrlAddOperation(feedDetails, "http://www.example.com/discounts/hotel-deals",
            labelName),
        CreateDsaUrlAddOperation(feedDetails, "http://www.example.com/discounts/flight-deals",
            labelName)
      }
      feedItemService.mutate(operations)
    End Sub

    ''' <summary>
    ''' Creates the DSA URL add operation.
    ''' </summary>
    ''' <param name="feedDetails">The page feed details.</param>
    ''' <param name="url">The DSA page feed URL.</param>
    ''' <param name="label">DSA page feed label.</param>
    ''' <returns>The DSA URL add operation.</returns>
    Private Function CreateDsaUrlAddOperation(ByVal feedDetails As DSAFeedDetails,
        ByVal url As String, ByVal label As String) As FeedItemOperation
      ' Create the FeedItemAttributeValues for our text values.
      Dim urlAttributeValue As New FeedItemAttributeValue()
      urlAttributeValue.feedAttributeId = feedDetails.UrlAttributeId

      ' Optional: Add the {feeditem} valuetrack parameter to track which page feed items lead
      ' to each click.
      url = url + "?id={feeditem}"
      urlAttributeValue.stringValues = New String() {url}

      Dim labelAttributeValue As New FeedItemAttributeValue()
      labelAttributeValue.feedAttributeId = feedDetails.LabelAttributeId
      labelAttributeValue.stringValues = New String() {label}

      ' Create the feed item and operation.
      Dim item As New FeedItem()
      item.feedId = feedDetails.FeedId

      item.attributeValues = New FeedItemAttributeValue() {
        urlAttributeValue, labelAttributeValue
      }

      Dim operation As New FeedItemOperation()
      operation.operand = item
      operation.operator = [Operator].ADD

      Return operation
    End Function

    ''' <summary>
    ''' Updates the campaign DSA setting to add DSA pagefeeds.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="campaignId">The Campaign ID.</param>
    ''' <param name="feedId">The page feed ID.</param>
    Private Sub UpdateCampaignDsaSetting(ByVal user As AdWordsUser, ByVal campaignId As Long,
        ByVal feedId As Long)
      ' Get the CampaignService.
      Dim campaignService As CampaignService = CType(user.GetService(
          AdWordsService.v201705.CampaignService), CampaignService)

      Dim selector As New Selector()
      selector.fields = New String() {Campaign.Fields.Id, Campaign.Fields.Settings}
      selector.predicates = New Predicate() {
          Predicate.Equals(Campaign.Fields.Id, campaignId)
      }
      selector.paging = Paging.Default

      Dim page As CampaignPage = campaignService.get(selector)

      If page Is Nothing Or page.entries Is Nothing Or page.entries.Length = 0 Then
        Throw New System.ApplicationException(String.Format(
            "Failed to retrieve campaign with ID = {0}.", campaignId))
      End If

      Dim selectedCampaign As Campaign = page.entries(0)

      If selectedCampaign.settings Is Nothing Then
        Throw New System.ApplicationException("This is not a DSA campaign.")
      End If

      Dim dsaSetting As DynamicSearchAdsSetting = Nothing
      Dim campaignSettings() As Setting = selectedCampaign.settings

      For i As Integer = 0 To selectedCampaign.settings.Length - 1
        Dim setting As Setting = campaignSettings(i)
        If TypeOf setting Is DynamicSearchAdsSetting Then
          dsaSetting = CType(setting, DynamicSearchAdsSetting)
          Exit For
        End If
      Next

      If dsaSetting Is Nothing Then
        Throw New System.ApplicationException("This is not a DSA campaign.")
      End If

      ' Use a page feed to specify precisely which URLs to use with your
      ' Dynamic Search Ads.
      dsaSetting.pageFeed = New PageFeed()
      dsaSetting.pageFeed.feedIds = New Long() {
        feedId
      }

      ' Optional: Specify whether only the supplied URLs should be used with your
      ' Dynamic Search Ads.
      dsaSetting.useSuppliedUrlsOnly = True

      Dim campaignToUpdate As New Campaign()
      campaignToUpdate.id = campaignId
      campaignToUpdate.settings = campaignSettings

      Dim operation As New CampaignOperation()
      operation.operand = campaignToUpdate
      operation.operator = [Operator].SET

      Try
        Dim retval As CampaignReturnValue = campaignService.mutate(
            New CampaignOperation() {operation})
        Console.WriteLine("DSA page feed for campaign ID '{0}' was updated with feed ID '{1}'.",
            campaignToUpdate.id, feedId)
      Catch e As Exception
        Throw New System.ApplicationException("Failed to set page feed for campaign.", e)
      End Try
    End Sub

    ''' <summary>
    ''' Set custom targeting for the page feed URLs based on a list of labels.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="adGroupId">Ad group ID.</param>
    ''' <param name="labelName">The label name.</param>
    ''' <returns>The newly created webpage criterion.</returns>
    Private Function AddDsaTargeting(ByVal user As AdWordsUser, ByVal adgroupId As Long,
        ByVal labelName As String) As BiddableAdGroupCriterion
      ' Get the AdGroupCriterionService.
      Dim adGroupCriterionService As AdGroupCriterionService = CType(user.GetService(
          AdWordsService.v201705.AdGroupCriterionService), AdGroupCriterionService)

      ' Create a webpage criterion.
      Dim webpage As New Webpage()

      Dim parameter As New WebpageParameter()
      parameter.criterionName = "Test criterion"
      webpage.parameter = parameter

      ' Add a condition for label=specified_label_name.
      Dim condition As New WebpageCondition()
      condition.operand = WebpageConditionOperand.CUSTOM_LABEL
      condition.argument = labelName
      parameter.conditions = New WebpageCondition() {condition}

      Dim criterion As New BiddableAdGroupCriterion()
      criterion.adGroupId = adgroupId
      criterion.criterion = webpage

      ' Set a custom bid for this criterion.
      Dim biddingStrategyConfiguration As New BiddingStrategyConfiguration()

      Dim cpcBid As New CpcBid
      cpcBid.bid = New Money()
      cpcBid.bid.microAmount = 1500000

      biddingStrategyConfiguration.bids = New Bids() {cpcBid}

      criterion.biddingStrategyConfiguration = biddingStrategyConfiguration

      Dim operation As New AdGroupCriterionOperation()
      operation.operand = criterion
      operation.operator = [Operator].ADD

      Try
        Dim retval As AdGroupCriterionReturnValue = adGroupCriterionService.mutate(
            New AdGroupCriterionOperation() {operation})
        Dim newCriterion As BiddableAdGroupCriterion =
            CType(retval.value(0), BiddableAdGroupCriterion)

        Console.WriteLine("Web page criterion with ID = {0} and status = {1} was created.",
          newCriterion.criterion.id, newCriterion.userStatus)

        Return newCriterion
      Catch e As Exception
        Throw New System.ApplicationException("Failed to create webpage criterion for " +
            "custom page feed label.", e)
      End Try
    End Function
  End Class
End Namespace

Add a DSA 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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201705
  ''' <summary>
  ''' This code example adds a Dynamic Search Ads campaign. To get campaigns, run GetCampaigns.vb.
  ''' </summary>
  Public Class AddDynamicSearchAdsCampaign
    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 AddDynamicSearchAdsCampaign
      Console.WriteLine(codeExample.Description)
      Try
        codeExample.Run(New AdWordsUser)
      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 Dynamic Search Ads campaign. To get campaigns, " +
            "run GetCampaigns.vb."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    Public Sub Run(ByVal user As AdWordsUser)
      Dim budget As Budget = CreateBudget(user)
      Dim campaign As Campaign = CreateCampaign(user, budget)
      Dim adGroup As AdGroup = CreateAdGroup(user, campaign.id)
      Dim expandedDSA As ExpandedDynamicSearchAd = CreateExpandedDSA(user, adGroup.id)
      Console.WriteLine("Dynamic Search Ads campaign setup is complete.")
    End Sub

    ''' <summary>
    ''' Creates the budget.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <returns>The newly created budget.</returns>
    Private Function CreateBudget(ByVal user As AdWordsUser) As Budget
      ' Get the BudgetService.
      Dim budgetService As BudgetService = CType(user.GetService(
          AdWordsService.v201705.BudgetService), BudgetService)

      ' Create the campaign budget.
      Dim budget As New Budget()
      budget.name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString()
      budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD
      budget.amount = New Money()
      budget.amount.microAmount = 500000

      Dim budgetOperation As New BudgetOperation()
      budgetOperation.operator = [Operator].ADD
      budgetOperation.operand = budget

      Try
        Dim budgetRetval As BudgetReturnValue = budgetService.mutate(
            New BudgetOperation() {budgetOperation})
        Dim newBudget As Budget = budgetRetval.value(0)
        Console.WriteLine("Budget with ID = '{0}' and name = '{1}' was created.",
            newBudget.budgetId, newBudget.name)
        Return newBudget
      Catch e As Exception
        Throw New System.ApplicationException("Failed to add budget.", e)
      End Try
    End Function

    ''' <summary>
    ''' Creates the campaign.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="budget">The campaign budget.</param>
    ''' <returns>The newly created campaign.</returns>
    Private Function CreateCampaign(ByVal user As AdWordsUser, ByVal budget As Budget) As Campaign
      ' Get the CampaignService.
      Dim campaignService As CampaignService = CType(user.GetService(
          AdWordsService.v201705.CampaignService), CampaignService)

      ' Create a Dynamic Search Ads campaign.
      Dim campaign As New Campaign()
      campaign.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString()
      campaign.advertisingChannelType = AdvertisingChannelType.SEARCH

      ' Recommendation: Set the campaign to PAUSED when creating it to prevent
      ' the ads from immediately serving. Set to ENABLED once you've added
      ' targeting and the ads are ready to serve.
      campaign.status = CampaignStatus.PAUSED

      Dim biddingConfig As New BiddingStrategyConfiguration()
      biddingConfig.biddingStrategyType = BiddingStrategyType.MANUAL_CPC
      campaign.biddingStrategyConfiguration = biddingConfig

      campaign.budget = New Budget()
      campaign.budget.budgetId = budget.budgetId

      ' Required: Set the campaign's Dynamic Search Ads settings.
      Dim dynamicSearchAdsSetting As New DynamicSearchAdsSetting()
      ' Required: Set the domain name And language.
      dynamicSearchAdsSetting.domainName = "example.com"
      dynamicSearchAdsSetting.languageCode = "en"

      ' Set the campaign settings.
      campaign.settings = New Setting() {dynamicSearchAdsSetting}

      ' Optional: Set the start date.
      campaign.startDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd")

      ' Optional: Set the end date.
      campaign.endDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd")

      ' Create the operation.
      Dim operation As New CampaignOperation()
      operation.operator = [Operator].ADD
      operation.operand = campaign

      Try
        ' Add the campaign.
        Dim retval As CampaignReturnValue = campaignService.mutate(
            New CampaignOperation() {operation})

        ' Display the results.
        Dim newCampaign As Campaign = retval.value(0)
        Console.WriteLine("Campaign with id = '{0}' and name = '{1}' was added.",
          newCampaign.id, newCampaign.name)
        Return newCampaign
      Catch e As Exception
        Throw New System.ApplicationException("Failed to add campaigns.", e)
      End Try
    End Function

    ''' <summary>
    ''' Creates an ad group.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="campaignId">The campaign ID.</param>
    ''' <returns>the newly created ad group.</returns>
    Private Function CreateAdGroup(ByVal user As AdWordsUser, ByVal campaignId As Long) As AdGroup
      ' Get the AdGroupService.
      Dim adGroupService As AdGroupService = CType(user.GetService(
          AdWordsService.v201705.AdGroupService), AdGroupService)

      ' Create the ad group.
      Dim adGroup As New AdGroup()

      ' Required: set the ad group's type to Dynamic Search Ads.
      adGroup.adGroupType = AdGroupType.SEARCH_DYNAMIC_ADS

      adGroup.name = String.Format("Earth to Mars Cruises #{0}",
        ExampleUtilities.GetRandomString())
      adGroup.campaignId = campaignId
      adGroup.status = AdGroupStatus.PAUSED

      ' Set the ad group bids.
      Dim biddingConfig As New BiddingStrategyConfiguration()

      Dim cpcBid As New CpcBid()
      cpcBid.bid = New Money()
      cpcBid.bid.microAmount = 3000000

      biddingConfig.bids = New Bids() {cpcBid}

      adGroup.biddingStrategyConfiguration = biddingConfig

      ' Create the operation.
      Dim Operation As New AdGroupOperation()
      Operation.operator = [Operator].ADD
      Operation.operand = adGroup

      Try
        ' Create the ad group.
        Dim retVal As AdGroupReturnValue = adGroupService.mutate(
            New AdGroupOperation() {Operation})

        ' Display the results.
        Dim newAdGroup As AdGroup = retVal.value(0)
        Console.WriteLine("Ad group with id = '{0}' and name = '{1}' was created.",
          newAdGroup.id, newAdGroup.name)
        Return newAdGroup
      Catch e As Exception
        Throw New System.ApplicationException("Failed to create ad group.", e)
      End Try
    End Function

    ''' <summary>
    ''' Creates the expanded Dynamic Search Ad.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="adGroupId">ID of the ad group in which ad is created.</param>
    ''' <returns>The newly created ad.</returns>
    Private Function CreateExpandedDSA(ByVal user As AdWordsUser, ByVal adGroupId As Long) _
        As ExpandedDynamicSearchAd
      ' Get the AdGroupAdService.
      Dim adGroupAdService As AdGroupAdService = CType(user.GetService(
          AdWordsService.v201705.AdGroupAdService), AdGroupAdService)

      ' Create an Expanded Dynamic Search Ad. This ad will have its headline, display URL and
      ' final URL auto-generated at serving time according to domain name specific information
      ' provided by DynamicSearchAdsSetting at the campaign level.
      Dim expandedDSA As New ExpandedDynamicSearchAd()
      ' Set the ad description.
      expandedDSA.description = "Buy your tickets now!"

      ' Create the ad group ad.
      Dim adGroupAd As New AdGroupAd()
      adGroupAd.adGroupId = adGroupId
      adGroupAd.ad = expandedDSA

      ' Optional Set the status.
      adGroupAd.status = AdGroupAdStatus.PAUSED

      ' Create the operation.
      Dim operation As New AdGroupAdOperation()
      operation.operator = [Operator].ADD
      operation.operand = adGroupAd

      Try
        ' Create the ads.
        Dim retval As AdGroupAdReturnValue = adGroupAdService.mutate(
            New AdGroupAdOperation() {operation})

        ' Display the results.
        Dim newAdGroupAd As AdGroupAd = retval.value(0)
        Dim newAd As ExpandedDynamicSearchAd = CType(newAdGroupAd.ad, ExpandedDynamicSearchAd)
        Console.WriteLine("Expanded Dynamic Search Ad with ID '{0}' and description '{1}' " +
            "was added.", newAd.id, newAd.description)
        Return newAd
      Catch e As Exception
        Throw New System.ApplicationException("Failed to create Expanded Dynamic Search Ad.", e)
      End Try
    End Function

    ''' <summary>
    ''' Adds a web page criteria to target Dynamic Search Ads.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="adGroupId">The ad group ID.</param>
    ''' <returns>The newly created web page criterion.</returns>
    Private Function AddWebPageCriteria(ByVal user As AdWordsUser, ByVal adGroupId As Long) _
        As BiddableAdGroupCriterion
      ' Get the AdGroupCriterionService.
      Dim adGroupCriterionService As AdGroupCriterionService = CType(user.GetService(
          AdWordsService.v201705.AdGroupCriterionService), AdGroupCriterionService)

      ' Create a webpage criterion for special offers for mars cruise.
      Dim param As New WebpageParameter()
      param.criterionName = "Special offers for mars"

      Dim urlCondition As New WebpageCondition()
      urlCondition.operand = WebpageConditionOperand.URL
      urlCondition.argument = "/marscruise/special"

      Dim titleCondition As New WebpageCondition()
      titleCondition.operand = WebpageConditionOperand.PAGE_TITLE
      titleCondition.argument = "Special Offer"

      param.conditions = New WebpageCondition() {urlCondition, titleCondition}

      Dim Webpage As New Webpage()
      Webpage.parameter = param

      ' Create biddable ad group criterion.
      Dim biddableAdGroupCriterion As New BiddableAdGroupCriterion()
      biddableAdGroupCriterion.adGroupId = adGroupId
      biddableAdGroupCriterion.criterion = Webpage
      biddableAdGroupCriterion.userStatus = UserStatus.PAUSED

      ' Optional: Set a custom bid.
      Dim biddingStrategyConfiguration As New BiddingStrategyConfiguration()
      Dim bid As New CpcBid()
      bid.bid = New Money()
      bid.bid.microAmount = 10000000L

      biddingStrategyConfiguration.bids = New Bids() {bid}
      biddableAdGroupCriterion.biddingStrategyConfiguration = biddingStrategyConfiguration

      ' Create operations.
      Dim operation As New AdGroupCriterionOperation()
      operation.operator = [Operator].ADD
      operation.operand = biddableAdGroupCriterion

      Try
        Dim result As AdGroupCriterionReturnValue = adGroupCriterionService.mutate(
            New AdGroupCriterionOperation() {operation})

        Dim newCriterion As BiddableAdGroupCriterion = CType(result.value(0),
            BiddableAdGroupCriterion)
        Console.WriteLine("Webpage criterion with '{0}' was added to ad group ID '{1}'.",
            newCriterion.adGroupId, newCriterion.criterion.id)
        Return newCriterion
      Catch e As Exception
        Throw New System.ApplicationException("Failed to create webpage criterion.", e)
      End Try
    End Function
  End Class
End Namespace

Add an expanded text ad with Upgraded URLs

' 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>
  ''' This code example adds an expanded text ad that uses advanced features of upgraded
  ''' URLs.
  ''' </summary>
  Public Class AddExpandedTextAdWithUpgradedUrls
    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 AddExpandedTextAdWithUpgradedUrls
      Console.WriteLine(codeExample.Description)
      Try
        Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
        codeExample.Run(New AdWordsUser, 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 an expanded text ad that uses advanced features of " & _
            "upgraded URLs."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="adGroupId">ID of the adgroup to which ad is added.</param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long)
      ' Get the AdGroupAdService.
      Dim service As AdGroupAdService = CType(user.GetService( _
          AdWordsService.v201705.AdGroupAdService), AdGroupAdService)

      ' Create the expanded text ad.
      Dim expandedTextAd As New ExpandedTextAd
      expandedTextAd.headlinePart1 = "Luxury Cruise to Mars"
      expandedTextAd.headlinePart2 = "Visit the Red Planet in style."
      expandedTextAd.description = "Low-gravity fun for everyone!"

      ' Specify a tracking URL for 3rd party tracking provider. You may
      ' specify one at customer, campaign, ad group, ad, criterion or
      ' feed item levels.
      expandedTextAd.trackingUrlTemplate = _
          "http://tracker.example.com/?cid={_season}&promocode={_promocode}&u={lpurl}"

      ' Since your tracking URL has two custom parameters, provide their
      ' values too. This can be provided at campaign, ad group, ad, criterion
      ' or feed item levels.
      Dim seasonParameter As New CustomParameter
      seasonParameter.key = "season"
      seasonParameter.value = "christmas"

      Dim promoCodeParameter As New CustomParameter
      promoCodeParameter.key = "promocode"
      promoCodeParameter.value = "NYC123"

      expandedTextAd.urlCustomParameters = New CustomParameters
      expandedTextAd.urlCustomParameters.parameters = _
          New CustomParameter() {seasonParameter, promoCodeParameter}

      ' Specify a list of final URLs. This field cannot be set if URL field is
      ' set. This may be specified at ad, criterion and feed item levels.
      expandedTextAd.finalUrls = New String() { _
        "http://www.example.com/cruise/space/", _
        "http://www.example.com/locations/mars/" _
      }

      ' Specify a list of final mobile URLs. This field cannot be set if URL
      ' field is set, or finalUrls is unset. This may be specified at ad,
      ' criterion and feed item levels.
      expandedTextAd.finalMobileUrls = New String() { _
        "http://mobile.example.com/cruise/space/", _
        "http://mobile.example.com/locations/mars/" _
      }

      Dim adGroupAd As New AdGroupAd
      adGroupAd.adGroupId = adGroupId
      adGroupAd.ad = expandedTextAd

      ' Optional: Set the status.
      adGroupAd.status = AdGroupAdStatus.PAUSED

      ' Create the operation.
      Dim operation As New AdGroupAdOperation
      operation.operator = [Operator].ADD
      operation.operand = adGroupAd

      Dim retVal As AdGroupAdReturnValue = Nothing

      Try
        ' Create the ads.
        retVal = service.mutate(New AdGroupAdOperation() {operation})

        ' Display the results.
        If Not (retVal Is Nothing) AndAlso Not (retVal.value Is Nothing) Then
          Dim newExpandedTextAd As ExpandedTextAd = CType(retVal.value(0).ad, ExpandedTextAd)

          Console.WriteLine("Expanded text ad with ID '{0}' and headline '{1} - {2}' was added.",
              newExpandedTextAd.id, newExpandedTextAd.headlinePart1,
              newExpandedTextAd.headlinePart2)

          Console.WriteLine("Upgraded URL properties:")

          Console.WriteLine("  Final URLs: {0}", String.Join(", ", newExpandedTextAd.finalUrls))
          Console.WriteLine("  Final Mobile URLS: {0}", _
                            String.Join(", ", newExpandedTextAd.finalMobileUrls))
          Console.WriteLine("  Tracking URL template: {0}", newExpandedTextAd.trackingUrlTemplate)

          Dim parameters As New List(Of String)
          For Each customParam As CustomParameter In _
              newExpandedTextAd.urlCustomParameters.parameters
            parameters.Add(String.Format("{0}={1}", customParam.key, customParam.value))
          Next
          Console.WriteLine("  Custom parameters: {0}", String.Join(", ", parameters.ToArray()))
        Else
          Console.WriteLine("No expanded text ads were created.")
        End If
      Catch e As Exception
        Throw New System.ApplicationException("Failed to add expanded text ad to adgroup.", e)
      End Try
    End Sub
  End Class

End Namespace

Add an HTML 5 ad to an ad group

' 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 Google.Api.Ads.Common.Util

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

  ''' <summary>
  ''' This code example adds an HTML5 ad to a given ad group. To get ad
  ''' groups, run GetAdGroups.vb.
  ''' </summary>
  Public Class AddHtml5Ad
    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 AddHtml5Ad
      Console.WriteLine(codeExample.Description)
      Try
        Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
        codeExample.Run(New AdWordsUser(), 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 an HTML5 ad to a given ad group. To get ad" & _
            "groups, run GetAdGroups.vb."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="adGroupId">Id of the first adgroup to which ad is added.</param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long)
      ' Get the AdGroupAdService.
      Dim service As AdGroupAdService = CType(user.GetService( _
          AdWordsService.v201705.AdGroupAdService), AdGroupAdService)

      ' Create the HTML5 template ad. See
      ' https://developers.google.com/adwords/api/docs/guides/template-ads#html5_ads
      ' for more details.
      Dim html5Ad As New TemplateAd()
      html5Ad.name = "Ad for HTML5"
      html5Ad.templateId = 419
      html5Ad.finalUrls = New String() {"http://example.com/html5"}
      html5Ad.displayUrl = "www.example.com/html5"

      html5Ad.dimensions = New Dimensions()
      html5Ad.dimensions.width = 300
      html5Ad.dimensions.height = 250

      ' The HTML5 zip file contains all the HTML, CSS, and images needed for the
      ' HTML5 ad. For help on creating an HTML5 zip file, check out Google Web
      ' Designer (https://www.google.com/webdesigner/).
      Dim html5Zip As Byte() = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/9Y7qI2")

      ' Create a media bundle containing the zip file with all the HTML5 components.
      Dim mediaBundle As New MediaBundle()
      ' You may also upload an HTML5 zip using MediaService.upload() method
      ' set the mediaId field. See UploadMediaBundle.vb for an example on how to
      ' upload HTML5 zip files.
      mediaBundle.data = html5Zip
      mediaBundle.entryPoint = "carousel/index.html"
      mediaBundle.type = MediaMediaType.MEDIA_BUNDLE

      ' Create the template elements for the ad. You can refer to
      ' https://developers.google.com/adwords/api/docs/appendix/templateads
      ' for the list of available template fields.

      Dim adData As New TemplateElement
      adData.uniqueName = "adData"

      Dim customLayout As New TemplateElementField
      customLayout.name = "Custom_layout"
      customLayout.fieldMedia = mediaBundle
      customLayout.type = TemplateElementFieldType.MEDIA_BUNDLE

      Dim layout As New TemplateElementField
      layout.name = "layout"
      layout.fieldText = "Custom"
      layout.type = TemplateElementFieldType.ENUM

      adData.fields = New TemplateElementField() {customLayout, layout}

      html5Ad.templateElements = New TemplateElement() {adData}

      ' Create the AdGroupAd.
      Dim html5AdGroupAd As New AdGroupAd()
      html5AdGroupAd.adGroupId = adGroupId
      html5AdGroupAd.ad = html5Ad
      ' Additional properties (non-required).
      html5AdGroupAd.status = AdGroupAdStatus.PAUSED

      Dim adGroupAdOperation As New AdGroupAdOperation()
      adGroupAdOperation.operator = [Operator].ADD
      adGroupAdOperation.operand = html5AdGroupAd

      Try
        ' Add HTML5 ad.
        Dim result As AdGroupAdReturnValue = _
            service.mutate(New AdGroupAdOperation() {adGroupAdOperation})

        ' Display results.
        If (Not result Is Nothing) AndAlso (Not result.value Is Nothing) AndAlso _
            (result.value.Length > 0) Then
          For Each adGroupAd As AdGroupAd In result.value
            Console.WriteLine("New HTML5 ad with id '{0}' and display url '{1}' was added.", _
              adGroupAd.ad.id, adGroupAd.ad.displayUrl)
          Next
        Else
          Console.WriteLine("No HTML5 ads were added.")
        End If
      Catch e As Exception
        Throw New System.ApplicationException("Failed to create HTML5 ad.", e)
      End Try
    End Sub
  End Class
End Namespace

Add responsive ads

' 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.Util

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201705
  ''' <summary>
  ''' This code example adds an image representing the ad using the MediaService
  ''' and then adds a responsive display ad to an ad group. To get ad groups,
  ''' run GetAdGroups.vb.
  ''' </summary>
  Public Class AddResponsiveDisplayAd
    Inherits ExampleBase
    ''' <summary>
    ''' Number of items being added / updated in this code example.
    ''' </summary>
    Const NUM_ITEMS As Integer = 5

    ''' <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 AddResponsiveDisplayAd
      Console.WriteLine(codeExample.Description)
      Try
        Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
        codeExample.Run(New AdWordsUser, 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 an image representing the ad using the MediaService" & _
            "and then adds a responsive display ad to an ad group. To get ad groups, " & _
            "run GetAdGroups.vb."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="adGroupId">Id of the ad group to which ads are added.
    ''' </param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long)
      ' Get the AdGroupAdService.
      Dim adGroupAdService As AdGroupAdService = CType(user.GetService( _
          AdWordsService.v201705.AdGroupAdService), AdGroupAdService)

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

      Try
        ' Create the image.
        Dim image As New Image()
        image.data = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/3b9Wfh", user.Config)
        image.type = MediaMediaType.IMAGE

        ' Upload the image.
        Dim newImage As Image = CType(mediaService.upload(New Media() {image})(0), Image)

        ' Create a responsive display ad.
        Dim responsiveDisplayAd As New ResponsiveDisplayAd()

        ' This ad format does not allow the creation of an image using the
        ' Image.data field. An image must first be created using the MediaService,
        ' and Image.mediaId must be populated when creating the ad.
        responsiveDisplayAd.marketingImage = New Image()
        responsiveDisplayAd.marketingImage.mediaId = newImage.mediaId

        responsiveDisplayAd.shortHeadline = "Travel"
        responsiveDisplayAd.longHeadline = "Travel the World"
        responsiveDisplayAd.description = "Take to the air!"
        responsiveDisplayAd.businessName = "Google"
        responsiveDisplayAd.finalUrls = New String() {"http://www.example.com"}

        ' Create ad group ad.
        Dim adGroupAd As New AdGroupAd()
        adGroupAd.adGroupId = adGroupId
        adGroupAd.ad = responsiveDisplayAd
        adGroupAd.status = AdGroupAdStatus.PAUSED

        ' Create operation.
        Dim operation As New AdGroupAdOperation()
        operation.operand = adGroupAd
        operation.operator = [Operator].ADD

        ' Make the mutate request.
        Dim result As AdGroupAdReturnValue = adGroupAdService.mutate( _
            New AdGroupAdOperation() {operation})

        ' Display results.
        If (Not result Is Nothing) AndAlso (Not result.value Is Nothing) Then
          For Each newAdGroupAd As AdGroupAd In result.value
            Dim newAd As ResponsiveDisplayAd = CType(newAdGroupAd.ad, ResponsiveDisplayAd)
            Console.WriteLine("Responsive display ad with ID '{0}' and short headline '{1}'" & _
                " was added.", newAd.id, newAd.shortHeadline)
          Next
        Else
          Console.WriteLine("No responsive display ads were created.")
        End If
      Catch e As Exception
        Throw New System.ApplicationException("Failed to create responsive display ads.", e)
      End Try
    End Sub
  End Class
End Namespace

Add a universal app 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

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

  ''' <summary>
  ''' This code example adds a universal app campaign. To get campaigns, run
  ''' GetCampaigns.vb. To upload image assets for this campaign, use
  ''' UploadImage.vb.
  ''' </summary>
  Public Class AddUniversalAppCampaign
    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 AddUniversalAppCampaign
      Console.WriteLine(codeExample.Description)
      Try
        codeExample.Run(New AdWordsUser())
      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 universal app campaign. To get campaigns, run" & _
            " GetCampaigns.vb. To upload image assets for this campaign, use UploadImage.vb."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    Public Sub Run(ByVal user As AdWordsUser)
      ' Get the CampaignService.
      Dim campaignService As CampaignService = CType(user.GetService( _
          AdWordsService.v201705.CampaignService), CampaignService)

      ' Create the campaign.
      Dim campaign As New Campaign
      campaign.name = "Interplanetary Cruise App #" + ExampleUtilities.GetRandomString

      ' Recommendation: Set the campaign to PAUSED when creating it to prevent
      ' the ads from immediately serving. Set to ENABLED once you've added
      ' targeting and the ads are ready to serve.
      campaign.status = CampaignStatus.PAUSED

      ' Set the advertising channel and subchannel types for universal app campaigns.
      campaign.advertisingChannelType = AdvertisingChannelType.MULTI_CHANNEL
      campaign.advertisingChannelSubType = AdvertisingChannelSubType.UNIVERSAL_APP_CAMPAIGN

      ' Set the campaign's bidding strategy. Universal app campaigns
      ' only support TARGET_CPA bidding strategy.
      Dim biddingConfig As New BiddingStrategyConfiguration()
      biddingConfig.biddingStrategyType = BiddingStrategyType.TARGET_CPA

      ' Set the target CPA to $1 / app install.
      Dim biddingScheme As New TargetCpaBiddingScheme()
      biddingScheme.targetCpa = New Money()
      biddingScheme.targetCpa.microAmount = 1000000

      biddingConfig.biddingScheme = biddingScheme
      campaign.biddingStrategyConfiguration = biddingConfig

      ' Set the campaign's budget.
      campaign.budget = New Budget()
      campaign.budget.budgetId = CreateBudget(user).budgetId

      ' Optional: Set the start date.
      campaign.startDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd")

      ' Optional: Set the end date.
      campaign.endDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd")

      ' Set the campaign's assets and ad text ideas. These values will be used to
      ' generate ads.
      Dim universalAppSetting As New UniversalAppCampaignSetting()
      universalAppSetting.appId = "com.labpixies.colordrips"
      universalAppSetting.description1 = "A cool puzzle game"
      universalAppSetting.description2 = "Remove connected blocks"
      universalAppSetting.description3 = "3 difficulty levels"
      universalAppSetting.description4 = "4 colorful fun skins"

      ' Optional: You can set up to 10 image assets for your campaign.
      ' See UploadImage.cs for an example on how to upload images.
      '
      ' universalAppSetting.imageMediaIds = new long[] { INSERT_IMAGE_MEDIA_ID_HERE };

      ' Optimize this campaign for getting new users for your app.
      universalAppSetting.universalAppBiddingStrategyGoalType =
          UniversalAppBiddingStrategyGoalType.OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME

      ' Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal
      ' type, then also specify your in-app conversion types so AdWords can
      ' focus your campaign on people who are most likely to complete the
      ' corresponding in-app actions.
      ' Conversion type IDs can be retrieved using ConversionTrackerService.get.
      '
      ' campaign.selectiveOptimization = new SelectiveOptimization();
      ' campaign.selectiveOptimization.conversionTypeIds =
      '    new long[] { INSERT_CONVERSION_TYPE_ID_1_HERE, INSERT_CONVERSION_TYPE_ID_2_HERE };

      ' Optional: Set the campaign settings for Advanced location options.
      Dim geoSetting As New GeoTargetTypeSetting()
      geoSetting.positiveGeoTargetType = _
          GeoTargetTypeSettingPositiveGeoTargetType.LOCATION_OF_PRESENCE
      geoSetting.negativeGeoTargetType = _
          GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE

      campaign.settings = New Setting() {universalAppSetting, geoSetting}

      ' Create the operation.
      Dim operation As New CampaignOperation()
      operation.operator = [Operator].ADD
      operation.operand = campaign

      Try
        ' Add the campaign.
        Dim retVal As CampaignReturnValue = campaignService.mutate( _
            New CampaignOperation() {operation})

        ' Display the results.
        If Not (retVal Is Nothing) AndAlso Not (retVal.value Is Nothing) Then
          For Each newCampaign As Campaign In retVal.value
            Console.WriteLine("Universal app campaign with name = '{0}' and id = '{1}' was added.",
                newCampaign.name, newCampaign.id)

            ' Optional: Set the campaign's location and language targeting. No other targeting
            ' criteria can be used for universal app campaigns.
            SetCampaignTargetingCriteria(user, newCampaign)
          Next
        Else
          Console.WriteLine("No universal app campaigns were added.")
        End If
      Catch e As Exception
        Throw New System.ApplicationException("Failed to add universal app campaigns.", e)
      End Try
    End Sub

    ''' <summary>
    ''' Creates the budget for the campaign.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <returns>The budget.</returns>
    Private Shared Function CreateBudget(ByVal user As AdWordsUser) As Budget
      ' Get the BudgetService.
      Dim budgetService As BudgetService = CType(user.GetService( _
          AdWordsService.v201705.BudgetService), BudgetService)

      ' Create the campaign budget.
      Dim budget As New Budget()
      budget.name = "Interplanetary Cruise App Budget #" & ExampleUtilities.GetRandomString()
      budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD
      budget.amount = New Money()
      budget.amount.microAmount = 5000000

      ' Universal app campaigns don't support shared budgets.
      budget.isExplicitlyShared = False

      Dim budgetOperation As New BudgetOperation()
      budgetOperation.operator = [Operator].ADD
      budgetOperation.operand = budget

      Dim budgetRetval As BudgetReturnValue = budgetService.mutate( _
        New BudgetOperation() {budgetOperation})
      Dim newBudget As Budget = budgetRetval.value(0)

      Console.WriteLine("Budget with ID = '{0}' and name = '{1}' was created.", _
          newBudget.budgetId, newBudget.name)
      Return newBudget
    End Function

    ''' <summary>
    ''' Sets the campaign's targeting criteria.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="campaign">The campaign for which targeting criteria is
    ''' created.</param>
    Private Shared Sub SetCampaignTargetingCriteria(ByVal user As AdWordsUser, _
                                                    ByVal campaign As Campaign)
      ' Get the CampaignCriterionService.
      Dim campaignCriterionService As CampaignCriterionService = CType(user.GetService( _
          AdWordsService.v201705.CampaignCriterionService), CampaignCriterionService)

      ' Create locations. The IDs can be found in the documentation or
      ' retrieved with the LocationCriterionService.
      Dim california As New Location()
      california.id = 21137L

      Dim mexico As New Location()
      mexico.id = 2484L

      ' Create languages. The IDs can be found in the documentation or
      ' retrieved with the ConstantDataService.
      Dim english As New Language()
      english.id = 1000L

      Dim spanish As New Language()
      spanish.id = 1003L

      Dim criteria As Criterion() = {california, mexico, english, spanish}

      ' Create operations to add each of the criteria above.
      Dim operations As New List(Of CampaignCriterionOperation)()
      For Each criterion As Criterion In criteria
        Dim campaignCriterion As New CampaignCriterion
        campaignCriterion.campaignId = campaign.id
        campaignCriterion.criterion = criterion

        Dim operation As New CampaignCriterionOperation()
        operation.operand = campaignCriterion
        operation.operator = [Operator].ADD

        operations.Add(operation)
      Next

      ' Set the campaign targets.
      Dim retVal As CampaignCriterionReturnValue = campaignCriterionService.mutate( _
          operations.ToArray())

      If Not (retVal Is Nothing) AndAlso Not (retVal.value Is Nothing) Then
        ' Display the added campaign targets.
        For Each criterion As CampaignCriterion In retVal.value
          Console.WriteLine("Campaign criteria of type '{0}' and id '{1}' was added.",
                            criterion.criterion.CriterionType, criterion.criterion.id)
        Next
      End If
    End Sub
  End Class
End Namespace

Create and attach a shared keyword set

' 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

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

  ''' <summary>
  ''' This code example creates a shared keyword list, adds keywords to the list
  ''' and attaches it to an existing campaign. To get the list of campaigns,
  ''' run GetCampaigns.vb.
  ''' </summary>
  Public Class CreateAndAttachSharedKeywordSet
    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 CreateAndAttachSharedKeywordSet
      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 creates a shared keyword list, adds keywords to the list" & _
            "and attaches it to an existing campaign. To get the list of campaigns, run " & _
            "GetCampaigns.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 to which keywords are added.</param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long)
      Try
        ' Create a shared set.
        Dim sharedSet As SharedSet = CreateSharedKeywordSet(user)

        Console.WriteLine("Shared set with id = {0}, name = {1}, type = {2}, status = {3} " & _
            "was created.", sharedSet.sharedSetId, sharedSet.name, sharedSet.type, _
            sharedSet.status)

        ' Add new keywords to the shared set.
        Dim keywordTexts As String() = New String() {"mars cruise", "mars hotels"}
        Dim sharedCriteria As SharedCriterion() = AddKeywordsToSharedSet(user, _
            sharedSet.sharedSetId, keywordTexts)
        For Each sharedCriterion As SharedCriterion In sharedCriteria
          Dim keyword As Keyword = DirectCast(sharedCriterion.criterion, Keyword)
          Console.WriteLine("Added keyword with id = {0}, text = {1}, matchtype = {2} to " & _
              "shared set with id = {3}.", keyword.id, keyword.text, keyword.matchType, _
              sharedSet.sharedSetId)
        Next

        ' Attach the shared set to the campaign.
        Dim attachedSharedSet As CampaignSharedSet = AttachSharedSetToCampaign(user, campaignId, _
            sharedSet.sharedSetId)

        Console.WriteLine("Attached shared set with id = {0} to campaign id {1}.", _
            attachedSharedSet.sharedSetId, attachedSharedSet.campaignId)
      Catch e As Exception
        Throw New System.ApplicationException("Failed to create shared keyword set and attach " & _
            "it to a campaign.", e)
      End Try
    End Sub

    ''' <summary>
    ''' Create a shared keyword set.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <returns>The shared set.</returns>
    Public Function CreateSharedKeywordSet(ByVal user As AdWordsUser) As SharedSet
      ' Get the SharedSetService.
      Dim sharedSetService As SharedSetService = DirectCast(user.GetService( _
          AdWordsService.v201705.SharedSetService), SharedSetService)

      Dim operation As New SharedSetOperation()
      operation.operator = [Operator].ADD
      Dim sharedSet As New SharedSet()
      sharedSet.name = "API Negative keyword list - " & ExampleUtilities.GetRandomString()
      sharedSet.type = SharedSetType.NEGATIVE_KEYWORDS
      operation.operand = sharedSet

      Dim retval As SharedSetReturnValue = sharedSetService.mutate( _
          New SharedSetOperation() {operation})
      Return retval.value(0)
    End Function

    ''' <summary>
    ''' Adds a set of keywords to a shared set.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="sharedSetId">The shared set id.</param>
    ''' <param name="keywordTexts">The keywords to be added to the shared set.</param>
    ''' <returns>The newly added set of shared criteria.</returns>
    Public Function AddKeywordsToSharedSet(ByVal user As AdWordsUser, ByVal sharedSetId As Long, _
        ByVal keywordTexts As String()) As SharedCriterion()
      ' Get the SharedCriterionService.
      Dim sharedSetService As SharedCriterionService = DirectCast(user.GetService( _
          AdWordsService.v201705.SharedCriterionService), SharedCriterionService)

      Dim operations As New List(Of SharedCriterionOperation)
      For Each keywordText As String In keywordTexts
        Dim keyword As New Keyword()
        keyword.text = keywordText
        keyword.matchType = KeywordMatchType.BROAD

        Dim sharedCriterion As New SharedCriterion()
        sharedCriterion.criterion = keyword
        sharedCriterion.negative = True
        sharedCriterion.sharedSetId = sharedSetId

        Dim operation As New SharedCriterionOperation()
        operation.operator = [Operator].ADD
        operation.operand = sharedCriterion
        operations.Add(operation)
      Next

      Dim retval As SharedCriterionReturnValue = sharedSetService.mutate(operations.ToArray())
      Return retval.value
    End Function

    ''' <summary>
    ''' Attaches a shared set to a campaign.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="campaignId">The campaign id.</param>
    ''' <param name="sharedSetId">The shared set id.</param>
    ''' <returns>A CampaignSharedSet object that represents a binding between
    ''' the specified campaign and the shared set.</returns>
    Public Function AttachSharedSetToCampaign(ByVal user As AdWordsUser, _
        ByVal campaignId As Long, ByVal sharedSetId As Long) As CampaignSharedSet
      ' Get the CampaignSharedSetService.
      Dim campaignSharedSetService As CampaignSharedSetService = DirectCast(user.GetService( _
          AdWordsService.v201705.CampaignSharedSetService), CampaignSharedSetService)

      Dim campaignSharedSet As New CampaignSharedSet()
      campaignSharedSet.campaignId = campaignId
      campaignSharedSet.sharedSetId = sharedSetId

      Dim operation As New CampaignSharedSetOperation()
      operation.operator = [Operator].ADD
      operation.operand = campaignSharedSet

      Dim retval As CampaignSharedSetReturnValue = campaignSharedSetService.mutate( _
          New CampaignSharedSetOperation() {operation})
      Return retval.value(0)
    End Function

  End Class
End Namespace

Find and remove criteria from a shared set

' 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

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

  ''' <summary>
  ''' This code example demonstrates how to find and remove shared sets and
  ''' shared set criteria.
  '''
  ''' </summary>
  Public Class FindAndRemoveCriteriaFromSharedSet
    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 FindAndRemoveCriteriaFromSharedSet
      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 demonstrates how to find and remove shared sets and shared " & _
            "set criteria."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="campaignId">Id of the campaign to which keywords are removed.</param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long)
      ' Get the list of shared sets that are attached to the campaign.
      Dim sharedSetIds As List(Of String) = GetSharedSetIds(user, campaignId)

      ' Get the shared criteria in those shared sets.
      Dim sharedCriteria As List(Of SharedCriterion) = GetSharedCriteria(user, sharedSetIds)

      ' Remove the shared criteria from the shared sets.
      RemoveSharedCriteria(user, sharedCriteria)
    End Sub

    ''' <summary>
    ''' Gets the shared set IDs associated with a campaign.
    ''' </summary>
    ''' <param name="user">The user that owns the campaign.</param>
    ''' <param name="campaignId">The campaign identifier.</param>
    ''' <returns>The list of shared set IDs associated with the campaign.</returns>
    Private Function GetSharedSetIds(ByVal user As AdWordsUser, ByVal campaignId As Long) _
        As List(Of String)
      Dim campaignSharedSetService As CampaignSharedSetService = DirectCast(user.GetService( _
              AdWordsService.v201705.CampaignSharedSetService), CampaignSharedSetService)

      Dim selector As New Selector()
      selector.fields = New String() {
        CampaignSharedSet.Fields.SharedSetId,
        CampaignSharedSet.Fields.CampaignId,
        CampaignSharedSet.Fields.SharedSetName,
        CampaignSharedSet.Fields.SharedSetType
      }

      selector.predicates = New Predicate() {
        Predicate.Equals(CampaignSharedSet.Fields.CampaignId, campaignId),
        Predicate.In(CampaignSharedSet.Fields.SharedSetType,
            New String() {SharedSetType.NEGATIVE_KEYWORDS.ToString()})
      }
      selector.paging = Paging.Default
      Dim sharedSetIds As New List(Of String)

      Dim page As New CampaignSharedSetPage()

      Try
        Do
          ' Get the campaigns.
          page = campaignSharedSetService.get(selector)

          ' Display the results.
          If (Not page Is Nothing) AndAlso (Not page.entries Is Nothing) Then
            Dim i As Integer = selector.paging.startIndex
            For Each campaignSharedSet As CampaignSharedSet In page.entries
              sharedSetIds.Add(campaignSharedSet.sharedSetId.ToString())
              Console.WriteLine("{0}) Campaign shared set ID {1} and name '{2}' found for " & _
                  "campaign ID {3}.\n", i + 1, campaignSharedSet.sharedSetId, _
                  campaignSharedSet.sharedSetName, campaignSharedSet.campaignId)
              i = i + 1
            Next
          End If
          selector.paging.IncreaseOffset()
        Loop While (selector.paging.startIndex < page.totalNumEntries)
        Return sharedSetIds
      Catch e As Exception
        Throw New Exception("Failed to get shared set ids for campaign.", e)
      End Try
    End Function

    ''' <summary>
    ''' Gets the shared criteria in a shared set.
    ''' </summary>
    ''' <param name="user">The user that owns the shared set.</param>
    ''' <param name="sharedSetIds">The shared criteria IDs.</param>
    ''' <returns>The list of shared criteria.</returns>
    Private Function GetSharedCriteria(ByVal user As AdWordsUser, ByVal sharedSetIds As  _
                                       List(Of String)) As List(Of SharedCriterion)
      Dim sharedCriterionService As SharedCriterionService = DirectCast(user.GetService( _
          AdWordsService.v201705.SharedCriterionService), SharedCriterionService)

      Dim selector As New Selector()
      selector.fields = New String() {
        SharedSet.Fields.SharedSetId, Criterion.Fields.Id, Keyword.Fields.KeywordText, _
        Keyword.Fields.KeywordMatchType, Placement.Fields.PlacementUrl
      }

      selector.predicates = New Predicate() {
        Predicate.In(SharedSet.Fields.SharedSetId, sharedSetIds)
      }

      selector.paging = Paging.Default

      Dim sharedCriteria As New List(Of SharedCriterion)
      Dim page As New SharedCriterionPage()

      Try
        Do
          ' Get the criteria.
          page = sharedCriterionService.get(selector)

          ' Display the results.
          If (Not page Is Nothing) AndAlso (Not page.entries Is Nothing) Then
            Dim i As Integer = selector.paging.startIndex
            For Each sharedCriterion As SharedCriterion In page.entries
              Select Case sharedCriterion.criterion.type
                Case CriterionType.KEYWORD
                  Dim keyword As Keyword = DirectCast(sharedCriterion.criterion, Keyword)
                  Console.WriteLine("Shared negative keyword with ID {0} and text '{1}' was " & _
                      "found.", keyword.id, keyword.text)
                  Exit Select

                Case CriterionType.PLACEMENT
                  Dim placement As Placement = DirectCast(sharedCriterion.criterion, Placement)
                  Console.WriteLine("{0}) Shared negative placement with ID {1} and URL '{2}' " & _
                      "was found.", i + 1, placement.id, placement.url)
                  Exit Select

                Case Else
                  Console.WriteLine("{0}) Shared criteria with ID {1} was found.", _
                      i + 1, sharedCriterion.criterion.id)
              End Select

              i = i + 1
              sharedCriteria.Add(sharedCriterion)
            Next
          End If
          selector.paging.IncreaseOffset()
        Loop While (selector.paging.startIndex < page.totalNumEntries)

        Return sharedCriteria
      Catch e As Exception
        Throw New Exception("Failed to get shared criteria.", e)
      End Try
    End Function

    ''' <summary>
    ''' Removes a list of shared criteria.
    ''' </summary>
    ''' <param name="user">The user that owns the shared criteria.</param>
    ''' <param name="sharedCriteria">The list shared criteria to be removed.</param>
    Private Sub RemoveSharedCriteria(ByVal user As AdWordsUser, ByVal sharedCriteria _
        As List(Of SharedCriterion))
      If sharedCriteria.Count = 0 Then
        Console.WriteLine("No shared criteria to remove.")
        Return
      End If

      Dim sharedCriterionService As SharedCriterionService = DirectCast(user.GetService( _
          AdWordsService.v201705.SharedCriterionService), SharedCriterionService)

      Dim operations As New List(Of SharedCriterionOperation)

      For Each sharedCriterion As SharedCriterion In sharedCriteria

        Dim operation As New SharedCriterionOperation()
        operation.operator = [Operator].REMOVE

        Dim tempSharedCriterion As New SharedCriterion()
        tempSharedCriterion.sharedSetId = sharedCriterion.sharedSetId
        tempSharedCriterion.criterion = New Criterion()
        tempSharedCriterion.criterion.id = sharedCriterion.criterion.id

        operation.operand = tempSharedCriterion
        operations.Add(operation)
      Next
      Try
        Dim sharedCriterionReturnValue As SharedCriterionReturnValue = _
            sharedCriterionService.mutate(operations.ToArray())

        For Each removedCriterion As SharedCriterion In sharedCriterionReturnValue.value
          Console.WriteLine("Shared criterion ID {0} was successfully removed from shared " & _
              "set ID {1}.", removedCriterion.criterion.id, removedCriterion.sharedSetId)
        Next
      Catch e As Exception
        Throw New Exception("Failed to remove shared criteria.", e)
      End Try
    End Sub
  End Class
End Namespace

Get ad group bid modifiers

' 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>
  ''' This code example illustrates how to retrieve ad group level mobile bid
  ''' modifiers for a campaign.
  '''
  ''' AdGroupBidModifierService.get
  ''' </summary>
  Public Class GetAdGroupBidModifiers
    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 GetAdGroupBidModifiers
      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 illustrates how to retrieve ad group level mobile bid" & _
            " modifiers for 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 for which adgroup bid
    ''' modifiers are retrieved.</param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long)
      ' Get the AdGroupBidModifierService.
      Dim adGroupBidModifierService As AdGroupBidModifierService = CType(user.GetService( _
          AdWordsService.v201705.AdGroupBidModifierService),  _
          AdGroupBidModifierService)

      ' Get all ad group bid modifiers for the campaign.
      Dim selector As New Selector()
      selector.fields = New String() {
        AdGroupBidModifier.Fields.CampaignId, AdGroupBidModifier.Fields.AdGroupId,
        AdGroupBidModifier.Fields.BidModifier, AdGroupBidModifier.Fields.BidModifierSource,
        Criterion.Fields.CriteriaType, Criterion.Fields.Id
      }

      Dim predicate As New Predicate()
      predicate.field = "CampaignId"
      predicate.[operator] = PredicateOperator.EQUALS
      predicate.values = New String() {campaignId.ToString()}
      selector.predicates = New Predicate() {
        Predicate.Equals(AdGroupBidModifier.Fields.CampaignId, campaignId)
      }
      selector.paging = Paging.Default

      Dim page As New AdGroupBidModifierPage()

      Try
        Do
          ' Get the ad group bids.
          page = adGroupBidModifierService.get(selector)

          ' Display the results.
          If (Not page Is Nothing) AndAlso (Not page.entries Is Nothing) Then
            Dim i As Integer = selector.paging.startIndex
            For Each adGroupBidModifier As AdGroupBidModifier In page.entries
              Dim bidModifier As String = ""
              If adGroupBidModifier.bidModifierSpecified Then
                bidModifier = adGroupBidModifier.bidModifier.ToString()
              Else
                bidModifier = "UNSET"
              End If
              Console.WriteLine("{0}) Campaign ID {1}, AdGroup ID {2}, Criterion ID {3} has " & _
                  "ad group level modifier: {4}, source = {5}.", _
                  i + 1, adGroupBidModifier.campaignId, _
                  adGroupBidModifier.adGroupId, adGroupBidModifier.criterion.id, _
                  bidModifier, adGroupBidModifier.bidModifierSource)
              i = i + 1
            Next
          End If
          selector.paging.IncreaseOffset()
        Loop While selector.paging.startIndex < page.totalNumEntries
        Console.WriteLine("Number of adgroup bid modifiers found: {0}", page.totalNumEntries)
      Catch e As Exception
        Throw New System.ApplicationException("Failed to retrieve adgroup bid modifiers.", e)
      End Try
    End Sub
  End Class
End Namespace

Send feedback about...

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