Share your feedback about the Google Ads (AdWords) API. Take the 2021 AdWords API and Google Ads API Annual Survey.

The AdWords API will sunset on April 27, 2022. Migrate to the Google Ads API to take advantage of the latest Google Ads features.

Advanced Operations Samples

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

Add an ad customizer feed

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example adds an ad customizer feed. Then it adds an ad in two
    ''' different ad groups 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 ad groups 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)
            Try
                ' 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)
            Catch e As Exception
                Throw New System.ApplicationException("Failed to add ad customizers modifiers to " +
                                                      "ad group.", e)
            End Try
        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
            Using adCustomizerFeedService As AdCustomizerFeedService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.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 Using
        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)
            Using feedItemService As FeedItemService = CType(
                user.GetService(
                    AdWordsService.v201809.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")))

                Dim venusDate As New DateTime(DateTime.Now.Year, DateTime.Now.Month, 15)
                feedItemOperations.Add(CreateFeedItemAddOperation(adCustomizerFeed, "Venus",
                                                                  "$1450.00",
                                                                  venusDate.ToString(
                                                                      "yyyyMMdd HHmmss")))
                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

                ' Add feed item targeting to restrict the feed item to specific ad groups.
                RestrictFeedItemToAdGroup(user, feedItemReturnValue.value(0), adGroupIds(0))
                RestrictFeedItemToAdGroup(user, feedItemReturnValue.value(1), adGroupIds(1))
            End Using
        End Sub

        ''' <summary>
        ''' Restricts the feed item to an ad group.
        ''' </summary>
        ''' <param name="user">The user.</param>
        ''' <param name="feedItem">The feed item.</param>
        ''' <param name="adGroupId">The ad group ID.</param>
        Private Shared Sub RestrictFeedItemToAdGroup(user As AdWordsUser,
                                                     feedItem As FeedItem, adGroupId As Long?)
            Dim adGroupTarget As New FeedItemAdGroupTarget()
            adGroupTarget.feedId = feedItem.feedId
            adGroupTarget.feedItemId = feedItem.feedItemId
            adGroupTarget.adGroupId = adGroupId.Value

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

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

        ''' <summary>
        ''' Creates a FeedItemOperation that will create a FeedItem with the
        ''' specified values 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>
        ''' <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) _
            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


            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)
            Using adGroupAdService As AdGroupAdService = CType(
                user.GetService(
                    AdWordsService.v201809.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 Using
        End Sub
    End Class
End Namespace

Add an ad group level bid modifier

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' 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)
            Using adGroupBidModifierService As AdGroupBidModifierService = CType(
                user.GetService(
                    AdWordsService.v201809.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 Using
        End Sub
    End Class
End Namespace

Add a page feed specifying URLs for a DSA campaign

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <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"

            Try
                ' 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)
            Catch e As Exception
                Throw _
                    New System.ApplicationException(
                        "Failed to setup dynamic page feed for campaign.", e)
            End Try
        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
            Using feedService As FeedService = CType(
                user.GetService(
                    AdWordsService.v201809.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 Using
        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)
            Using feedMappingService As FeedMappingService = CType(
                user.GetService(
                    AdWordsService.v201809.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})
            End Using
        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)
            Using feedItemService As FeedItemService = CType(
                user.GetService(
                    AdWordsService.v201809.FeedItemService),
                FeedItemService)

                Dim rentalCarsUrl As String = "http://www.example.com/discounts/rental-cars"
                Dim hotelDealsUrl As String = "http://www.example.com/discounts/hotel-deals"
                Dim flightDealsUrl As String = "http://www.example.com/discounts/flight-deals"
                Dim operations() As FeedItemOperation =
                        { _
                            CreateDsaUrlAddOperation(feedDetails,
                                                     rentalCarsUrl,
                                                     labelName),
                            CreateDsaUrlAddOperation(feedDetails,
                                                     hotelDealsUrl,
                                                     labelName),
                            CreateDsaUrlAddOperation(feedDetails,
                                                     flightDealsUrl,
                                                     labelName)
                        }
                feedItemService.mutate(operations)
            End Using
        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

            ' See https://support.google.com/adwords/answer/7166527 for page feed URL
            ' recommendations and rules.
            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)
            Using campaignService As CampaignService = CType(
                user.GetService(
                    AdWordsService.v201809.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 Using
        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
            Using adGroupCriterionService As AdGroupCriterionService = CType(
                user.GetService(
                    AdWordsService.v201809.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 Using
        End Function

    End Class
End Namespace

Add a DSA campaign

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <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)
            Try
                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.")
            Catch e As Exception
                Throw _
                    New System.ApplicationException("Failed to setup Dynamic Search Ads campaign.",
                                                    e)
            End Try
        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.
            Using budgetService As BudgetService = CType(
                user.GetService(
                    AdWordsService.v201809.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 Using
        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
            Using campaignService As CampaignService = CType(
                user.GetService(
                    AdWordsService.v201809.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 Using
        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
            Using adGroupService As AdGroupService = CType(
                user.GetService(
                    AdWordsService.v201809.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 Using
        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
            Using adGroupAdService As AdGroupAdService = CType(
                user.GetService(
                    AdWordsService.v201809.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!"
                expandedDSA.description2 = "Discount ends soon"

                ' 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 Using
        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
            Using adGroupCriterionService As AdGroupCriterionService = CType(
                user.GetService(
                    AdWordsService.v201809.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 Using
        End Function
    End Class
End Namespace

Add an expanded text ad with Upgraded URLs

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' 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)
            Using adGroupAdService As AdGroupAdService = CType(
                user.GetService(
                    AdWordsService.v201809.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 = adGroupAdService.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 Using
        End Sub
    End Class
End Namespace

Add a Gmail ad to an ad group

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example adds a Gmail ad to a given ad group. The ad group's
    ''' campaign needs to have an AdvertisingChannelType of DISPLAY and
    ''' AdvertisingChannelSubType of DISPLAY_GMAIL_AD.
    ''' To get ad groups, run GetAdGroups.cs.
    ''' </summary>
    Public Class AddGmailAd
        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 AddGmailAd
            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 a Gmail ad to a given ad group. The ad group's " &
                    "campaign needs to have an AdvertisingChannelType of DISPLAY and " &
                    "AdvertisingChannelSubType of DISPLAY_GMAIL_AD. 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 adgroup to which ads are added.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long)
            Using adGroupAdService As AdGroupAdService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.AdGroupAdService),
                AdGroupAdService)
                ' 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.
                Dim logoImage As New Image()
                logoImage.mediaId = UploadImage(user, "https://goo.gl/mtt54n").mediaId

                Dim marketingImage As New Image()
                marketingImage.mediaId = UploadImage(user, "https://goo.gl/3b9Wfh").mediaId

                Dim teaser As New GmailTeaser()
                teaser.headline = "Dream"
                teaser.description = "Create your own adventure"
                teaser.businessName = "Interplanetary Ships"
                teaser.logoImage = logoImage

                ' Creates a Gmail ad.
                Dim gmailAd As New GmailAd()
                gmailAd.teaser = teaser
                gmailAd.marketingImage = marketingImage
                gmailAd.marketingImageHeadline = "Travel"
                gmailAd.marketingImageDescription = "Take to the skies!"
                gmailAd.finalUrls = New String() {"http://www.example.com/"}

                ' Creates ad group ad for the Gmail ad.
                Dim adGroupAd As New AdGroupAd()
                adGroupAd.adGroupId = adGroupId
                adGroupAd.ad = gmailAd

                ' Optional: Set additional settings.
                adGroupAd.status = AdGroupAdStatus.PAUSED

                ' Creates ad group ad operation and add it to the list.
                Dim operation As New AdGroupAdOperation()
                operation.operand = adGroupAd
                operation.operator = [Operator].ADD

                Try
                    ' Adds a responsive display ad on the server.
                    Dim result As AdGroupAdReturnValue = adGroupAdService.mutate(
                        New AdGroupAdOperation() {operation})

                    If result Is Nothing Or result.value Is Nothing Or result.value.Length = 0 Then
                        Console.WriteLine("No Gmail ads were added.")
                        Return
                    End If

                    ' Prints out some information for each created Gmail ad.
                    For Each newAdGroupAd As AdGroupAd In result.value
                        Console.WriteLine("A Gmail ad with ID {0} and headline '{1}' was added.",
                                          newAdGroupAd.ad.id,
                                          DirectCast(newAdGroupAd.ad, GmailAd).teaser.headline)
                    Next
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to add Gmail ads.", e)
                End Try
            End Using
        End Sub

        ''' <summary>
        ''' Uploads an image to the server.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="url">The URL of image to upload.</param>
        ''' <returns>The created image.</returns>
        Private Shared Function UploadImage(ByVal user As AdWordsUser, ByVal url As String) As Media
            Using mediaService As MediaService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.MediaService),
                MediaService)
                Dim image As New Image()
                image.data = MediaUtilities.GetAssetDataFromUrl(url, user.Config)
                image.type = MediaMediaType.IMAGE
                Return mediaService.upload(New Media() {image})(0)
            End Using
        End Function
    End Class
