Optimization Samples

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

Get keyword traffic estimates

' 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 gets keyword traffic estimates.
    ''' </summary>
    Public Class EstimateKeywordTraffic
        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 EstimateKeywordTraffic
            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 gets keyword traffic estimates."
            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 trafficEstimatorService As TrafficEstimatorService = CType(
                user.GetService(
                    AdWordsService.v201809.TrafficEstimatorService),
                TrafficEstimatorService)

                ' Create keywords. Up to 2000 keywords can be passed in a single request.
                Dim keyword1 As New Keyword
                keyword1.text = "mars cruise"
                keyword1.matchType = KeywordMatchType.BROAD

                Dim keyword2 As New Keyword
                keyword2.text = "cheap cruise"
                keyword2.matchType = KeywordMatchType.PHRASE

                Dim keyword3 As New Keyword
                keyword3.text = "cruise"
                keyword3.matchType = KeywordMatchType.EXACT

                Dim keywords As Keyword() = New Keyword() {keyword1, keyword2, keyword3}

                ' Create a keyword estimate request for each keyword.
                Dim keywordEstimateRequests As New List(Of KeywordEstimateRequest)

                For Each keyword As Keyword In keywords
                    Dim keywordEstimateRequest As New KeywordEstimateRequest
                    keywordEstimateRequest.keyword = keyword
                    keywordEstimateRequests.Add(keywordEstimateRequest)
                Next

                ' Create negative keywords.
                Dim negativeKeyword1 As New Keyword
                negativeKeyword1.text = "moon walk"
                negativeKeyword1.matchType = KeywordMatchType.BROAD

                Dim negativeKeywordEstimateRequest As New KeywordEstimateRequest
                negativeKeywordEstimateRequest.keyword = negativeKeyword1
                negativeKeywordEstimateRequest.isNegative = True
                keywordEstimateRequests.Add(negativeKeywordEstimateRequest)

                ' Create ad group estimate requests.
                Dim adGroupEstimateRequest As New AdGroupEstimateRequest
                adGroupEstimateRequest.keywordEstimateRequests = keywordEstimateRequests.ToArray
                adGroupEstimateRequest.maxCpc = New Money
                adGroupEstimateRequest.maxCpc.microAmount = 1000000

                ' Create campaign estimate requests.
                Dim campaignEstimateRequest As New CampaignEstimateRequest
                campaignEstimateRequest.adGroupEstimateRequests = New AdGroupEstimateRequest() _
                    {adGroupEstimateRequest}

                ' See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
                ' for a detailed list of country codes.
                Dim countryCriterion As New Location
                countryCriterion.id = 2840 'US

                ' See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html
                ' for a detailed list of language codes.
                Dim languageCriterion As New Language
                languageCriterion.id = 1000 'en

                campaignEstimateRequest.criteria = New Criterion() _
                    {countryCriterion, languageCriterion}

                Try
                    ' Create the selector.
                    Dim selector As New TrafficEstimatorSelector
                    selector.campaignEstimateRequests =
                        New CampaignEstimateRequest() {campaignEstimateRequest}

                    ' Optional: Request a list of campaign level estimates segmented by platform.
                    selector.platformEstimateRequested = True

                    ' Get traffic estimates.
                    Dim result As TrafficEstimatorResult = trafficEstimatorService.get(selector)

                    ' Display the results.
                    If ((Not result Is Nothing) AndAlso (Not result.campaignEstimates Is Nothing) _
                        AndAlso (result.campaignEstimates.Length > 0)) Then
                        Dim campaignEstimate As CampaignEstimate = result.campaignEstimates(0)

                        ' Display the campaign level estimates segmented by platform.
                        If Not campaignEstimate.platformEstimates Is Nothing Then
                            For Each platformEstimate As PlatformCampaignEstimate In _
                                campaignEstimate.platformEstimates
                                Dim platformMessage As String =
                                        String.Format("Results for the platform with ID:" &
                                                      " {0} and name : {1}.",
                                                      platformEstimate.platform.id,
                                                      platformEstimate.platform.platformName)

                                DisplayMeanEstimates(platformMessage, platformEstimate.minEstimate,
                                                     platformEstimate.maxEstimate)
                            Next
                        End If

                        If ((Not campaignEstimate.adGroupEstimates Is Nothing) AndAlso
                            (campaignEstimate.adGroupEstimates.Length > 0)) Then
                            Dim adGroupEstimate As AdGroupEstimate =
                                    campaignEstimate.adGroupEstimates(0)

                            If (Not adGroupEstimate.keywordEstimates Is Nothing) Then
                                For i As Integer = 0 To adGroupEstimate.keywordEstimates.Length - 1
                                    Dim keyword As Keyword = keywordEstimateRequests.Item(i).keyword
                                    Dim keywordEstimate As KeywordEstimate =
                                            adGroupEstimate.keywordEstimates(i)

                                    If keywordEstimateRequests.Item(i).isNegative Then
                                        Continue For
                                    End If

                                    Dim kwdMessage As String =
                                            String.Format("Results for the keyword with" &
                                                          " text = '{0}' and match type = '{1}':",
                                                          keyword.text, keyword.matchType)
                                    DisplayMeanEstimates(kwdMessage, keywordEstimate.min,
                                                         keywordEstimate.max)
                                Next i
                            End If
                        End If
                    Else
                        Console.WriteLine("No traffic estimates were returned.")
                    End If
                Catch e As Exception
                    Throw _
                        New System.ApplicationException("Failed to retrieve traffic estimates.", e)
                End Try
            End Using
        End Sub

        ''' <summary>
        ''' Displays the mean estimates.
        ''' </summary>
        ''' <param name="message">The message to display.</param>
        ''' <param name="minEstimate">The minimum stats estimate.</param>
        ''' <param name="maxEstimate">The maximum stats estimate.</param>
        Private Sub DisplayMeanEstimates(ByVal message As String,
                                         ByVal minEstimate As StatsEstimate,
                                         ByVal maxEstimate As StatsEstimate)
            ' Find the mean of the min and max values.
            Dim meanAverageCpc As Long = 0L
            Dim meanAveragePosition As Double = 0
            Dim meanClicks As Single = 0
            Dim meanTotalCost As Single = 0

            If (Not (minEstimate Is Nothing) AndAlso Not (maxEstimate Is Nothing)) Then
                If (Not (minEstimate.averageCpc Is Nothing) AndAlso
                    Not (maxEstimate.averageCpc Is Nothing)) Then
                    meanAverageCpc = CLng((minEstimate.averageCpc.microAmount +
                                           maxEstimate.averageCpc.microAmount)/2)
                End If

                If minEstimate.averagePositionSpecified AndAlso
                   maxEstimate.averagePositionSpecified Then
                    meanAveragePosition =
                        (minEstimate.averagePosition + maxEstimate.averagePosition)/2
                End If

                If minEstimate.clicksPerDaySpecified AndAlso maxEstimate.clicksPerDaySpecified Then
                    meanClicks = (minEstimate.clicksPerDay + maxEstimate.clicksPerDay)/2
                End If
                If (Not (minEstimate.totalCost Is Nothing) AndAlso
                    Not (maxEstimate.totalCost Is Nothing)) Then
                    meanTotalCost = CLng((minEstimate.totalCost.microAmount +
                                          maxEstimate.totalCost.microAmount)/2)
                End If
            End If

            Console.WriteLine(message)
            Console.WriteLine("  Estimated average CPC: {0}", meanAverageCpc)
            Console.WriteLine("  Estimated ad position: {0:0.00}", meanAveragePosition)
            Console.WriteLine("  Estimated daily clicks: {0}", meanClicks)
            Console.WriteLine("  Estimated daily cost: {0}", meanTotalCost)
        End Sub
    End Class
End Namespace

Get bid landscapes for 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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example gets bid landscapes for an ad group. To get ad groups,
    ''' run GetAdGroups.vb.
    ''' </summary>
    Public Class GetAdGroupBidSimulations
        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 GetAdGroupBidSimulations
            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 gets bid landscapes for 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 for which bid simulations are
        ''' retrieved.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long)
            Using dataService As DataService = CType(
                user.GetService(
                    AdWordsService.v201809.DataService),
                DataService)

                ' Create the selector.
                Dim selector As New Selector
                selector.fields = New String() { _
                                                   AdGroupBidLandscape.Fields.AdGroupId,
                                                   AdGroupBidLandscape.Fields.LandscapeType,
                                                   AdGroupBidLandscape.Fields.LandscapeCurrent,
                                                   AdGroupBidLandscape.Fields.StartDate,
                                                   AdGroupBidLandscape.Fields.EndDate,
                                                   BidLandscapeLandscapePoint.Fields.Bid,
                                                   BidLandscapeLandscapePoint.Fields.LocalClicks,
                                                   BidLandscapeLandscapePoint.Fields.LocalCost,
                                                   BidLandscapeLandscapePoint.Fields.
                                                       LocalImpressions
                                               }

                ' Set the filters.
                Dim adGroupPredicate As New Predicate
                adGroupPredicate.field = "AdGroupId"
                adGroupPredicate.operator = PredicateOperator.IN
                adGroupPredicate.values = New String() {adGroupId.ToString}

                selector.predicates = New Predicate() { _
                                                          Predicate.Equals(
                                                              AdGroupBidLandscape.Fields.AdGroupId,
                                                              adGroupId)
                                                      }

                Try
                    ' Get bid landscape for ad group.
                    Dim page As AdGroupBidLandscapePage =
                            dataService.getAdGroupBidLandscape(selector)
                    If (((Not page Is Nothing) AndAlso (Not page.entries Is Nothing)) AndAlso
                        (page.entries.Length > 0)) Then
                        For Each bidLandscape As AdGroupBidLandscape In page.entries
                            Console.WriteLine(
                                "Found ad group bid landscape with ad group id '{0}', " &
                                "type '{1}', current: '{2}', start date '{3}', end date '{4}', " &
                                "and landscape points", bidLandscape.adGroupId, bidLandscape.type,
                                bidLandscape.landscapeCurrent, bidLandscape.startDate,
                                bidLandscape.endDate)
                            Dim point As BidLandscapeLandscapePoint
                            For Each point In bidLandscape.landscapePoints
                                Console.WriteLine(
                                    "- bid: {0} => clicks: {1}, cost: {2}, impressions: {3}",
                                    point.bid.microAmount, point.bid.microAmount,
                                    point.clicks, point.cost.microAmount, point.impressions)
                            Next
                        Next
                    Else
                        Console.WriteLine("No ad group bid landscapes were found.\n")
                    End If
                Catch e As Exception
                    Throw _
                        New System.ApplicationException("Failed to get ad group bid landscapes.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Get all mobile bid modifier landscapes for 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 gets all available campaign mobile bid modifier
    ''' landscapes for a given campaign. To get campaigns, run GetCampaigns.cs.
    ''' </summary>
    Public Class GetCampaignCriterionBidModifierSimulations
        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 GetCampaignCriterionBidModifierSimulations
            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 gets all available campaign mobile bid modifier landscapes" &
                    " for a given campaign. To get 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 for which bid simulations are
        ''' retrieved.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long)
            Using _
                dataService As DataService =
                    CType(user.GetService(AdWordsService.v201809.DataService), DataService)

                ' Create selector.
                Dim selector As New Selector()
                selector.fields = New String() { _
                                                   CriterionBidLandscape.Fields.CampaignId,
                                                   CriterionBidLandscape.Fields.CriterionId,
                                                   CriterionBidLandscape.Fields.StartDate,
                                                   CriterionBidLandscape.Fields.EndDate,
                                                   BidLandscapeLandscapePoint.Fields.LocalClicks,
                                                   BidLandscapeLandscapePoint.Fields.LocalCost,
                                                   BidLandscapeLandscapePoint.Fields.
                                                       LocalImpressions,
                                                   BidLandscapeLandscapePoint.Fields.
                                                       TotalLocalClicks,
                                                   BidLandscapeLandscapePoint.Fields.TotalLocalCost,
                                                   BidLandscapeLandscapePoint.Fields.
                                                       TotalLocalImpressions,
                                                   BidLandscapeLandscapePoint.Fields.RequiredBudget,
                                                   BidLandscapeLandscapePoint.Fields.BidModifier
                                               }
                selector.predicates =
                    New Predicate() { _
                                        Predicate.Equals(
                                            CriterionBidLandscape.Fields.CampaignId, campaignId)
                                    }
                selector.paging = Paging.Default

                Dim landscapePointsInLastResponse As Integer = 0
                Dim landscapePointsFound As Integer = 0

                Try
                    Dim page As CriterionBidLandscapePage = Nothing

                    Do
                        ' When retrieving bid landscape, page.totalNumEntities cannot be used to
                        ' determine if there are more entries, since it shows only the total number
                        ' of bid landscapes and not the number of bid landscape points. So you need
                        ' to iterate until you no longer get back any bid landscapes.

                        ' Get bid landscape for campaign.
                        page = dataService.getCampaignCriterionBidLandscape(selector)
                        landscapePointsInLastResponse = 0

                        If (Not page Is Nothing) AndAlso (Not page.entries Is Nothing) Then
                            For Each bidLandscape As CriterionBidLandscape In page.entries
                                Console.WriteLine(
                                    "Found campaign-level criterion bid modifier landscapes for" &
                                    " criterion with ID {0}, start date '{1}', end date '{2}', " &
                                    "and landscape points:",
                                    bidLandscape.criterionId,
                                    bidLandscape.startDate,
                                    bidLandscape.endDate
                                    )

                                For Each point As BidLandscapeLandscapePoint In _
                                    bidLandscape.landscapePoints
                                    Console.WriteLine(
                                        "- bid modifier: {0:0.00} => clicks: {1}, cost: {2}, " &
                                        "impressions: {3}, total clicks: {4}, total cost: {5}, " &
                                        "total impressions: {6}, and required budget: {7}",
                                        point.bidModifier, point.clicks, point.cost.microAmount,
                                        point.impressions, point.totalLocalClicks,
                                        point.totalLocalCost.microAmount,
                                        point.totalLocalImpressions,
                                        point.requiredBudget.microAmount)
                                    landscapePointsInLastResponse += 1
                                    landscapePointsFound += 1
                                Next
                            Next
                        End If
                        ' Offset by the number of landscape points, NOT the number
                        ' of entries (bid landscapes) in the last response.
                        selector.paging.IncreaseOffsetBy(landscapePointsInLastResponse)
                    Loop While landscapePointsInLastResponse > 0
                    Console.WriteLine("Number of bid landscape points found: {0}",
                                      landscapePointsFound)
                Catch e As Exception
                    Throw _
                        New System.ApplicationException(
                            "Failed to retrieve campaign bid landscapes.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Get a bid landscape for an ad group and criterion

' 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.Util.Reports.v201809
Imports Google.Api.Ads.AdWords.v201809

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example gets a bid landscape for an ad group and a keyword.
    ''' To get ad groups, run GetAdGroups.vb. To get keywords, run
    ''' GetKeywords.vb.
    ''' </summary>
    Public Class GetKeywordBidSimulations
        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 GetKeywordBidSimulations
            Console.WriteLine(codeExample.Description)
            Try
                Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
                Dim keywordId As Long = Long.Parse("INSERT_KEYWORD_ID_HERE")
                codeExample.Run(New AdWordsUser, adGroupId, keywordId)
            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 gets a bid landscape for an ad group and a keyword. To " &
                       "get ad groups, run GetAdGroups.vb. To get keywords, run GetKeywords.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 for which keyword bid
        ''' simulations are retrieved.</param>
        ''' <param name="keywordId">Id of the keyword for which bid simulations are
        ''' retrieved.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long, ByVal keywordId As Long)
            Using dataService As DataService = CType(
                user.GetService(
                    AdWordsService.v201809.DataService),
                DataService)

                ' Create the query.
                Dim query As SelectQuery = New SelectQueryBuilder().Select(
                    CriterionBidLandscape.Fields.AdGroupId,
                    CriterionBidLandscape.Fields.CriterionId,
                    CriterionBidLandscape.Fields.StartDate,
                    CriterionBidLandscape.Fields.EndDate,
                    BidLandscapeLandscapePoint.Fields.Bid,
                    BidLandscapeLandscapePoint.Fields.LocalClicks,
                    BidLandscapeLandscapePoint.Fields.LocalCost,
                    BidLandscapeLandscapePoint.Fields.LocalImpressions,
                    BidLandscapeLandscapePoint.Fields.BiddableConversions,
                    BidLandscapeLandscapePoint.Fields.BiddableConversionsValue
                    ) _
                        .Where(CriterionBidLandscape.Fields.AdGroupId).Equals(adGroupId) _
                        .Where(CriterionBidLandscape.Fields.CriterionId).Equals(keywordId) _
                        .DefaultLimit() _
                        .Build()

                Dim page As New CriterionBidLandscapePage

                Dim landscapePointsFound As Integer = 0

                Try
                    Do
                        ' Get bid landscape for keywords.
                        page = dataService.queryCriterionBidLandscape(query)

                        ' Display bid landscapes.
                        If ((Not page Is Nothing) AndAlso (Not page.entries Is Nothing)) Then

                            For Each bidLandscape As CriterionBidLandscape In page.entries
                                Console.WriteLine(
                                    "Found keyword bid landscape with ad group id ""{0}"", " &
                                    "keyword id ""{1}"", start date ""{2}"", end date ""{3}"", " &
                                    "and landscape points:", bidLandscape.adGroupId,
                                    bidLandscape.criterionId, bidLandscape.startDate,
                                    bidLandscape.endDate)
                                For Each bidLandscapePoint As BidLandscapeLandscapePoint _
                                    In bidLandscape.landscapePoints
                                    Console.WriteLine(
                                        "- bid: {0} => clicks: {1}, cost: {2}, impressions: {3}, " &
                                        "biddable conversions: {4:0.00}, biddable conversions " &
                                        "value:{5:0.00}",
                                        bidLandscapePoint.bid.microAmount, bidLandscapePoint.clicks,
                                        bidLandscapePoint.cost.microAmount,
                                        bidLandscapePoint.impressions,
                                        bidLandscapePoint.biddableConversions,
                                        bidLandscapePoint.biddableConversionsValue)
                                    landscapePointsFound += 1
                                Next
                            Next
                        End If
                        query.NextPage(page)
                    Loop While (query.HasNextPage(page))
                    Console.WriteLine("Number of keyword bid landscape points found: {0}",
                                      landscapePointsFound)
                Catch e As Exception
                    Throw New _
                        System.ApplicationException("Failed to retrieve keyword bid landscapes.",
                                                    e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Get keywords related to a seed keyword

' 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 Attribute = Google.Api.Ads.AdWords.v201809.Attribute

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example retrieves keywords that are related to a given keyword.
    ''' </summary>
    Public Class GetKeywordIdeas
        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 GetKeywordIdeas
            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 retrieves keywords that are related to a given keyword."
            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 use for generating ideas.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long?)
            Using targetingIdeaService As TargetingIdeaService = CType(
                user.GetService(
                    AdWordsService.v201809.TargetingIdeaService),
                TargetingIdeaService)

                ' Create selector.
                Dim selector As New TargetingIdeaSelector()
                selector.requestType = RequestType.IDEAS
                selector.ideaType = IdeaType.KEYWORD
                selector.requestedAttributeTypes =
                    New AttributeType() { _
                                            AttributeType.KEYWORD_TEXT,
                                            AttributeType.SEARCH_VOLUME,
                                            AttributeType.CATEGORY_PRODUCTS_AND_SERVICES
                                        }

                Dim searchParameters As New List(Of SearchParameter)

                ' Create related to query search parameter.
                Dim relatedToQuerySearchParameter As New RelatedToQuerySearchParameter()
                relatedToQuerySearchParameter.queries = New String() { _
                                                                         "bakery", "pastries",
                                                                         "birthday cake"
                                                                     }
                searchParameters.Add(relatedToQuerySearchParameter)

                ' Add a language search parameter (optional).
                ' The ID can be found in the documentation:
                '   https://developers.google.com/adwords/api/docs/appendix/languagecodes
                Dim languageParameter As New LanguageSearchParameter()
                Dim english As New Language()
                english.id = 1000
                languageParameter.languages = New Language() {english}
                searchParameters.Add(languageParameter)

                ' Add network search parameter (optional).
                Dim networkSetting As New NetworkSetting()
                networkSetting.targetGoogleSearch = True
                networkSetting.targetSearchNetwork = False
                networkSetting.targetContentNetwork = False
                networkSetting.targetPartnerSearchNetwork = False

                Dim networkSearchParameter As New NetworkSearchParameter()
                networkSearchParameter.networkSetting = networkSetting
                searchParameters.Add(networkSearchParameter)

                ' Optional: Use an existing ad group to generate ideas.
                If adGroupId.HasValue() Then
                    Dim seedAdGroupIdSearchParameter As New SeedAdGroupIdSearchParameter()
                    seedAdGroupIdSearchParameter.adGroupId = adGroupId.Value
                    searchParameters.Add(seedAdGroupIdSearchParameter)
                End If

                ' Set the search parameters.
                selector.searchParameters = searchParameters.ToArray()


                ' Set selector paging (required for targeting idea service).
                selector.paging = Paging.Default

                Dim page As New TargetingIdeaPage()

                Try
                    Dim i As Integer = 0
                    Do
                        ' Get related keywords.
                        page = targetingIdeaService.get(selector)

                        'Display the results.
                        If Not page.entries Is Nothing AndAlso page.entries.Length > 0 Then
                            For Each targetingIdea As TargetingIdea In page.entries
                                For Each entry As Type_AttributeMapEntry In targetingIdea.data
                                    ' Preferred: Use targetingIdea.data.ToDict() if you are not on
                                    ' Mono.
                                    Dim ideas As Dictionary(Of AttributeType, Attribute) =
                                            MapEntryExtensions.ToDict (Of AttributeType, Attribute)(
                                                targetingIdea.data)

                                    Dim keyword As String =
                                            DirectCast(ideas(AttributeType.KEYWORD_TEXT),
                                                       StringAttribute).value
                                    Dim categorySet As IntegerSetAttribute =
                                            DirectCast(
                                                ideas(AttributeType.CATEGORY_PRODUCTS_AND_SERVICES),
                                                IntegerSetAttribute)

                                    Dim categories As String = ""

                                    If _
                                        (Not categorySet Is Nothing) AndAlso
                                        (Not categorySet.value Is Nothing) Then
                                        categories = String.Join(", ", categorySet.value)
                                    End If

                                    Dim averageMonthlySearches As Long =
                                            DirectCast(ideas(AttributeType.SEARCH_VOLUME),
                                                       LongAttribute).value


                                    Dim averageCpcMoney As Money =
                                            DirectCast(ideas(AttributeType.AVERAGE_CPC),
                                                       MoneyAttribute).value
                                    Dim averageCpc As Long
                                    If (Not averageCpcMoney Is Nothing) Then
                                        averageCpc = averageCpcMoney.microAmount
                                    End If

                                    Dim competition As Double =
                                            DirectCast(ideas(AttributeType.COMPETITION),
                                                       DoubleAttribute).value
                                    Console.WriteLine(
                                        "Keyword with text '{0}', average monthly search " +
                                        "volume {1}, average CPC {2}, and competition {3:F2} was " &
                                        "found with categories: {4}", keyword,
                                        averageMonthlySearches, averageCpc,
                                        competition, categories)
                                Next
                                i = i + 1
                            Next
                        End If
                        selector.paging.IncreaseOffset()
                    Loop While (selector.paging.startIndex < page.totalNumEntries)
                    Console.WriteLine("Number of related keywords found: {0}", page.totalNumEntries)
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to retrieve related keywords.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace