Campaign Management Samples

The code samples below provide examples for managing campaigns using the AdWords API. Client Library.

Add a campaign group and set its performance target

' 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 campaign group and sets a performance target for that group. To
    ''' get campaigns, run GetCampaigns.vb. To download reports, run
    ''' DownloadCriteriaReportWithAwql.vb.
    ''' </summary>
    Public Class AddCampaignGroupsAndPerformanceTargets
        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 AddCampaignGroupsAndPerformanceTargets
            Console.WriteLine(codeExample.Description)
            Try
                Dim campaignId1 As Long = Long.Parse("INSERT_CAMPAIGN_ID1_HERE")
                Dim campaignId2 As Long = Long.Parse("INSERT_CAMPAIGN_ID2_HERE")

                codeExample.Run(New AdWordsUser, campaignId1, campaignId2)
            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 campaign group and sets a performance target for " &
                    "that group. To get campaigns, run GetCampaigns.vb. To download reports, run" &
                    " DownloadCriteriaReportWithAwql.vb."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="campaignId1">Id of the campaign to be added to the campaign group.</param>
        ''' <param name="campaignId2">Id of the campaign to be added to the campaign group.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId1 As Long,
                       ByVal campaignId2 As Long)
            Dim campaignGroup As CampaignGroup = CreateCampaignGroup(user)
            AddCampaignsToGroup(user, campaignGroup.id, New Long() {campaignId1, campaignId2})
            CreatePerformanceTarget(user, campaignGroup.id)
            Console.WriteLine("Campaign group and its performance target were setup successfully.")
        End Sub

        ''' <summary>
        ''' Create a campaign group.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <returns>The campaign group.</returns>
        Private Function CreateCampaignGroup(ByVal user As AdWordsUser) As CampaignGroup
            Using campaignGroupService As CampaignGroupService = CType(
                user.GetService(
                    AdWordsService.v201809.CampaignGroupService),
                CampaignGroupService)

                ' Create the campaign group.
                Dim campaignGroup As New CampaignGroup()
                campaignGroup.name = "Mars campaign group - " +
                                     ExampleUtilities.GetShortRandomString()

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

                Try
                    Dim retval As CampaignGroupReturnValue = campaignGroupService.mutate(
                        New CampaignGroupOperation() {operation})

                    ' Display the results.
                    Dim newCampaignGroup As CampaignGroup = retval.value(0)
                    Console.WriteLine("Campaign group with ID = '{0}' and name = '{1}' was " &
                                      "created.", newCampaignGroup.id, newCampaignGroup.name)
                    Return newCampaignGroup
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to add campaign group.", e)
                End Try
            End Using
        End Function

        ''' <summary>
        ''' Adds multiple campaigns to a campaign group.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="campaignGroupId">The campaign group ID.</param>
        ''' <param name="campaignIds">IDs of the campaigns to be added to the campaign group.
        ''' </param>
        Private Sub AddCampaignsToGroup(ByVal user As AdWordsUser, ByVal campaignGroupId As Long,
                                        ByVal campaignIds() As Long)
            Using campaignService As CampaignService = CType(
                user.GetService(
                    AdWordsService.v201809.CampaignService),
                CampaignService)

                Dim operations As New List(Of CampaignOperation)

                For i As Integer = 0 To campaignIds.Length - 1
                    Dim campaign As New Campaign()
                    campaign.id = campaignIds(i)
                    campaign.campaignGroupId = campaignGroupId

                    Dim operation As New CampaignOperation()
                    operation.operand = campaign
                    operation.operator = [Operator].SET
                    operations.Add(operation)
                Next

                Try
                    Dim retval As CampaignReturnValue = campaignService.mutate(operations.ToArray())

                    Dim updatedCampaignIds As New List(Of Long)()
                    For Each updatedCampaign As Campaign In retval.value
                        updatedCampaignIds.Add(updatedCampaign.id)
                    Next

                    ' Display the results.
                    Console.WriteLine(
                        "The following campaign IDs were added to the campaign group " +
                        "with ID '{0}':\n\t{1}'", campaignGroupId, String.Join(", ", campaignIds))
                Catch e As Exception
                    Throw New _
                        System.ApplicationException("Failed to add campaigns to campaign group.",
                                                    e)
                End Try
            End Using
        End Sub

        ''' <summary>
        ''' Creates a performance target for the campaign group.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="campaignGroupId">Campaign group ID.</param>
        ''' <returns>The newly created performance target.</returns>
        Private Function CreatePerformanceTarget(ByVal user As AdWordsUser,
                                                 ByVal campaignGroupId As Long) _
            As CampaignGroupPerformanceTarget
            Using campaignGroupPerformanceTargetService As CampaignGroupPerformanceTargetService =
                CType(user.GetService(AdWordsService.v201809.CampaignGroupPerformanceTargetService),
                      CampaignGroupPerformanceTargetService)

                ' Create the performance target.
                Dim campaignGroupPerformanceTarget As New CampaignGroupPerformanceTarget()
                campaignGroupPerformanceTarget.campaignGroupId = campaignGroupId

                Dim performanceTarget As New PerformanceTarget()
                ' Keep the CPC for the campaigns <$3.
                performanceTarget.efficiencyTargetType =
                    EfficiencyTargetType.CPC_LESS_THAN_OR_EQUAL_TO
                performanceTarget.efficiencyTargetValue = 3000000

                ' Keep the maximum spend under $50.
                performanceTarget.spendTargetType = SpendTargetType.MAXIMUM
                Dim maxSpend As New Money()
                maxSpend.microAmount = 500000000
                performanceTarget.spendTarget = maxSpend

                ' Aim for at least 3000 clicks.
                performanceTarget.volumeTargetValue = 3000
                performanceTarget.volumeGoalType = VolumeGoalType.MAXIMIZE_CLICKS

                ' Start the performance target today, And run it for the next 90 days.
                Dim startDate As System.DateTime = System.DateTime.Now
                Dim endDate As System.DateTime = startDate.AddDays(90)

                performanceTarget.startDate = startDate.ToString("yyyyMMdd")
                performanceTarget.endDate = endDate.ToString("yyyyMMdd")

                campaignGroupPerformanceTarget.performanceTarget = performanceTarget

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

                Try
                    Dim retval As CampaignGroupPerformanceTargetReturnValue =
                            campaignGroupPerformanceTargetService.mutate(
                                New CampaignGroupPerformanceTargetOperation() {operation})

                    ' Display the results.
                    Dim newCampaignPerfTarget As CampaignGroupPerformanceTarget = retval.value(0)

                    Console.WriteLine("Campaign performance target with id = '{0}' was added for " +
                                      "campaign group ID '{1}'.", newCampaignPerfTarget.id,
                                      newCampaignPerfTarget.campaignGroupId)
                    Return newCampaignPerfTarget
                Catch e As Exception
                    Throw _
                        New System.ApplicationException(
                            "Failed to create campaign performance target.", e)
                End Try
            End Using
        End Function

    End Class
End Namespace

Add a label to multiple campaigns

' 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 label to multiple campaigns.
    ''' </summary>
    Public Class AddCampaignLabels
        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 AddCampaignLabels
            Console.WriteLine(codeExample.Description)
            Try
                Dim campaignId1 As Long = Long.Parse("INSERT_CAMPAIGN_ID1_HERE")
                Dim campaignId2 As Long = Long.Parse("INSERT_CAMPAIGN_ID2_HERE")
                Dim labelId As Long = Long.Parse("INSERT_LABEL_ID_HERE")

                codeExample.Run(New AdWordsUser, campaignId1, campaignId2, labelId)
            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 label to multiple campaigns."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="campaignId1">Id of the campaign to which labels are
        ''' added.</param>
        ''' <param name="campaignId2">Id of the ad group to which labels are
        ''' added.</param>
        ''' <param name="labelId">ID of the label to apply.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId1 As Long,
                       ByVal campaignId2 As Long, ByVal labelId As Long)
            Using campaignService As CampaignService = CType(
                user.GetService(
                    AdWordsService.v201809.CampaignService),
                CampaignService)
                ' Create label operations.
                Dim operations As New List(Of CampaignLabelOperation)

                For Each campaignId As Long In New Long() {campaignId1, campaignId2}
                    Dim campaignLabel As New CampaignLabel
                    campaignLabel.campaignId = campaignId
                    campaignLabel.labelId = labelId

                    Dim operation As New CampaignLabelOperation
                    operation.operand = campaignLabel
                    operation.operator = [Operator].ADD

                    operations.Add(operation)
                Next

                Try
                    Dim retval As CampaignLabelReturnValue = campaignService.mutateLabel(
                        operations.ToArray())

                    ' Display campaign labels.
                    If Not (retval Is Nothing) AndAlso Not (retval.value Is Nothing) Then
                        For Each newCampaignLabel As CampaignLabel In retval.value
                            Console.WriteLine(
                                "Campaign label for campaign ID {0} and label ID {1} was added.\n",
                                newCampaignLabel.campaignId, newCampaignLabel.labelId)
                        Next
                    Else
                        Console.WriteLine("No campaign labels were added.")
                    End If
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to add campaign labels.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Add a campaign using BatchJobService