End Namespace

Add an HTML 5 ad to an ad group

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <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)
            Using adGroupAdService As AdGroupAdService = CType(
                user.GetService(
                    AdWordsService.v201809.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",
                                                                            user.Config)

                ' 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 =
                            adGroupAdService.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 Using
        End Sub
    End Class
End Namespace

Add a multi-asset responsive display ad to an ad group

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example adds a responsive display ad (MultiAssetResponsiveDisplayAd)
    ''' to an ad group. Image assets are uploaded using AssetService. To get ad groups,
    ''' run GetAdGroups.vb.
    ''' </summary>
    Public Class AddMultiAssetResponsiveDisplayAd
        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 AddMultiAssetResponsiveDisplayAd
            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 a responsive display ad " +
                       "(MultiAssetResponsiveDisplayAd) to an ad group. Image assets are uploaded" +
                       " using AssetService. 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 adgroup to which ad is added.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long)
            Using adGroupAdService As AdGroupAdService = CType(
                user.GetService(
                    AdWordsService.v201809.AdGroupAdService),
                AdGroupAdService)
                Try
                    ' Create the ad.
                    Dim ad As New MultiAssetResponsiveDisplayAd()

                    ' Text assets can be specified directly in the asset field when
                    ' creating the ad.
                    Dim textAsset1 As New TextAsset
                    textAsset1.assetText = "Travel to Mars"
                    Dim headline1 As New AssetLink
                    headline1.asset = textAsset1

                    Dim textAsset2 As New TextAsset
                    textAsset2.assetText = "Travel to Jupiter"
                    Dim headline2 As New AssetLink
                    headline2.asset = textAsset2

                    Dim textAsset3 As New TextAsset
                    textAsset3.assetText = "Travel to Pluto"
                    Dim headline3 As New AssetLink
                    headline3.asset = textAsset3

                    ad.headlines = New AssetLink() {headline1, headline2, headline3}

                    Dim textAsset4 As New TextAsset
                    textAsset4.assetText = "Visit the planet in a luxury spaceship."
                    Dim description1 As New AssetLink
                    description1.asset = textAsset1

                    Dim textAsset5 As New TextAsset
                    textAsset5.assetText = "Travel to Jupiter"
                    Dim description2 As New AssetLink
                    description2.asset = textAsset5

                    Dim textAsset6 As New TextAsset
                    textAsset6.assetText = "Travel to Pluto"
                    Dim description3 As New AssetLink
                    description3.asset = textAsset6

                    ad.descriptions = New AssetLink() {description1, description2, description3}
                    ad.businessName = "Galactic Luxury Cruises"

                    Dim textAsset7 As New TextAsset
                    textAsset7.assetText = "Travel to Pluto"
                    Dim longHeadline As New AssetLink
                    longHeadline.asset = textAsset7

                    ad.longHeadline = longHeadline

                    ' This ad format does not allow the creation of an image asset by setting
                    ' the asset.imageData field. An image asset must first be created using the
                    ' AssetService, and asset.assetId must be populated when creating the ad.

                    Dim imageAsset1 As New ImageAsset
                    imageAsset1.assetId = UploadImageAsset(user, "https://goo.gl/3b9Wfh")
                    Dim marketingImage As New AssetLink
                    marketingImage.asset = imageAsset1
                    ad.marketingImages = New AssetLink() {marketingImage}

                    Dim imageAsset2 As New ImageAsset
                    imageAsset2.assetId = UploadImageAsset(user, "https://goo.gl/mtt54n")
                    Dim squareMarketingImage As New AssetLink
                    squareMarketingImage.asset = imageAsset2
                    ad.squareMarketingImages = New AssetLink() {squareMarketingImage}

                    ad.finalUrls = New String() {"http://www.example.com"}

                    ' Optional: set call to action text.
                    ad.callToActionText = "Shop Now"

                    ' Set color settings using hexadecimal values. Set allowFlexibleColor to false
                    ' if you want your ads to render by always using your colors strictly.
                    ad.mainColor = "#0000ff"
                    ad.accentColor = "#ffff00"
                    ad.allowFlexibleColor = False

                    ' Set the format setting that the ad will be served in.
                    ad.formatSetting = DisplayAdFormatSetting.NON_NATIVE

                    ' Optional: set dynamic display ad settings, composed of landscape logo
                    ' image, promotion text, And price prefix.
                    ad.dynamicSettingsPricePrefix = "as low as"
                    ad.dynamicSettingsPromoText = "Free shipping!"

                    Dim imageAsset3 As New ImageAsset
                    imageAsset3.assetId = UploadImageAsset(user, "https://goo.gl/mtt54n")
                    Dim logoImages As New AssetLink
                    logoImages.asset = imageAsset3
                    ad.logoImages = New AssetLink() {logoImages}

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

                    ' Create the 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 MultiAssetResponsiveDisplayAd =
                                    CType(newAdGroupAd.ad, MultiAssetResponsiveDisplayAd)
                            Console.WriteLine(
                                "Responsive display ad with ID '{0}' and long headline '{1}'" +
                                " was added.", newAd.id,
                                CType(newAd.longHeadline.asset, TextAsset).assetText)
                        Next
                    End If
                Catch e As Exception
                    Throw New System.ApplicationException(
                        "Failed to add expanded text ad to adgroup.",
                        e)
                End Try
            End Using
        End Sub

        ''' <summary>
        ''' Uploads the image from the specified <paramref name="url"/>.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="url">The image URL.</param>
        ''' <returns>ID of the uploaded image.</returns>
        Private Shared Function UploadImageAsset(ByVal user As AdWordsUser, ByVal url As String) _
            As Long
            Using assetService As AssetService = CType(
                user.GetService(
                    AdWordsService.v201809.AssetService),
                AssetService)

                ' Create the image asset.
                Dim imageAsset = New ImageAsset()
                ' Optional: Provide a unique friendly name to identify your asset. If you specify
                ' the assetName field, then both the asset name and the image being uploaded should
                ' be unique, and should not match another ACTIVE asset in this customer account.
                ' imageAsset.assetName = "Image asset " + ExampleUtilities.GetRandomString()
                imageAsset.imageData = MediaUtilities.GetAssetDataFromUrl(url, user.Config)

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

                ' Create the asset And return the ID.
                Return assetService.mutate(New AssetOperation() {operation}).value(0).assetId
            End Using
        End Function
    End Class
End Namespace

Add a responsive display ad

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <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)
            Using adGroupAdService As AdGroupAdService = CType(
                user.GetService(
                    AdWordsService.v201809.AdGroupAdService),
                AdGroupAdService)

                Try
                    ' 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 =
                        UploadImage(user, "https://goo.gl/3b9Wfh")

                    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"}

                    ' Optional: Create a square marketing image Using MediaService, And set it
                    ' to the ad.
                    responsiveDisplayAd.squareMarketingImage = New Image()
                    responsiveDisplayAd.squareMarketingImage.mediaId =
                        UploadImage(user, "https://goo.gl/mtt54n")

                    ' Optional: Set call to action text.
                    responsiveDisplayAd.callToActionText = "Shop Now"

                    ' Optional: Set dynamic display ad settings, composed of landscape logo
                    ' image, promotion text, And price prefix.
                    responsiveDisplayAd.dynamicDisplayAdSettings =
                        CreateDynamicDisplayAdSettings(user)

                    ' Whitelisted accounts only Set color settings using hexadecimal values.
                    ' Set allowFlexibleColor to false if you want your ads to render by always
                    ' using your colors strictly.

                    ' responsiveDisplayAd.mainColor = "#0000ff"
                    ' responsiveDisplayAd.accentColor = "#ffff00"
                    ' responsiveDisplayAd.allowFlexibleColor = false

                    ' Whitelisted accounts only Set the format setting that the ad will be
                    ' served in.

                    ' responsiveDisplayAd.formatSetting = DisplayAdFormatSetting.NON_NATIVE;

                    ' 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 Using
        End Sub

        ''' <summary>
        ''' Creates the dynamic display ad settings.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <returns></returns>
        Private Shared Function CreateDynamicDisplayAdSettings(ByVal user As AdWordsUser) _
            As DynamicSettings
            Dim logoImageMediaId As Long = UploadImage(user, "https://goo.gl/dEvQeF")
            Dim logo As New Image()
            logo.mediaId = logoImageMediaId

            Dim dynamicSettings As New DynamicSettings()
            dynamicSettings.landscapeLogoImage = logo
            dynamicSettings.pricePrefix = "as low as"
            dynamicSettings.promoText = "Free shipping!"
            Return dynamicSettings
        End Function

        ''' <summary>
        ''' Uploads the image from the specified <paramref name="url"/>.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="url">The image URL.</param>
        ''' <returns>ID of the uploaded image.</returns>
        Private Shared Function UploadImage(ByVal user As AdWordsUser, ByVal url As String) As Long
            Using mediaService As MediaService = CType(
                user.GetService(
                    AdWordsService.v201809.MediaService),
                MediaService)

                ' Create the image.
                Dim image As New Image()
                image.data = MediaUtilities.GetAssetDataFromUrl(url, user.Config)
                image.type = MediaMediaType.IMAGE

                ' Upload the image.
                Return mediaService.upload(New Media() {image})(0).mediaId
            End Using
        End Function
    End Class
End Namespace

Add a Shopping dynamic remarketing campaign

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example adds a Shopping dynamic remarketing campaign for the Display Network
    ''' via the following steps:
    ''' <list type="bullet">
    '''   <item>
    '''     <description>Creates a new Display Network campaign.</description>
    '''   </item>
    '''   <item>
    '''     <description>Links the campaign with Merchant Center.</description>
    '''   </item>
    '''   <item>
    '''     <description>Links the user list to the ad group.</description>
    '''   </item>
    '''   <item>
    '''     <description>Creates a responsive display ad to render the dynamic text.</description>
    '''   </item>
    ''' </list>
    ''' </summary>
    Public Class AddShoppingDynamicRemarketingCampaign
        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 AddShoppingDynamicRemarketingCampaign
            Console.WriteLine(codeExample.Description)
            Try
                ' The ID of the merchant center account from which to source product feed data.
                Dim merchantId As Long = Long.Parse("INSERT_MERCHANT_CENTER_ID_HERE")

                ' The ID of a shared budget to associate with the campaign.
                Dim budgetId As Long = Long.Parse("INSERT_BUDGET_ID_HERE")

                ' The ID of a user list to target.
                Dim userListId As Long = Long.Parse("INSERT_USER_LIST_ID_HERE")
                codeExample.Run(New AdWordsUser(), merchantId, budgetId, userListId)
            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 Shopping dynamic remarketing campaign for the " &
                       "Display Network via the following steps:\n" &
                       "*  Creates a new Display Network campaign.\n" &
                       "*  Links the campaign with Merchant Center.\n" &
                       "*  Links the user list to the ad group.\n" +
                       "*  Creates a responsive display ad to render the dynamic text."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="merchantId">The ID of the merchant center account from which to source
        ''' product feed data.</param>
        ''' <param name="budgetId">The ID of a shared budget to associate with the campaign.</param>
        ''' <param name="userListId">The ID of a user list to target.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal merchantId As Long, ByVal budgetId As Long,
                       ByVal userListId As Long)
            Try
                Dim campaign As Campaign = CreateCampaign(user, merchantId, budgetId)
                Console.WriteLine("Campaign with name '{0}' and ID {1} was added.",
                                  campaign.name, campaign.id)

                Dim adGroup As AdGroup = CreateAdGroup(user, campaign)
                Console.WriteLine("Ad group with name '{0}' and ID {1} was added.",
                                  adGroup.name, adGroup.id)

                Dim adGroupAd As AdGroupAd = CreateAd(user, adGroup)
                Console.WriteLine("Responsive display ad with ID {0} was added.", adGroupAd.ad.id)

                AttachUserList(user, adGroup, userListId)
                Console.WriteLine("User list with ID {0} was attached to ad group with ID {1}.",
                                  userListId, adGroup.id)
            Catch e As Exception
                Throw _
                    New System.ApplicationException(
                        "Failed to create Shopping dynamic remarketing " +
                        "campaign for the Display Network.", e)
            End Try
        End Sub

        ''' <summary>
        ''' Creates a Shopping dynamic remarketing campaign object (not including ad group level and
        ''' below). This creates a Display campaign with the merchant center feed attached.
        ''' Merchant Center is used for the product information in combination with a user list
        ''' which contains hits with <code>ecomm_prodid</code> specified. See
        ''' <a href="https://developers.google.com/adwords-remarketing-tag/parameters#retail">
        ''' the guide</a> for more detail.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="merchantId">The ID of the Merchant Center account.</param>
        ''' <param name="budgetId">The ID of the budget to use for the campaign.</param>
        ''' <returns>The campaign that was created.</returns>
        Private Shared Function CreateCampaign(ByVal user As AdWordsUser, ByVal merchantId As Long,
                                               ByVal budgetId As Long) As Campaign
            Using campaignService As CampaignService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.CampaignService),
                CampaignService)
                Dim campaign As New Campaign()
                campaign.name = "Shopping campaign #" + ExampleUtilities.GetRandomString()
                ' Dynamic remarketing campaigns are only available on the Google Display Network.
                campaign.advertisingChannelType = AdvertisingChannelType.DISPLAY
                campaign.status = CampaignStatus.PAUSED

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

                ' This example uses a Manual CPC bidding strategy, but you should select the
                ' strategy that best aligns with your sales goals. More details here:
                '   https://support.google.com/adwords/answer/2472725
                Dim biddingStrategyConfiguration As New BiddingStrategyConfiguration()
                biddingStrategyConfiguration.biddingStrategyType = BiddingStrategyType.MANUAL_CPC
                campaign.biddingStrategyConfiguration = biddingStrategyConfiguration

                Dim setting As New ShoppingSetting()
                ' Campaigns with numerically higher priorities take precedence over those with lower
                ' priorities.
                setting.campaignPriority = 0

                ' Set the Merchant Center account ID from which to source products.
                setting.merchantId = merchantId

                ' Display Network campaigns do not support partition by country. The only supported
                ' value is "ZZ". This signals that products from all countries are available in the
                ' campaign. The actual products which serve are based on the products tagged in the
                ' user list entry.
                setting.salesCountry = "ZZ"

                ' Optional: Enable local inventory ads (items for sale in physical stores.)
                setting.enableLocal = True

                campaign.settings = New Setting() {setting}

                Dim op As New CampaignOperation()
                op.operand = campaign
                op.operator = [Operator].ADD

                Dim result As CampaignReturnValue = campaignService.mutate(
                    New CampaignOperation() _
                                                                              {op})
                Return result.value(0)
            End Using
        End Function

        ''' <summary>
        ''' Creates an ad group in the specified campaign.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="campaign">The campaign to which the ad group should be attached.</param>
        ''' <returns>The ad group that was created.</returns>
        Private Shared Function CreateAdGroup(ByVal user As AdWordsUser,
                                              ByVal campaign As Campaign) _
            As AdGroup
            Using adGroupService As AdGroupService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.AdGroupService),
                AdGroupService)
                Dim group As New AdGroup()
                group.name = "Dynamic remarketing ad group"
                group.campaignId = campaign.id
                group.status = AdGroupStatus.ENABLED

                Dim op As New AdGroupOperation()
                op.operand = group
                op.operator = [Operator].ADD
                Dim result As AdGroupReturnValue = adGroupService.mutate(
                    New AdGroupOperation() {op})
                Return result.value(0)
            End Using
        End Function

        ''' <summary>
        ''' Attach a user list to an ad group. The user list provides positive targeting and feed
        ''' information to drive the dynamic content of the ad.
        ''' </summary>
        ''' <param name="user">The user.</param>
        ''' <param name="adGroup">The ad group which will have the user list attached.</param>
        ''' <param name="userListId">The user list to use for targeting and dynamic content.</param>
        ''' <remarks>User lists must be attached at the ad group level for positive targeting in
        ''' Shopping dynamic remarketing campaigns.</remarks>
        Private Shared Sub AttachUserList(ByVal user As AdWordsUser, ByVal adGroup As AdGroup,
                                          ByVal userListId As Long)
            Using adGroupCriterionService As AdGroupCriterionService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.AdGroupCriterionService),
                AdGroupCriterionService)
                Dim userList As New CriterionUserList()
                userList.userListId = userListId
                Dim adGroupCriterion As New BiddableAdGroupCriterion()
                adGroupCriterion.criterion = userList
                adGroupCriterion.adGroupId = adGroup.id

                Dim op As New AdGroupCriterionOperation()
                op.operand = adGroupCriterion
                op.operator = [Operator].ADD

                adGroupCriterionService.mutate(New AdGroupCriterionOperation() {op})
            End Using
        End Sub

        ''' <summary>
        ''' Creates an ad for serving dynamic content in a remarketing campaign.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="adGroup">The ad group under which to create the ad.</param>
        ''' <returns>The ad that was created.</returns>
        Private Shared Function CreateAd(ByVal user As AdWordsUser, ByVal adGroup As AdGroup) _
            As AdGroupAd
            Using adService As AdGroupAdService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.AdGroupAdService),
                AdGroupAdService)
                Dim ad 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.
                ad.marketingImage = UploadImage(user, "https://goo.gl/3b9Wfh")

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

                ' Optional: Call to action text.
                ' Valid texts: https://support.google.com/adwords/answer/7005917
                ad.callToActionText = "Apply Now"

                ' Optional: Set dynamic display ad settings, composed of landscape logo
                ' image, promotion text, and price prefix.
                ad.dynamicDisplayAdSettings = CreateDynamicDisplayAdSettings(user)

                ' Optional: Create a logo image and set it to the ad.
                ad.logoImage = UploadImage(user, "https://goo.gl/mtt54n")

                ' Optional: Create a square marketing image and set it to the ad.
                ad.squareMarketingImage = UploadImage(user, "https://goo.gl/mtt54n")

                ' Whitelisted accounts only: Set color settings using hexadecimal values.
                ' Set allowFlexibleColor to false if you want your ads to render by always
                ' using your colors strictly.
                ' ad.mainColor = "#0000ff"
                ' ad.accentColor = "#ffff00"
                ' ad.allowFlexibleColor = False

                ' Whitelisted accounts only: Set the format setting that the ad will be
                ' served in.
                ' ad.formatSetting = DisplayAdFormatSetting.NON_NATIVE

                Dim adGroupAd As New AdGroupAd()
                adGroupAd.ad = ad
                adGroupAd.adGroupId = adGroup.id

                Dim op As New AdGroupAdOperation()
                op.operand = adGroupAd
                op.operator = [Operator].ADD

                Dim result As AdGroupAdReturnValue = adService.mutate(New AdGroupAdOperation() {op})
                Return result.value(0)
            End Using
        End Function

        ''' <summary>
        ''' Creates the additional content (images, promo text, etc.) supported by dynamic ads.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <returns>The DynamicSettings object to be used.</returns>
        Private Shared Function CreateDynamicDisplayAdSettings(ByVal user As AdWordsUser) _
            As DynamicSettings
            Dim logo As Image = UploadImage(user, "https://goo.gl/dEvQeF")

            Dim dynamicSettings As New DynamicSettings()
            dynamicSettings.landscapeLogoImage = logo
            dynamicSettings.pricePrefix = "as low as"
            dynamicSettings.promoText = "Free shipping!"
            Return dynamicSettings
        End Function

        ''' <summary>
        ''' Uploads the image from the specified <paramref name="url"/>.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="url">The image URL.</param>
        ''' <returns>ID of the uploaded image.</returns>
        Private Shared Function UploadImage(ByVal user As AdWordsUser, ByVal url As String) As Image
            Using mediaService As MediaService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.MediaService),
                MediaService)
                ' Create the image.
                Dim image As New Image()
                image.data = MediaUtilities.GetAssetDataFromUrl(url, user.Config)
                image.type = MediaMediaType.IMAGE

                ' Upload the image And return the ID.
                Return DirectCast(mediaService.upload(New Media() {image})(0), Image)
            End Using
        End Function
    End Class
End Namespace

Add a universal app campaign

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <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)
            Using campaignService As CampaignService = CType(
                user.GetService(
                    AdWordsService.v201809.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.appVendor = MobileApplicationVendor.VENDOR_GOOGLE_MARKET
                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 20 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 Using
        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
            Using budgetService As BudgetService = CType(
                user.GetService(
                    AdWordsService.v201809.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 Using
        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)
            Using campaignCriterionService As CampaignCriterionService = CType(
                user.GetService(
                    AdWordsService.v201809.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 Using
        End Sub
    End Class
End Namespace

Create a negative broad match keywords list and attach it to a campaign

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <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
            Using sharedSetService As SharedSetService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.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 Using
        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()
            Using sharedSetService As SharedCriterionService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.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 Using
        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
            Using campaignSharedSetService As CampaignSharedSetService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.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 Using
        End Function
    End Class
End Namespace

Find and remove shared sets and shared set criteria

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' 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)
            Using campaignSharedSetService As CampaignSharedSetService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.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 Using
        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)
            Using sharedCriterionService As SharedCriterionService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.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 Using
        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

            Using sharedCriterionService As SharedCriterionService = DirectCast(
                user.GetService(
                    AdWordsService.v201809.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 Using
        End Sub
    End Class
End Namespace

Get ad group level bid modifiers

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' 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.
            Using adGroupBidModifierService As AdGroupBidModifierService = CType(
                user.GetService(
                    AdWordsService.v201809.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 Using
        End Sub
    End Class
End Namespace

Add a portfolio bidding strategy to a campaign

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

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

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example adds a portfolio bidding strategy and uses it to
    ''' construct a campaign.
    ''' </summary>
    Public Class UsePortfolioBiddingStrategy
        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 UsePortfolioBiddingStrategy
            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 portfolio bidding strategy and uses it to " &
                       "construct a campaign."
            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 biddingStrategyName As String = "Maximize Clicks " &
                                                ExampleUtilities.GetRandomString()
            Dim bidCeiling As Long = 2000000
            Dim spendTarget As Long = 20000000

            Dim budgetName As String = "Shared Interplanetary Budget #" &
                                       ExampleUtilities.GetRandomString()
            Dim budgetAmount As Long = 30000000

            Dim campaignName As String = "Interplanetary Cruise #" +
                                         ExampleUtilities.GetRandomString()

            Try
                Dim portfolioBiddingStrategy As SharedBiddingStrategy =
                        CreateBiddingStrategy(user, biddingStrategyName, bidCeiling, spendTarget)
                Console.WriteLine(
                    "Portfolio bidding strategy with name '{0}' and ID {1} of type {2} " &
                    "was created.", portfolioBiddingStrategy.name, portfolioBiddingStrategy.id,
                    portfolioBiddingStrategy.biddingScheme.BiddingSchemeType)

                Dim sharedBudget As Budget = CreateSharedBudget(user, budgetName, budgetAmount)

                Dim newCampaign As Campaign =
                        CreateCampaignWithBiddingStrategy(user,
                                                          campaignName,
                                                          portfolioBiddingStrategy.id,
                                                          sharedBudget.budgetId)

                Console.WriteLine(
                    "Campaign with name '{0}', ID {1} and bidding scheme ID {2} was " &
                    "created.", newCampaign.name, newCampaign.id,
                    newCampaign.biddingStrategyConfiguration.biddingStrategyId)

            Catch e As Exception
                Throw _
                    New System.ApplicationException(
                        "Failed to create campaign that uses portfolio " &
                        "bidding strategy.", e)
            End Try
        End Sub


        ''' <summary>
        ''' Creates the portfolio bidding strategy.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="name">The bidding strategy name.</param>
        ''' <param name="bidCeiling">The bid ceiling.</param>
        ''' <param name="spendTarget">The spend target.</param>
        ''' <returns>The bidding strategy object.</returns>
        Private Function CreateBiddingStrategy(ByVal user As AdWordsUser,
                                               ByVal name As String, ByVal bidCeiling As Long,
                                               ByVal spendTarget As Long) _
            As SharedBiddingStrategy
            Using biddingStrategyService As BiddingStrategyService = CType(
                user.GetService(
                    AdWordsService.v201809.BiddingStrategyService),
                BiddingStrategyService)
                ' Create a portfolio bidding strategy.
                Dim portfolioBiddingStrategy As New SharedBiddingStrategy()
                portfolioBiddingStrategy.name = name

                Dim biddingScheme As New TargetSpendBiddingScheme()
                ' Optionally set additional bidding scheme parameters.
                biddingScheme.bidCeiling = New Money()
                biddingScheme.bidCeiling.microAmount = bidCeiling

                biddingScheme.spendTarget = New Money()
                biddingScheme.spendTarget.microAmount = spendTarget

                portfolioBiddingStrategy.biddingScheme = biddingScheme

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

                Return _
                    biddingStrategyService.mutate(New BiddingStrategyOperation() {operation}).value(
                        0)
            End Using
        End Function

        ''' <summary>
        ''' Creates an explicit budget to be used only to create the Campaign.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="name">The budget name.</param>
        ''' <param name="amount">The budget amount.</param>
        ''' <returns>The budget object.</returns>
        Private Function CreateSharedBudget(ByVal user As AdWordsUser,
                                            ByVal name As String, ByVal amount As Long) As Budget
            Using budgetService As BudgetService = CType(
                user.GetService(
                    AdWordsService.v201809.BudgetService),
                BudgetService)

                ' Create a shared budget
                Dim budget As New Budget()
                budget.name = name
                budget.amount = New Money()
                budget.amount.microAmount = amount
                budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD
                budget.isExplicitlyShared = True

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

                ' Make the mutate request.
                Return budgetService.mutate(New BudgetOperation() {operation}).value(0)
            End Using
        End Function

        ''' <summary>
        ''' Creates the campaign with a portfolio bidding strategy.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="name">The campaign name.</param>
        ''' <param name="biddingStrategyId">The bidding strategy id.</param>
        ''' <param name="sharedBudgetId">The shared budget id.</param>
        ''' <returns>The campaign object.</returns>
        Private Function CreateCampaignWithBiddingStrategy(ByVal user As AdWordsUser,
                                                           ByVal name As String,
                                                           ByVal biddingStrategyId As Long,
                                                           ByVal sharedBudgetId As Long) _
            As Campaign
            Using campaignService As CampaignService = CType(
                user.GetService(
                    AdWordsService.v201809.CampaignService),
                CampaignService)

                ' Create campaign.
                Dim campaign As New Campaign()
                campaign.name = name
                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

                ' Set the budget.
                campaign.budget = New Budget()
                campaign.budget.budgetId = sharedBudgetId

                ' Set bidding strategy (required).
                Dim biddingStrategyConfiguration As New BiddingStrategyConfiguration()
                biddingStrategyConfiguration.biddingStrategyId = biddingStrategyId

                campaign.biddingStrategyConfiguration = biddingStrategyConfiguration

                ' Set network targeting (recommended).
                Dim networkSetting As New NetworkSetting()
                networkSetting.targetGoogleSearch = True
                networkSetting.targetSearchNetwork = True
                networkSetting.targetContentNetwork = True
                campaign.networkSetting = networkSetting

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

                Return campaignService.mutate(New CampaignOperation() {operation}).value(0)
            End Using
        End Function
    End Class
End Namespace