' 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 System.Threading
Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.Util.BatchJob.v201809
Imports Google.Api.Ads.AdWords.v201809

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example illustrates how to use BatchJobService to create multiple
    ''' complete campaigns, including ad groups and keywords.
    ''' </summary>
    Public Class AddCompleteCampaignsUsingBatchJob
        Inherits ExampleBase

        ''' <summary>
        ''' The last ID that was automatically generated.
        ''' </summary>
        Private Shared LAST_ID As Long = - 1

        ''' <summary>
        ''' The number of campaigns to be added.
        ''' </summary>
        Private Const NUMBER_OF_CAMPAIGNS_TO_ADD As Long = 2

        ''' <summary>
        ''' The number of ad groups to be added per campaign.
        ''' </summary>
        Private Const NUMBER_OF_ADGROUPS_TO_ADD As Long = 2

        ''' <summary>
        ''' The number of keywords to be added per campaign.
        ''' </summary>
        Private Const NUMBER_OF_KEYWORDS_TO_ADD As Long = 5

        ''' <summary>
        ''' The maximum milliseconds to wait for completion.
        ''' </summary>
        Private Const TIME_TO_WAIT_FOR_COMPLETION As Integer = 15*60*1000 ' 15 minutes

        ''' <summary>
        ''' Create a temporary ID generator that will produce a sequence of descending
        ''' negative numbers.
        ''' </summary>
        ''' <returns></returns>
        Private Shared Function NextId() As Long
            Return Interlocked.Decrement(LAST_ID)
        End Function

        ''' <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 AddCompleteCampaignsUsingBatchJob
            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 illustrates how to use BatchJobService to create multiple" &
                    " complete campaigns, including ad groups and keywords."
            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 batchJobService As BatchJobService = CType(
                user.GetService(
                    AdWordsService.v201809.BatchJobService),
                BatchJobService)

                Try
                    ' Create a BatchJob.
                    Dim addOp As New BatchJobOperation()
                    addOp.operator = [Operator].ADD
                    addOp.operand = New BatchJob()

                    Dim batchJob As BatchJob = batchJobService.mutate(
                        New BatchJobOperation() {addOp}).value(0)

                    ' Get the upload URL from the new job.
                    Dim uploadUrl As String = batchJob.uploadUrl.url

                    Console.WriteLine(
                        "Created BatchJob with ID {0}, status '{1}' and upload URL {2}.",
                        batchJob.id, batchJob.status, batchJob.uploadUrl.url)

                    ' Create the mutate request that will be sent to the upload URL.
                    Dim operations As New List(Of Operation)()

                    ' Create and add an operation to create a new budget.
                    Dim budgetOperation As BudgetOperation = BuildBudgetOperation()
                    operations.Add(budgetOperation)

                    ' Create and add operations to create new campaigns.
                    Dim campaignOperations As List(Of CampaignOperation) =
                            BuildCampaignOperations(budgetOperation.operand.budgetId)
                    operations.AddRange(campaignOperations.ToArray())

                    Dim adGroupOperations As New List(Of AdGroupOperation)()

                    ' Create and add operations to create new ad groups.
                    For Each campaignOperation As CampaignOperation In campaignOperations
                        adGroupOperations.AddRange(
                            BuildAdGroupOperations(campaignOperation.operand.id))
                    Next
                    operations.AddRange(adGroupOperations.ToArray())

                    ' Create and add operations to create new ad group ads (expanded text ads).
                    For Each adGroupOperation As AdGroupOperation In adGroupOperations
                        operations.AddRange(
                            BuildAdGroupAdOperations(adGroupOperation.operand.id).ToArray())
                    Next

                    ' Create and add operations to create new ad group criteria (keywords).
                    For Each adGroupOperation As AdGroupOperation In adGroupOperations
                        operations.AddRange(BuildAdGroupCriterionOperations(
                            adGroupOperation.operand.id).ToArray())
                    Next

                    Dim batchJobUploadHelper As New BatchJobUtilities(user)

                    ' Create a resumable Upload URL to upload the operations.
                    Dim resumableUploadUrl As String =
                            batchJobUploadHelper.GetResumableUploadUrl(uploadUrl)

                    ' Use the BatchJobUploadHelper to upload all operations.
                    batchJobUploadHelper.Upload(resumableUploadUrl, operations.ToArray())

                    Dim waitHandler As WaitHandler

                    ' Create a wait handler.
                    waitHandler = New WaitHandler(batchJob, False)

                    Dim isComplete As Boolean = batchJobUploadHelper.WaitForPendingJob(
                        batchJob.id,
                        TIME_TO_WAIT_FOR_COMPLETION,
                        AddressOf waitHandler.OnJobWaitForCompletion)

                    ' Restore the latest value for batchJob from waithandler.
                    batchJob = waitHandler.Job

                    If Not isComplete Then
                        Throw _
                            New TimeoutException(
                                "Job is still in pending state after waiting for " &
                                TIME_TO_WAIT_FOR_COMPLETION & " seconds.")
                    End If

                    If Not (batchJob.processingErrors Is Nothing) Then
                        For Each processingError As BatchJobProcessingError In _
                            batchJob.processingErrors
                            Console.WriteLine("  Processing error: {0}, {1}, {2}, {3}, {4}",
                                              processingError.ApiErrorType,
                                              processingError.trigger,
                                              processingError.errorString,
                                              processingError.fieldPath,
                                              processingError.reason)
                        Next
                    End If

                    If (Not (batchJob.downloadUrl Is Nothing)) AndAlso
                       (Not (batchJob.downloadUrl.url Is Nothing)) Then
                        Dim mutateResponse As BatchJobMutateResponse =
                                batchJobUploadHelper.Download(batchJob.downloadUrl.url)
                        Console.WriteLine("Downloaded results from {0}.", batchJob.downloadUrl.url)
                        For Each mutateResult As MutateResult In mutateResponse.rval
                            Dim outcome As String = ""
                            If mutateResult.errorList Is Nothing Then
                                outcome = "SUCCESS"
                            Else
                                outcome = "FAILURE"
                            End If
                            Console.WriteLine("  Operation [{0}] - {1}",
                                              mutateResult.index,
                                              outcome)
                        Next
                    End If
                Catch e As Exception
                    Throw _
                        New System.ApplicationException("Failed to add campaigns using batch job.",
                                                        e)
                End Try
            End Using
        End Sub

        ''' <summary>
        ''' A class that handles wait callbacks for the batch job.
        ''' </summary>
        Class WaitHandler
            ''' <summary>
            ''' The batch job to wait for.
            ''' </summary>
            Private batchJob As BatchJob

            ''' <summary>
            ''' A flag to determine if the job was requested to be cancelled. This
            ''' typically comes from the user.
            ''' </summary>
            Private cancelRequested As Boolean

            ''' <summary>
            ''' Initializes a new instance of the <see cref="WaitHandler"/> class.
            ''' </summary>
            ''' <param name="batchJob">The batch job to wait for.</param>
            ''' <param name="wasCancelRequested">A flag to determine if the job was
            ''' requested to be cancelled. This typically comes from the user.</param>
            Sub New(ByVal batchJob As BatchJob, ByVal wasCancelRequested As Boolean)
                Me.batchJob = batchJob
                Me.WasCancelRequested = wasCancelRequested
            End Sub

            ''' <summary>
            ''' Gets or sets the batch job to wait for.
            ''' </summary>
            Public Property Job As BatchJob
                Get
                    Return Me.batchJob
                End Get
                Set(value As BatchJob)
                    Me.batchJob = value
                End Set
            End Property

            ''' <summary>
            ''' Gets or sets a flag to determine if the job was requested to be
            ''' cancelled. This typically comes from the user.
            ''' </summary>
            Public Property WasCancelRequested As Boolean
                Get
                    Return Me.cancelRequested
                End Get
                Set(value As Boolean)
                    Me.cancelRequested = value
                End Set
            End Property

            ''' <summary>
            ''' Callback method when the job is waiting for cancellation.
            ''' </summary>
            ''' <param name="waitBatchJob">The updated batch job being waited for.</param>
            ''' <param name="timeElapsed">The time elapsed.</param>
            ''' <returns>True, if the wait loop should be cancelled, false otherwise.
            '''</returns>
            Public Function OnJobWaitForCancellation(ByVal waitBatchJob As BatchJob,
                                                     ByVal timeElapsed As Long) As Boolean
                Console.WriteLine("[{0} seconds]: Batch job ID {1} has status '{2}'.",
                                  timeElapsed/1000, waitBatchJob.id, waitBatchJob.status)
                batchJob = waitBatchJob
                Return False
            End Function

            ''' <summary>
            ''' Callback method when the job is waiting for completion.
            ''' </summary>
            ''' <param name="waitBatchJob">The updated batch job being waited for.</param>
            ''' <param name="timeElapsed">The time elapsed.</param>
            ''' <returns>True, if the wait loop should be cancelled, false otherwise.
            '''</returns>
            Public Function OnJobWaitForCompletion(ByVal waitBatchJob As BatchJob,
                                                   ByVal timeElapsed As Long) As Boolean
                Console.WriteLine("[{0} seconds]: Batch job ID {1} has status '{2}'.",
                                  timeElapsed/1000, waitBatchJob.id, waitBatchJob.status)
                batchJob = waitBatchJob
                Return Me.WasCancelRequested
            End Function
        End Class

        ''' <summary>
        ''' Builds the operation for creating an ad within an ad group.
        ''' </summary>
        ''' <param name="adGroupId">ID of the ad group for which ads are created.</param>
        ''' <returns>A list of operations for creating ads.</returns>
        Private Shared Function BuildAdGroupAdOperations(ByVal adGroupId As Long) _
            As List(Of AdGroupAdOperation)
            Dim operations As New List(Of AdGroupAdOperation)()

            Dim adGroupAd As New AdGroupAd()
            adGroupAd.adGroupId = adGroupId

            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!"
            expandedTextAd.finalUrls = New String() {"http://www.example.com/1"}
            adGroupAd.ad = expandedTextAd

            Dim operation As New AdGroupAdOperation()
            operation.operand = adGroupAd
            operation.operator = [Operator].ADD
            operations.Add(operation)
            Return operations
        End Function

        ''' <summary>
        ''' Builds the operations for creating keywords within an ad group.
        ''' </summary>
        ''' <param name="adGroupId">ID of the ad group for which keywords are
        ''' created.</param>
        ''' <returns>A list of operations for creating keywords.</returns>
        Private Shared Function BuildAdGroupCriterionOperations(ByVal adGroupId As Long) _
            As List(Of AdGroupCriterionOperation)
            Dim adGroupCriteriaOperations As New List(Of AdGroupCriterionOperation)()

            ' Create AdGroupCriterionOperations to add keywords.

            For i As Integer = 0 To NUMBER_OF_KEYWORDS_TO_ADD
                ' Create Keyword.
                Dim text As String = String.Format("mars{0}", i)

                ' Make 50% of keywords invalid to demonstrate error handling.
                If (i Mod 2) = 0 Then
                    text = text & "!!!"
                End If

                ' Create AdGroupCriterionOperation.
                Dim operation As New AdGroupCriterionOperation()
                operation.operand = New BiddableAdGroupCriterion()
                operation.operand.adGroupId = adGroupId

                Dim keyword As New Keyword
                keyword.text = text
                keyword.matchType = KeywordMatchType.BROAD
                operation.operand.criterion = keyword

                operation.operator = [Operator].ADD
                ' Add to list.
                adGroupCriteriaOperations.Add(operation)
            Next

            Return adGroupCriteriaOperations
        End Function

        ''' <summary>
        ''' Builds the operations for creating ad groups within a campaign.
        ''' </summary>
        ''' <param name="campaignId">ID of the campaign for which ad groups are
        ''' created.</param>
        ''' <returns>A list of operations for creating ad groups.</returns>
        Private Shared Function BuildAdGroupOperations(ByVal campaignId As Long) As _
            List(Of AdGroupOperation)
            Dim operations As New List(Of AdGroupOperation)()
            For i As Integer = 0 To NUMBER_OF_ADGROUPS_TO_ADD
                Dim adGroup As New AdGroup()
                adGroup.campaignId = campaignId
                adGroup.id = NextId()
                adGroup.name = "Batch Ad Group # " & ExampleUtilities.GetRandomString()

                Dim cpcBid As New CpcBid
                cpcBid.bid = New Money()
                cpcBid.bid.microAmount = 10000000L
                Dim biddingStrategyConfiguration As New BiddingStrategyConfiguration()
                biddingStrategyConfiguration.bids = New Bids() {cpcBid}

                adGroup.biddingStrategyConfiguration = biddingStrategyConfiguration

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

                operations.Add(operation)
            Next
            Return operations
        End Function

        ''' <summary>
        ''' Builds the operations for creating new campaigns.
        ''' </summary>
        ''' <param name="budgetId">ID of the budget to be used for the campaign.
        ''' </param>
        ''' <returns>A list of operations for creating campaigns.</returns>
        Private Shared Function BuildCampaignOperations(ByVal budgetId As Long) _
            As List(Of CampaignOperation)
            Dim operations As New List(Of CampaignOperation)()

            For i As Integer = 0 To NUMBER_OF_CAMPAIGNS_TO_ADD
                Dim campaign As New Campaign()
                campaign.name = "Batch Campaign " + 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

                campaign.id = NextId()
                campaign.advertisingChannelType = AdvertisingChannelType.SEARCH

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

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

                ' You can optionally provide a bidding scheme in place of the type.
                Dim biddingScheme As New ManualCpcBiddingScheme()
                biddingStrategyConfiguration.biddingScheme = biddingScheme

                campaign.biddingStrategyConfiguration = biddingStrategyConfiguration

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

                operations.Add(operation)
            Next
            Return operations
        End Function

        ''' <summary>
        ''' Builds an operation for creating a budget.
        ''' </summary>
        ''' <returns>The operation for creating a budget.</returns>
        Private Shared Function BuildBudgetOperation() As BudgetOperation
            Dim budget As New Budget()
            budget.budgetId = NextId()
            budget.name = "Interplanetary Cruise #" & ExampleUtilities.GetRandomString()

            Dim amount As New Money()
            amount.microAmount = 50000000L
            budget.amount = amount

            budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD

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

            Return budgetOperation
        End Function
    End Class
End Namespace

Create a draft and access its 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 illustrates how to create a draft and access its
    ''' associated draft campaign. See the Campaign Drafts and Experiments guide
    ''' for more information:
    ''' https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments
    ''' </summary>
    Public Class AddDraft
        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 AddDraft
            Console.WriteLine(codeExample.Description)
            Try
                Dim baseCampaignId As Long = Long.Parse("INSERT_BASE_CAMPAIGN_ID_HERE")

                codeExample.Run(New AdWordsUser, baseCampaignId)
            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 label to multiple campaigns."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="baseCampaignId">Id of the base campaign for creating draft.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal baseCampaignId As Long)
            Using draftService As DraftService = CType(
                user.GetService(
                    AdWordsService.v201809.DraftService),
                DraftService)
                Dim draft As New Draft()
                draft.baseCampaignId = baseCampaignId
                draft.draftName = "Test Draft #" + ExampleUtilities.GetRandomString()

                Dim draftOperation As New DraftOperation()
                draftOperation.operator = [Operator].ADD
                draftOperation.operand = draft

                Try
                    draft = draftService.mutate(New DraftOperation() {draftOperation}).value(0)

                    Console.WriteLine(
                        "Draft with ID {0}, base campaign ID {1} and draft campaign ID " &
                        "{2} created.", draft.draftId, draft.baseCampaignId, draft.draftCampaignId)

                    ' Once the draft is created, you can modify the draft campaign as if it
                    ' were a real campaign. For example, you may add criteria, adjust bids,
                    ' or even include additional ads. Adding a criterion is shown here.
                    Dim campaignCriterionService As CampaignCriterionService =
                            CType(user.GetService(AdWordsService.v201809.CampaignCriterionService),
                                  CampaignCriterionService)
                    Dim language As New Language()
                    language.id = 1003L ' Spanish

                    ' Make sure to use the draftCampaignId when modifying the virtual draft
                    ' campaign.
                    Dim campaignCriterion As New CampaignCriterion()
                    campaignCriterion.campaignId = draft.draftCampaignId
                    campaignCriterion.criterion = language

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

                    campaignCriterion = campaignCriterionService.mutate(
                        New CampaignCriterionOperation() {criterionOperation}).value(0)

                    Console.WriteLine("Draft updated to include criteria in draft campaign ID {0}.",
                                      draft.draftCampaignId)
                Catch e As Exception
                    Throw _
                        New System.ApplicationException("Failed to create draft campaign and add " &
                                                        "criteria.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Upload keywords incrementally using BatchJobService

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

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code sample illustrates how to perform asynchronous requests using
    ''' BatchJobService and incremental uploads of operations. It also
    ''' demonstrates how to cancel a running batch job.
    ''' </summary>
    Public Class AddKeywordsUsingIncrementalBatchJob
        Inherits ExampleBase

        Private Const NUMBER_OF_KEYWORDS_TO_ADD As Long = 100

        ''' <summary>
        ''' The chunk size to use when uploading operations.
        ''' </summary>
        Private Const CHUNK_SIZE As Integer = 4*1024*1024

        ''' <summary>
        ''' The maximum milliseconds to wait for completion.
        ''' </summary>
        Private Const TIME_TO_WAIT_FOR_COMPLETION As Integer = 15*60*1000 ' 15 minutes

        ''' <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 AddKeywordsUsingIncrementalBatchJob
            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 sample illustrates how to perform asynchronous requests using " &
                       "BatchJobService and incremental uploads of operations. It also " &
                       "demonstrates how to cancel a running batch job."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="adGroupId">Id of the ad groups to which keywords are
        ''' added.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long)
            Using batchJobService As BatchJobService = CType(
                user.GetService(
                    AdWordsService.v201809.BatchJobService),
                BatchJobService)

                Dim addOp As New BatchJobOperation
                addOp.operator = [Operator].ADD
                addOp.operand = New BatchJob()

                Try
                    Dim batchJob As BatchJob = batchJobService.mutate(
                        New BatchJobOperation() {addOp}).value(0)

                    Console.WriteLine(
                        "Created BatchJob with ID {0}, status '{1}' and upload URL {2}.",
                        batchJob.id, batchJob.status, batchJob.uploadUrl.url)

                    Dim operations As List(Of AdGroupCriterionOperation) =
                            CreateOperations(adGroupId)

                    ' Create a BatchJobUtilities instance for uploading operations. Use a
                    ' chunked upload.
                    Dim batchJobUploadHelper As New BatchJobUtilities(user, True, CHUNK_SIZE)

                    ' Create a resumable Upload URL to upload the operations.
                    Dim resumableUploadUrl As String = batchJobUploadHelper.GetResumableUploadUrl(
                        batchJob.uploadUrl.url)

                    ' Use the BatchJobUploadHelper to upload all operations.
                    batchJobUploadHelper.Upload(resumableUploadUrl, operations.ToArray())

                    Dim waitHandler As WaitHandler
                    Dim wasCancelRequested As Boolean = False

                    ' Create a wait handler.
                    waitHandler = New WaitHandler(batchJob, wasCancelRequested)

                    Dim isComplete As Boolean = batchJobUploadHelper.WaitForPendingJob(
                        batchJob.id,
                        TIME_TO_WAIT_FOR_COMPLETION,
                        AddressOf waitHandler.OnJobWaitForCompletion)

                    ' Restore the latest value for batchJob from waithandler.
                    batchJob = waitHandler.Job
                    wasCancelRequested = waitHandler.WasCancelRequested

                    ' Optional: Cancel the job if it has not completed after waiting for
                    ' TIME_TO_WAIT_FOR_COMPLETION.
                    Dim shouldWaitForCancellation As Boolean = False
                    If Not isComplete AndAlso wasCancelRequested Then
                        Dim cancellationError As BatchJobError = Nothing
                        Try
                            batchJobUploadHelper.TryToCancelJob(batchJob.id)
                        Catch e As AdWordsApiException
                            cancellationError = GetBatchJobError(e)
                        End Try
                        If cancellationError Is Nothing Then
                            Console.WriteLine("Successfully requested job cancellation.")
                            shouldWaitForCancellation = True
                        Else
                            Console.WriteLine("Job cancellation failed. Error says: {0}.",
                                              cancellationError.reason)
                        End If

                        If shouldWaitForCancellation Then
                            waitHandler = New WaitHandler(batchJob, wasCancelRequested)

                            isComplete = batchJobUploadHelper.WaitForPendingJob(
                                batchJob.id,
                                TIME_TO_WAIT_FOR_COMPLETION,
                                AddressOf waitHandler.OnJobWaitForCancellation)

                            batchJob = waitHandler.Job
                            wasCancelRequested = waitHandler.WasCancelRequested
                        End If
                    End If

                    If Not isComplete Then
                        Throw _
                            New TimeoutException(
                                "Job is still in pending state after waiting for " &
                                TIME_TO_WAIT_FOR_COMPLETION & " seconds.")
                    End If

                    If Not batchJob.processingErrors Is Nothing Then
                        For Each processingError As BatchJobProcessingError In _
                            batchJob.processingErrors
                            Console.WriteLine("  Processing error: {0}, {1}, {2}, {3}, {4}",
                                              processingError.ApiErrorType, processingError.trigger,
                                              processingError.errorString,
                                              processingError.fieldPath,
                                              processingError.reason)
                        Next
                    End If

                    If (Not batchJob.downloadUrl Is Nothing) AndAlso
                       (Not batchJob.downloadUrl.url Is Nothing) Then
                        Dim mutateResponse As BatchJobMutateResponse =
                                batchJobUploadHelper.Download(
                                    batchJob.downloadUrl.url)
                        Console.WriteLine("Downloaded results from {0}.", batchJob.downloadUrl.url)
                        For Each mutateResult As MutateResult In mutateResponse.rval
                            Dim outcome As String
                            If mutateResult.errorList Is Nothing Then
                                outcome = "SUCCESS"
                            Else
                                outcome = "FAILURE"
                            End If
                            Console.WriteLine("  Operation [{0}] - {1}", mutateResult.index,
                                              outcome)
                        Next
                    Else
                        Console.WriteLine("No results available for download.")
                    End If
                Catch e As Exception
                    Throw _
                        New System.ApplicationException(
                            "Failed to create keywords using batch job.",
                            e)
                End Try
            End Using
        End Sub

        ''' <summary>
        ''' A class that handles wait callbacks for the batch job.
        ''' </summary>
        Class WaitHandler
            ''' <summary>
            ''' The batch job to wait for.
            ''' </summary>
            Private batchJob As BatchJob

            ''' <summary>
            ''' A flag to determine if the job was requested to be cancelled. This
            ''' typically comes from the user.
            ''' </summary>
            Private cancelRequested As Boolean

            ''' <summary>
            ''' Initializes a new instance of the <see cref="WaitHandler"/> class.
            ''' </summary>
            ''' <param name="batchJob">The batch job to wait for.</param>
            ''' <param name="wasCancelRequested">A flag to determine if the job was
            ''' requested to be cancelled. This typically comes from the user.</param>
            Sub New(ByVal batchJob As BatchJob, ByVal wasCancelRequested As Boolean)
                Me.batchJob = batchJob
                Me.WasCancelRequested = wasCancelRequested
            End Sub

            ''' <summary>
            ''' Gets or sets the batch job to wait for.
            ''' </summary>
            Public Property Job As BatchJob
                Get
                    Return Me.batchJob
                End Get
                Set(value As BatchJob)
                    Me.batchJob = value
                End Set
            End Property

            ''' <summary>
            ''' Gets or sets a flag to determine if the job was requested to be
            ''' cancelled. This typically comes from the user.
            ''' </summary>
            Public Property WasCancelRequested As Boolean
                Get
                    Return Me.cancelRequested
                End Get
                Set(value As Boolean)
                    Me.cancelRequested = value
                End Set
            End Property

            ''' <summary>
            ''' Callback method when the job is waiting for cancellation.
            ''' </summary>
            ''' <param name="waitBatchJob">The updated batch job being waited for.</param>
            ''' <param name="timeElapsed">The time elapsed.</param>
            ''' <returns>True, if the wait loop should be cancelled, false otherwise.
            '''</returns>
            Public Function OnJobWaitForCancellation(ByVal waitBatchJob As BatchJob,
                                                     ByVal timeElapsed As Long) As Boolean
                Console.WriteLine("[{0} seconds]: Batch job ID {1} has status '{2}'.",
                                  timeElapsed/1000, waitBatchJob.id, waitBatchJob.status)
                batchJob = waitBatchJob
                Return False
            End Function

            ''' <summary>
            ''' Callback method when the job is waiting for completion.
            ''' </summary>
            ''' <param name="waitBatchJob">The updated batch job being waited for.</param>
            ''' <param name="timeElapsed">The time elapsed.</param>
            ''' <returns>True, if the wait loop should be cancelled, false otherwise.
            '''</returns>
            Public Function OnJobWaitForCompletion(ByVal waitBatchJob As BatchJob,
                                                   ByVal timeElapsed As Long) As Boolean
                Console.WriteLine("[{0} seconds]: Batch job ID {1} has status '{2}'.",
                                  timeElapsed/1000, waitBatchJob.id, waitBatchJob.status)
                batchJob = waitBatchJob
                Return Me.WasCancelRequested
            End Function
        End Class

        ''' <summary>
        ''' Gets the batch job error.
        ''' </summary>
        ''' <param name="e">The AdWords API Exception.</param>
        ''' <returns>The underlying batch job error if available, null otherwise.</returns>
        Private Function GetBatchJobError(ByVal e As AdWordsApiException) As BatchJobError
            Dim temp As List(Of BatchJobError) = TryCast(e.ApiException, ApiException).
                    GetAllErrorsByType (Of BatchJobError)()
            ' MOE:begin_strip
            ' Reinvent FirstOrDefault since you cannot use FirstOrDefault with Mono and VBNC. It
            ' works in C# though.
            ' MOE:end_strip
            If temp.Count = 0 Then
                Return Nothing
            Else
                Return temp(0)
            End If
        End Function

        ''' <summary>
        ''' Creates the operations for uploading via batch job.
        ''' </summary>
        ''' <param name="adGroupId">The ad group ID.</param>
        ''' <returns>The list of operations.</returns>
        Private Shared Function CreateOperations(ByVal adGroupId As Long) _
            As List(Of AdGroupCriterionOperation)
            Dim operations As New List(Of AdGroupCriterionOperation)

            ' Create AdGroupCriterionOperations to add keywords, and upload every 10 operations
            ' incrementally.
            For i As Integer = 0 To NUMBER_OF_KEYWORDS_TO_ADD
                ' Create Keyword.
                Dim text As String = String.Format("mars{0}", i)

                ' Make 10% of keywords invalid to demonstrate error handling.
                If (i Mod 10) = 0 Then
                    text = text + "!!!"
                End If

                ' Create BiddableAdGroupCriterion.
                Dim bagc As New BiddableAdGroupCriterion()
                bagc.adGroupId = adGroupId
                Dim keyword As New Keyword()
                keyword.text = text
                keyword.matchType = KeywordMatchType.BROAD
                bagc.criterion = keyword

                ' Create AdGroupCriterionOperation.
                Dim agco As New AdGroupCriterionOperation()
                agco.operand = bagc
                agco.operator = [Operator].ADD

                ' Add to the list of operations.
                operations.Add(agco)
            Next
            Return operations
        End Function
    End Class
End Namespace

Create a trial

' 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 System.Threading
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 create a trial and wait for it to
    ''' complete. See the Campaign Drafts and Experiments guide for more
    ''' information:
    ''' https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments
    ''' </summary>
    Public Class AddTrial
        Inherits ExampleBase

        ''' <summary>
        ''' The polling interval base to be used for exponential backoff.
        ''' </summary>
        Private Const POLL_INTERVAL_SECONDS_BASE As Integer = 30

        ''' <summary>
        ''' The maximum number of retries.
        ''' </summary>
        Private Const MAX_RETRIES As Long = 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 AddTrial
            Console.WriteLine(codeExample.Description)
            Try
                Dim draftId As Long = Long.Parse("INSERT_DRAFT_ID_HERE")
                Dim baseCampaignId As Long = Long.Parse("INSERT_BASE_CAMPAIGN_ID_HERE")
                codeExample.Run(New AdWordsUser(), draftId, baseCampaignId)
            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 create a trial and wait for it to " &
                       "complete. See the Campaign Drafts and Experiments guide for more " &
                       "information: https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments"
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="baseCampaignId">Id of the campaign to use as base of the
        ''' trial.</param>
        ''' <param name="draftId">Id of the draft.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal draftId As Long,
                       ByVal baseCampaignId As Long)
            Using trialService As TrialService = CType(
                user.GetService(
                    AdWordsService.v201809.TrialService),
                TrialService)
                Using trialAsyncErrorService As TrialAsyncErrorService =
                    CType(user.GetService(AdWordsService.v201809.TrialAsyncErrorService),
                          TrialAsyncErrorService)

                    Dim newTrial As New Trial
                    newTrial.draftId = draftId
                    newTrial.baseCampaignId = baseCampaignId
                    newTrial.name = "Test Trial #" & ExampleUtilities.GetRandomString()
                    newTrial.trafficSplitPercent = 50
                    newTrial.trafficSplitType = CampaignTrialTrafficSplitType.RANDOM_QUERY

                    Dim trialOperation As New TrialOperation()
                    trialOperation.operator = [Operator].ADD
                    trialOperation.operand = newTrial
                    Try
                        Dim trialId As Long = trialService.mutate(
                            New TrialOperation() {trialOperation}).value(0).id

                        ' Since creating a trial is asynchronous, we have to poll it to wait
                        ' for it to finish.
                        Dim trialSelector As New Selector()
                        trialSelector.fields = New String() { _
                                                                Trial.Fields.Id,
                                                                Trial.Fields.Status,
                                                                Trial.Fields.BaseCampaignId,
                                                                Trial.Fields.TrialCampaignId
                                                            }
                        trialSelector.predicates = New Predicate() { _
                                                                       Predicate.Equals(
                                                                           Trial.Fields.Id, trialId)
                                                                   }
                        newTrial = Nothing
                        Dim isPending As Boolean = True
                        Dim pollAttempts As Integer = 0

                        Do
                            Dim sleepMillis As Integer = CType(Math.Pow(2, pollAttempts)*
                                                               POLL_INTERVAL_SECONDS_BASE*1000,
                                                               Integer)
                            Console.WriteLine("Sleeping {0} millis...", sleepMillis)
                            Thread.Sleep(sleepMillis)

                            newTrial = trialService.get(trialSelector).entries(0)

                            Console.WriteLine("Trial ID {0} has status '{1}'.", newTrial.id,
                                              newTrial.status)
                            pollAttempts = pollAttempts + 1
                            isPending = (newTrial.status = TrialStatus.CREATING)
                        Loop While isPending AndAlso (pollAttempts <= MAX_RETRIES)

                        If newTrial.status = TrialStatus.ACTIVE Then
                            ' The trial creation was successful.
                            Console.WriteLine("Trial created with ID {0} and trial campaign " &
                                              "ID {1}.",
                                              newTrial.id, newTrial.trialCampaignId)
                        ElseIf newTrial.status = TrialStatus.CREATION_FAILED Then
                            ' The trial creation failed, and errors can be fetched from the
                            ' TrialAsyncErrorService.
                            Dim errorsSelector As New Selector()
                            errorsSelector.fields = New String() { _
                                                                     TrialAsyncError.Fields.TrialId,
                                                                     TrialAsyncError.Fields.
                                                                         AsyncError
                                                                 }
                            errorsSelector.predicates =
                                New Predicate() { _
                                                    Predicate.Equals(TrialAsyncError.Fields.TrialId,
                                                                     newTrial.id)
                                                }

                            Dim trialAsyncErrorPage As TrialAsyncErrorPage = trialAsyncErrorService.
                                    get(
                                        errorsSelector)
                            If trialAsyncErrorPage.entries Is Nothing OrElse
                               trialAsyncErrorPage.entries.Length = 0 Then
                                Console.WriteLine("Could not retrieve errors for trial {0}.",
                                                  newTrial.id)
                            Else
                                Console.WriteLine(
                                    "Could not create trial ID {0} for draft ID {1} due to the " &
                                    "following errors:", trialId, draftId)
                                Dim i As Integer = 1
                                For Each err As TrialAsyncError In trialAsyncErrorPage.entries
                                    Dim asyncError As ApiError = err.asyncError
                                    Console.WriteLine(
                                        "Error #{0}: errorType='{1}', errorString='{2}', " &
                                        "trigger='{3}', fieldPath='{4}'", i,
                                        asyncError.ApiErrorType,
                                        asyncError.errorString, asyncError.trigger,
                                        asyncError.fieldPath)
                                    i += 1
                                Next
                            End If
                        Else
                            ' Most likely, the trial is still being created. You can continue
                            ' polling, but we have limited the number of attempts in the
                            ' example.
                            Console.WriteLine(
                                "Timed out waiting to create trial from draft ID {0} with " +
                                "base campaign ID {1}.", draftId, baseCampaignId)
                        End If
                    Catch e As Exception
                        Throw _
                            New System.ApplicationException("Failed to create trial from draft.", e)
                    End Try
                End Using
            End Using
        End Sub
    End Class
End Namespace

Get all disapproved ads in 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 retrieves all the disapproved ads in a given campaign.
    ''' </summary>
    Public Class GetAllDisapprovedAds
        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 GetAllDisapprovedAds
            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 retrieves all the disapproved ads in a given 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 disapproved ads
        ''' are retrieved.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long)
            Using service As AdGroupAdService = CType(
                user.GetService(
                    AdWordsService.v201809.AdGroupAdService),
                AdGroupAdService)

                ' Create the selector.
                Dim selector As New Selector
                selector.fields = New String() { _
                                                   Ad.Fields.Id, AdGroupAd.Fields.PolicySummary
                                               }

                ' Set the filters.
                selector.predicates =
                    New Predicate() { _
                                        Predicate.Equals(AdGroup.Fields.CampaignId, campaignId),
                                        Predicate.Equals(
                                            AdGroupAdPolicySummary.Fields.CombinedApprovalStatus,
                                            PolicyApprovalStatus.DISAPPROVED.ToString())
                                    }

                ' Set the selector paging.
                selector.paging = Paging.Default

                Dim page As New AdGroupAdPage
                Dim disapprovedAdsCount As Integer = 0

                Try
                    Do
                        ' Get the disapproved ads.
                        page = service.get(selector)

                        ' Display the results.
                        If Not (page Is Nothing) AndAlso Not (page.entries Is Nothing) Then
                            For Each AdGroupAd As AdGroupAd In page.entries
                                Dim policySummary As AdGroupAdPolicySummary =
                                        AdGroupAd.policySummary
                                disapprovedAdsCount += 1
                                Console.WriteLine(
                                    "Ad with ID {0} and type '{1}' was disapproved with the " +
                                    "following policy topic entries: ", AdGroupAd.ad.id,
                                    AdGroupAd.ad.AdType)
                                ' Display the policy topic entries related to the ad disapproval.
                                For Each PolicyTopicEntry As PolicyTopicEntry In _
                                    policySummary.policyTopicEntries
                                    Console.WriteLine("  topic id: {0}, topic name: '{1}'",
                                                      PolicyTopicEntry.policyTopicId,
                                                      PolicyTopicEntry.policyTopicName)
                                    ' Display the attributes And values that triggered the policy
                                    ' topic.
                                    If Not PolicyTopicEntry.policyTopicEvidences Is Nothing Then
                                        For Each evidence As PolicyTopicEvidence In _
                                            PolicyTopicEntry.policyTopicEvidences
                                            Console.WriteLine("    evidence type: {0}",
                                                              evidence.policyTopicEvidenceType)
                                            If Not evidence.evidenceTextList Is Nothing Then
                                                For i As Integer = 0 To _
                                                    evidence.evidenceTextList.Length
                                                    Console.WriteLine(
                                                        "      evidence text[{0}]: {1}",
                                                        i, evidence.evidenceTextList(i))
                                                Next
                                            End If
                                        Next
                                    End If
                                Next
                            Next
                        End If

                        selector.paging.IncreaseOffset()
                    Loop While selector.paging.startIndex < page.totalNumEntries
                    Console.WriteLine("Number of disapproved ads found: {0}", disapprovedAdsCount)
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to get disapproved ads.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Get all disapproved ads in an ad group using AWQL

' 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 retrieves all the disapproved ads in a given campaign
    ''' using an AWQL query. See
    ''' https://developers.google.com/adwords/api/docs/guides/awql for AWQL
    ''' documentation.
    ''' </summary>
    Public Class GetAllDisapprovedAdsWithAwql
        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 GetAllDisapprovedAdsWithAwql
            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 retrieves all the disapproved ads in a given campaign " &
                       "using an AWQL query. " &
                       "See https://developers.google.com/adwords/api/docs/guides/awql for " &
                       "AWQL documentation."
            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 disapproved ads
        ''' are retrieved.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long)
            Using service As AdGroupAdService = CType(
                user.GetService(
                    AdWordsService.v201809.AdGroupAdService),
                AdGroupAdService)

                ' Get all the disapproved ads for this campaign.
                Dim query As SelectQuery = New SelectQueryBuilder() _
                        .Select(Ad.Fields.Id, AdGroupAd.Fields.PolicySummary) _
                        .Where(AdGroup.Fields.CampaignId).Equals(campaignId) _
                        .Where(AdGroupAdPolicySummary.Fields.CombinedApprovalStatus) _
                        .Equals(ApprovalStatus.DISAPPROVED.ToString()) _
                        .OrderByAscending(Ad.Fields.Id) _
                        .DefaultLimit() _
                        .Build()

                Dim page As New AdGroupAdPage()
                Dim disapprovedAdsCount As Integer = 0

                Try
                    Do
                        ' Get the disapproved ads.
                        page = service.query(query)

                        ' Display the results.
                        If Not (page Is Nothing) AndAlso Not (page.entries Is Nothing) Then
                            For Each AdGroupAd As AdGroupAd In page.entries
                                Dim policySummary As AdGroupAdPolicySummary =
                                        AdGroupAd.policySummary
                                disapprovedAdsCount += 1
                                Console.WriteLine(
                                    "Ad with ID {0} and type '{1}' was disapproved with the " +
                                    "following policy topic entries: ", AdGroupAd.ad.id,
                                    AdGroupAd.ad.AdType)
                                ' Display the policy topic entries related to the ad disapproval.
                                For Each PolicyTopicEntry As PolicyTopicEntry In _
                                    policySummary.policyTopicEntries
                                    Console.WriteLine("  topic id: {0}, topic name: '{1}'",
                                                      PolicyTopicEntry.policyTopicId,
                                                      PolicyTopicEntry.policyTopicName)
                                    ' Display the attributes And values that triggered the policy
                                    ' topic.
                                    If Not PolicyTopicEntry.policyTopicEvidences Is Nothing Then
                                        For Each evidence As PolicyTopicEvidence In _
                                            PolicyTopicEntry.policyTopicEvidences
                                            Console.WriteLine("    evidence type: {0}",
                                                              evidence.policyTopicEvidenceType)
                                            If Not evidence.evidenceTextList Is Nothing Then
                                                For i As Integer = 0 To _
                                                    evidence.evidenceTextList.Length
                                                    Console.WriteLine(
                                                        "      evidence text[{0}]: {1}",
                                                        i, evidence.evidenceTextList(i))
                                                Next
                                            End If
                                        Next
                                    End If
                                Next
                            Next
                        End If

                        query.NextPage(page)
                    Loop While (query.HasNextPage(page))
                    Console.WriteLine("Number of disapproved ads found: {0}", disapprovedAdsCount)
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to get disapproved ads.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Get all campaigns with a specific label

' 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 campaigns with a specific label. To add a
    ''' label to campaigns, run AddCampaignLabels.vb.
    ''' </summary>
    Public Class GetCampaignsByLabel
        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 GetCampaignsByLabel
            Console.WriteLine(codeExample.Description)
            Dim labelId As Long = Long.Parse("INSERT_LABEL_ID_HERE")

            Try
                codeExample.Run(New AdWordsUser, labelId)
            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 campaigns with a specific label. To add a" &
                       " label to campaigns, run AddCampaignLabels.vb."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="labelId">ID of the label.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal labelId As Long)
            Using campaignService As CampaignService = CType(
                user.GetService(
                    AdWordsService.v201809.CampaignService),
                CampaignService)

                ' Create the selector.
                Dim selector As New Selector
                selector.fields = New String() { _
                                                   Campaign.Fields.Id, Campaign.Fields.Name,
                                                   Campaign.Fields.Labels
                                               }

                ' Labels filtering is performed by ID. You can use CONTAINS_ANY to
                ' select campaigns with any of the label IDs, CONTAINS_ALL to select
                ' campaigns with all of the label IDs, or CONTAINS_NONE to select
                ' campaigns with none of the label IDs.
                selector.predicates = New Predicate() { _
                                                          Predicate.ContainsAny(
                                                              Campaign.Fields.Labels,
                                                              New String() {labelId.ToString()})
                                                      }

                ' Set the selector paging.
                selector.paging = Paging.Default

                Dim page As New CampaignPage

                Try
                    Do
                        ' Get the campaigns.
                        page = campaignService.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 campaign As Campaign In page.entries
                                Dim labelNames As New List(Of String)
                                For Each label As Label In campaign.labels
                                    labelNames.Add(label.name)
                                Next

                                Console.WriteLine(
                                    "{0}) Campaign with id = '{1}', name = '{2}' and labels = " &
                                    "'{3}' was found.", i + 1, campaign.id, campaign.name,
                                    String.Join(", ", labelNames.ToArray()))
                                i = i + 1
                            Next
                        End If
                        selector.paging.IncreaseOffset()
                    Loop While selector.paging.startIndex < page.totalNumEntries
                    Console.WriteLine("Number of campaigns found: {0}", page.totalNumEntries)
                Catch e As Exception
                    Throw _
                        New System.ApplicationException("Failed to retrieve campaigns by label.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Graduate a trial

' 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 graduate a trial. See the Campaign
    ''' Drafts and Experiments guide for more information:
    ''' https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments
    ''' </summary>
    Public Class GraduateTrial
        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 GraduateTrial
            Console.WriteLine(codeExample.Description)
            Try
                Dim trialId As Long = Long.Parse("INSERT_TRIAL_ID_HERE")
                codeExample.Run(New AdWordsUser(), trialId)
            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 graduate a trial. See the Campaign " &
                       "Drafts and Experiments guide for more information: " &
                       "https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments"
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="trialId">Id of the trial to be graduated.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal trialId As Long)
            Using trialService As TrialService = CType(
                user.GetService(
                    AdWordsService.v201809.TrialService),
                TrialService)

                ' To graduate a trial, you must specify a different budget from the
                ' base campaign. The base campaign (in order to have had a trial based
                ' on it) must have a non-shared budget, so it cannot be shared with
                ' the new independent campaign created by graduation.
                Dim budget As Budget = CreateBudget(user)

                Dim trial As New Trial()
                trial.id = trialId
                trial.budgetId = budget.budgetId
                trial.status = TrialStatus.GRADUATED

                Dim trialOperation As New TrialOperation()
                trialOperation.operator = [Operator].SET
                trialOperation.operand = trial

                Try
                    ' Update the trial.
                    trial = trialService.mutate(New TrialOperation() {trialOperation}).value(0)

                    ' Graduation is a synchronous operation, so the campaign is already
                    ' ready. If you promote instead, make sure to see the polling scheme
                    ' demonstrated in AddTrial.cs to wait for the asynchronous operation
                    ' to finish.
                    Console.WriteLine(
                        "Trial ID {0} graduated. Campaign ID {1} was given a new budget " &
                        "ID {2} and is no Longer dependent on this trial.", trial.id,
                        trial.trialCampaignId,
                        budget.budgetId)
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to graduate trial.", e)
                End Try
            End Using
        End Sub

        ''' <summary>
        ''' Creates the budget.
        ''' </summary>
        ''' <param name="user">The user.</param>
        ''' <returns>The new budget.</returns>
        Private Shared Function CreateBudget(user As AdWordsUser) As Budget
            Using budgetService As BudgetService = CType(
                user.GetService(
                    AdWordsService.v201809.BudgetService),
                BudgetService)
                Dim budget As New Budget()
                budget.name = "Budget #" + ExampleUtilities.GetRandomString()
                budget.amount = New Money()
                budget.amount.microAmount = 50000000L
                budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD

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

                ' Add budget.
                Return budgetService.mutate(New BudgetOperation() {budgetOperation}).value(0)
            End Using
        End Function
    End Class
End Namespace

Set ad parameters for a keyword ad group 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.v201809

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example illustrates how to create a text ad with ad parameters.
    ''' To add an ad group, run AddAdGroup.vb. To add a keyword, run
    ''' AddKeyword.vb.
    ''' </summary>
    Public Class SetAdParameters
        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 SetAdParameters
            Console.WriteLine(codeExample.Description)
            Try
                Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
                Dim criterionId As Long = Long.Parse("INSERT_CRITERION_ID_HERE")

                codeExample.Run(New AdWordsUser, adGroupId, criterionId)
            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 create a text ad with ad parameters. To" &
                    " add an ad group, run AddAdGroup.vb. To add a keyword, run AddKeyword.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 that contains the criterion.
        ''' </param>
        ''' <param name="criterionId">Id of the keyword for which the ad
        ''' parameters are set.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long,
                       ByVal criterionId As Long)
            Using adGroupAdService As AdGroupAdService = CType(
                user.GetService(
                    AdWordsService.v201809.AdGroupAdService),
                AdGroupAdService)
                Using adParamService As AdParamService = CType(
                    user.GetService(
                        AdWordsService.v201809.AdParamService),
                    AdParamService)

                    ' Create the expanded text ad.
                    Dim expandedTextAd As New ExpandedTextAd()
                    expandedTextAd.headlinePart1 = "Mars Cruises"
                    expandedTextAd.headlinePart2 = "Low-gravity fun for {param1:cheap}."
                    expandedTextAd.description = "Only {param2:a few} seats left!"
                    expandedTextAd.finalUrls = New String() {"http://www.example.com"}

                    Dim adOperand As New AdGroupAd
                    adOperand.adGroupId = adGroupId
                    adOperand.status = AdGroupAdStatus.ENABLED
                    adOperand.ad = expandedTextAd

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

                    ' Create the expanded text ad.
                    Dim retVal As AdGroupAdReturnValue = adGroupAdService.mutate(
                        New AdGroupAdOperation() {adOperation})

                    ' Display the results.
                    If ((Not retVal Is Nothing) AndAlso (Not retVal.value Is Nothing) _
                        AndAlso (retVal.value.Length > 0)) Then
                        Console.WriteLine(
                            "Expanded text ad with id = ""{0}"" was successfully added.",
                            retVal.value(0).ad.id)
                    Else
                        Throw New System.ApplicationException("Failed to create expanded text ads.")
                        Return
                    End If

                    ' Create the ad param for price.
                    Dim priceParam As New AdParam
                    priceParam.adGroupId = adGroupId
                    priceParam.criterionId = criterionId
                    priceParam.paramIndex = 1
                    priceParam.insertionText = "$100"

                    ' Create the ad param for seats.
                    Dim seatParam As New AdParam
                    seatParam.adGroupId = adGroupId
                    seatParam.criterionId = criterionId
                    seatParam.paramIndex = 2
                    seatParam.insertionText = "50"

                    ' Create the operations.
                    Dim priceOperation As New AdParamOperation
                    priceOperation.operator = [Operator].SET
                    priceOperation.operand = priceParam

                    Dim seatOperation As New AdParamOperation
                    seatOperation.operator = [Operator].SET
                    seatOperation.operand = seatParam

                    Try
                        ' Set the ad parameters.
                        Dim newAdParams As AdParam() = adParamService.mutate(
                            New AdParamOperation() _
                                                                                {priceOperation,
                                                                                 seatOperation})

                        'Display the results.
                        If (Not newAdParams Is Nothing) Then
                            Console.WriteLine("Ad parameters were successfully updated.")
                        Else
                            Console.WriteLine("No ad parameters were set.")
                        End If
                    Catch e As Exception
                        Throw New System.ApplicationException("Failed to set ad parameter(s).", e)
                    End Try
                End Using
            End Using
        End Sub
    End Class
End Namespace

Set a bid modifier on 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 sets a bid modifier for the mobile platform on given
    ''' campaign. The campaign must be an enhanced type of campaign. To get
    ''' campaigns, run GetCampaigns.vb. To enhance a campaign, run
    ''' SetCampaignEnhanced.vb.
    ''' </summary>
    Public Class SetBidModifier
        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 SetBidModifier
            Console.WriteLine(codeExample.Description)
            Try
                Dim campaignId As Long = Long.Parse("INSERT_CAMPAIGN_ID_HERE")
                Dim bidModifier As Double = Double.Parse("INSERT_BID_MODIFIER_HERE")
                codeExample.Run(New AdWordsUser, campaignId, 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 sets a bid modifier for the mobile platform on given " &
                       "campaign. The campaign must be an enhanced type of campaign. To get " &
                       "campaigns, run GetCampaigns.vb. To enhance a campaign, run " &
                       "SetCampaignEnhanced.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 whose bid should be modified.
        ''' </param>
        ''' <param name="bidModifier">The bid modifier.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long,
                       ByVal bidModifier As Double)
            Using campaignCriterionService As CampaignCriterionService = CType(
                user.GetService(
                    AdWordsService.v201809.CampaignCriterionService),
                CampaignCriterionService)

                ' Create mobile platform. The ID can be found in the documentation.
                ' https://developers.google.com/adwords/api/docs/appendix/platforms
                Dim mobile As New Platform()
                mobile.id = 30001

                ' Create criterion with modified bid.
                Dim criterion As New CampaignCriterion()
                criterion.campaignId = campaignId
                criterion.criterion = mobile
                criterion.bidModifier = bidModifier

                ' Create SET operation.
                Dim operation As New CampaignCriterionOperation()
                operation.operator = [Operator].SET
                operation.operand = criterion

                Try
                    ' Update campaign criteria.
                    Dim result As CampaignCriterionReturnValue = campaignCriterionService.mutate(
                        New CampaignCriterionOperation() {operation})

                    ' Display campaign criteria.
                    If Not result.value Is Nothing Then
                        For Each newCriterion As CampaignCriterion In result.value
                            Console.WriteLine(
                                "Campaign criterion with campaign id '{0}', criterion id '{1}' " &
                                "and type '{2}' was modified with bid {3:F2}.",
                                newCriterion.campaignId,
                                newCriterion.criterion.id, newCriterion.criterion.type,
                                newCriterion.bidModifier)
                        Next
                    Else
                        Console.WriteLine("No campaigns were modified.")
                    End If
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to set bid modifier.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Validate text ad through setValidateOnly header

' 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 shows how to use the validateOnly header to validate
    ''' an expanded text ad. No objects will be created, but exceptions will
    ''' still be thrown.
    ''' </summary>
    Public Class ValidateTextAd
        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 ValidateTextAd
            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 shows how to use the validateOnly header to validate an " &
                    "expanded text ad. No objects will be created, but exceptions will still be " &
                    "thrown."
            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 text 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)

                ' Set the validateOnly headers.
                adGroupAdService.RequestHeader.validateOnly = True

                ' Create your 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!!"
                expandedTextAd.finalUrls = New String() {"http://www.example.com"}

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

                Dim operation As New AdGroupAdOperation
                operation.operator = [Operator].ADD
                operation.operand = adGroupAd
                Try
                    Dim retVal As AdGroupAdReturnValue = adGroupAdService.mutate(
                        New AdGroupAdOperation() {operation})
                    ' Since validation is ON, result will be null.
                    Console.WriteLine("Expanded text ad validated successfully.")
                Catch e As AdWordsApiException
                    ' This block will be hit if there is a validation error from the server.
                    Console.WriteLine(
                        "There were validation error(s) while adding expanded text ad.")

                    If (Not e.ApiException Is Nothing) Then
                        For Each apiError As ApiError In _
                            DirectCast(e.ApiException, ApiException).errors
                            Console.WriteLine("  Error type is '{0}' and fieldPath is '{1}'.",
                                              apiError.ApiErrorType, apiError.fieldPath)
                        Next
                    End If
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to validate expanded text ad.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace

Надіслати відгук про…

Цю сторінку
AdWords API
AdWords API
Потрібна допомога? Відвідайте сторінку підтримки.