Account Management Samples

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

Accept an invitation for linking to a manager account

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

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

  ''' <summary>
  ''' This code example accepts a pending invitation to link your AdWords
  ''' account to a Google Merchant Center account.
  ''' </summary>
  Public Class AcceptServiceLink
    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 AcceptServiceLink
      Console.WriteLine(codeExample.Description)
      Try
        Dim serviceLinkId As Long = Long.Parse("INSERT_SERVICE_LINK_ID_HERE")
        codeExample.Run(New AdWordsUser, serviceLinkId)
      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 accepts a pending invitation to link your AdWords " &
            "account to a Google Merchant Center account."
      End Get
    End Property

    ''' <summary>
    ''' Runs the code example.
    ''' </summary>
    ''' <param name="user">The AdWords user.</param>
    ''' <param name="serviceLinkId">The service link ID to accept.</param>
    Public Sub Run(ByVal user As AdWordsUser, ByVal serviceLinkId As Long)
      Using customerService As CustomerService = CType(user.GetService(
          AdWordsService.v201806.CustomerService), CustomerService)

        ' Create the operation to set the status to ACTIVE.
        Dim op As New ServiceLinkOperation()
        op.operator = [Operator].SET
        Dim serviceLink As New ServiceLink()
        serviceLink.serviceLinkId = serviceLinkId
        serviceLink.serviceType = ServiceType.MERCHANT_CENTER
        serviceLink.linkStatus = ServiceLinkLinkStatus.ACTIVE
        op.operand = serviceLink

        Try
          ' Update the service link.
          Dim mutatedServiceLinks As ServiceLink() =
            customerService.mutateServiceLinks(New ServiceLinkOperation() {op})

          ' Display the results.
          For Each mutatedServiceLink As ServiceLink In mutatedServiceLinks
            Console.WriteLine("Service link with service link ID {0}, type '{1}' updated to " &
              "status: {2}.", mutatedServiceLink.serviceLinkId, mutatedServiceLink.serviceType,
              mutatedServiceLink.linkStatus)
          Next
        Catch e As Exception
          Throw New System.ApplicationException("Failed to update service link.", e)
        End Try
      End Using
    End Sub

  End Class

End Namespace

Create a new account under an AdWords manager

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

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

  ''' <summary>
  ''' This code example illustrates how to create an account. Note by default,
  ''' this account will only be accessible via its parent AdWords manager
  ''' account.
  ''' </summary>
  Public Class CreateAccount
    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 CreateAccount
      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 create an account. Note by default," &
            " this account will only be accessible via its parent AdWords manager account."
      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 managedCustomerService As ManagedCustomerService = CType(user.GetService(
          AdWordsService.v201806.ManagedCustomerService), ManagedCustomerService)

        ' Create account.
        Dim customer As New ManagedCustomer()
        customer.name = "Customer created with ManagedCustomerService on " &
          New DateTime().ToString()
        customer.currencyCode = "EUR"
        customer.dateTimeZone = "Europe/London"

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

        ' For whitelisted users only, uncomment two commands below as part of the
        ' ADD operation to invite a user to have access to an account. An email
        ' will be sent to that user inviting them to have access to the newly
        ' created account.
        ' operation.inviteeEmail = "invited_user1@example.com"
        ' operation.inviteeRole = AccessRole.ADMINISTRATIVE

        Try
          Dim operations As ManagedCustomerOperation() = New ManagedCustomerOperation() {operation}
          ' Add account.
          Dim result As ManagedCustomerReturnValue = managedCustomerService.mutate(operations)

          ' Display accounts.
          If (Not result.value Is Nothing) AndAlso (result.value.Length > 0) Then
            Dim customerResult As ManagedCustomer = result.value(0)
            Console.WriteLine("Account with customer ID '{0}' was created.",
              customerResult.customerId)
          Else
            Console.WriteLine("No accounts were created.")
          End If
        Catch e As Exception
          Throw New System.ApplicationException("Failed to create accounts.", e)
        End Try
      End Using
    End Sub

  End Class

End Namespace

Get all account changes during the past 24 hours

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

Imports System.Text

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

  ''' <summary>
  ''' This code example gets the changes in the account during the last 24
  ''' hours.
  ''' </summary>
  Public Class GetAccountChanges
    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 GetAccountChanges
      Console.WriteLine(codeExample.Description)
      Try
        codeExample.Run(New AdWordsUser)
      Catch e As Exception
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e))
      End Try
    End Sub

    ''' <summary>
    ''' Returns a description about the code example.
    ''' </summary>
    Public Overrides ReadOnly Property Description() As String
      Get
        Return "This code example gets the changes in the account during the last 24 hours."
      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 customerSyncService As CustomerSyncService = CType(user.GetService(
          AdWordsService.v201806.CustomerSyncService), CustomerSyncService)

        ' The date time string should be of the form  yyyyMMdd HHmmss zzz.
        Dim minDateTime As String = (DateTime.Now.AddDays(-1).ToUniversalTime.ToString(
          "yyyyMMdd HHmmss") & " UTC")
        Dim maxDateTime As String = (DateTime.Now.ToUniversalTime.ToString(
                                   "yyyyMMdd HHmmss") & " UTC")

        ' Create date time range.
        Dim dateTimeRange As New DateTimeRange
        dateTimeRange.min = minDateTime
        dateTimeRange.max = maxDateTime

        Try
          ' Create the selector.
          Dim selector As New CustomerSyncSelector
          selector.dateTimeRange = dateTimeRange
          selector.campaignIds = GetAllCampaignIds(user)

          ' Get all account changes for campaign.
          Dim accountChanges As CustomerChangeData = customerSyncService.get(selector)

          ' Display the changes.
          If ((Not accountChanges Is Nothing) AndAlso
            (Not accountChanges.changedCampaigns Is Nothing)) Then
            Console.WriteLine("Displaying changes up to: {0}", accountChanges.lastChangeTimestamp)

            For Each campaignChanges As CampaignChangeData In accountChanges.changedCampaigns
              Console.WriteLine("Campaign with id ""{0}"" was changed:",
                  campaignChanges.campaignId)
              Console.WriteLine("  Campaign changed status: {0}",
                campaignChanges.campaignChangeStatus)
              If (campaignChanges.campaignChangeStatus <> ChangeStatus.NEW) Then

                Console.WriteLine("  Added campaign criteria: {0}",
                  GetFormattedList(campaignChanges.addedCampaignCriteria))

                Console.WriteLine("  Removed campaign criteria: {0}",
                  GetFormattedList(campaignChanges.removedCampaignCriteria))

                If (Not campaignChanges.changedAdGroups Is Nothing) Then
                  For Each adGroupChanges As AdGroupChangeData In campaignChanges.changedAdGroups
                    Console.WriteLine("  Ad group with id ""{0}"" was changed:",
                      adGroupChanges.adGroupId)
                    Console.WriteLine("    Ad group changed status: {0}",
                      adGroupChanges.adGroupChangeStatus)
                    If (adGroupChanges.adGroupChangeStatus <> ChangeStatus.NEW) Then
                      Console.WriteLine("    Ads changed: {0}",
                        GetFormattedList(adGroupChanges.changedAds))
                      Console.WriteLine("    Criteria changed: {0}",
                        GetFormattedList(adGroupChanges.changedCriteria))
                      Console.WriteLine("    Criteria removed: {0}",
                        GetFormattedList(adGroupChanges.removedCriteria))
                    End If
                  Next
                End If
              End If
              Console.WriteLine()
            Next
          Else
            Console.WriteLine("No account changes were found.")
          End If
        Catch e As Exception
          Throw New System.ApplicationException("Failed to get account changes.", e)
        End Try
      End Using
    End Sub

    ''' <summary>
    ''' Formats a list of ids as a comma separated string.
    ''' </summary>
    ''' <param name="ids">The list of ids.</param>
    ''' <returns>The comma separed formatted string, enclosed in square braces.
    ''' </returns>
    Private Function GetFormattedList(ByVal ids As Long()) As String
      Dim builder As New StringBuilder
      If (Not ids Is Nothing) Then
        For Each id As Long In ids
          builder.AppendFormat("{0}, ", id)
        Next
      End If
      Return ("[" & builder.ToString.TrimEnd(New Char() {","c, " "c}) & "]")
    End Function

    ''' <summary>
    ''' Gets all campaign ids in the account.
    ''' </summary>
    ''' <param name="user">The user for which campaigns are retrieved.</param>
    ''' <returns>The list of campaign ids.</returns>
    Private Function GetAllCampaignIds(ByVal user As AdWordsUser) As Long()
      ' Get the CampaignService.
      Using campaignService As CampaignService = CType(user.GetService(
          AdWordsService.v201806.CampaignService), CampaignService)
        Dim allCampaigns As New List(Of Long)

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

        ' Get all campaigns.
        Dim page As CampaignPage = campaignService.get(selector)

        ' Return the results.
        If ((Not page Is Nothing) AndAlso (Not page.entries Is Nothing)) Then
          For Each campaign As Campaign In page.entries
            allCampaigns.Add(campaign.id)
          Next
        End If
        Return allCampaigns.ToArray
      End Using
    End Function

  End Class

End Namespace

Get the account hierarchy under the current account

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

Imports System.Text

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

  ''' <summary>
  ''' This code example illustrates how to retrieve the account hierarchy under
  ''' an account. This code example won't work with Test Accounts. See
  ''' https://developers.google.com/adwords/api/docs/test-accounts
  ''' </summary>
  Public Class GetAccountHierarchy
    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 GetAccountHierarchy
      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 retrieve the account hierarchy under " &
            "an account. This code example won't work with Test Accounts. See " &
            "https://developers.google.com/adwords/api/docs/test-accounts"
      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 managedCustomerService As ManagedCustomerService = CType(user.GetService(
          AdWordsService.v201806.ManagedCustomerService), ManagedCustomerService)

        ' Create selector.
        Dim selector As New Selector()
        selector.fields = New String() {
          ManagedCustomer.Fields.CustomerId, ManagedCustomer.Fields.Name
        }
        selector.paging = Paging.Default

        ' Map from customerId to customer node.
        Dim customerIdToCustomerNode As Dictionary(Of Long, ManagedCustomerTreeNode) =
          New Dictionary(Of Long, ManagedCustomerTreeNode)()

        ' Temporary cache to save links.
        Dim allLinks As New List(Of ManagedCustomerLink)

        Dim page As ManagedCustomerPage = Nothing
        Try
          Do
            page = managedCustomerService.get(selector)

            ' Display serviced account graph.
            If Not page.entries Is Nothing Then
              ' Create account tree nodes for each customer.
              For Each customer As ManagedCustomer In page.entries
                Dim node As New ManagedCustomerTreeNode()
                node.Account = customer
                customerIdToCustomerNode.Add(customer.customerId, node)
              Next

              If Not page.links Is Nothing Then
                allLinks.AddRange(page.links)
              End If
            End If

            selector.paging.IncreaseOffset()
          Loop While (selector.paging.startIndex < page.totalNumEntries)

          ' For each link, connect nodes in tree.
          For Each link As ManagedCustomerLink In allLinks
            Dim managerNode As ManagedCustomerTreeNode =
              customerIdToCustomerNode(link.managerCustomerId)
            Dim childNode As ManagedCustomerTreeNode =
              customerIdToCustomerNode(link.clientCustomerId)
            childNode.ParentNode = managerNode
            If (Not managerNode Is Nothing) Then
              managerNode.ChildAccounts.Add(childNode)
            End If
          Next

          ' Find the root account node in the tree.
          Dim rootNode As ManagedCustomerTreeNode = Nothing
          For Each node As ManagedCustomerTreeNode In customerIdToCustomerNode.Values
            If node.ParentNode Is Nothing Then
              rootNode = node
              Exit For
            End If
          Next

          ' Display account tree.
          Console.WriteLine("CustomerId, Name")
          Console.WriteLine(rootNode.ToTreeString(0, New StringBuilder()))
        Catch e As Exception
          Throw New System.ApplicationException("Failed to get accounts.", e)
        End Try
      End Using
    End Sub

  End Class

  ''' <summary>
  '''Example implementation of a node that would exist in an account tree.
  ''' </summary>
  Class ManagedCustomerTreeNode

    ''' <summary>
    ''' The parent node.
    ''' </summary>
    Private _parentNode As ManagedCustomerTreeNode

    ''' <summary>
    ''' The account associated with this node.
    ''' </summary>
    Private _account As ManagedCustomer

    ''' <summary>
    ''' The list of child accounts.
    ''' </summary>
    Private _childAccounts As New List(Of ManagedCustomerTreeNode)

    ''' <summary>
    ''' Gets or sets the parent node.
    ''' </summary>
    Public Property ParentNode() As ManagedCustomerTreeNode
      Get
        Return _parentNode
      End Get
      Set(ByVal value As ManagedCustomerTreeNode)
        _parentNode = value
      End Set
    End Property

    ''' <summary>
    ''' Gets or sets the account.
    ''' </summary>
    Public Property Account() As ManagedCustomer
      Get
        Return _account
      End Get
      Set(ByVal value As ManagedCustomer)
        _account = value
      End Set
    End Property

    ''' <summary>
    ''' Gets or sets the child accounts.
    ''' </summary>
    Public Property ChildAccounts() As List(Of ManagedCustomerTreeNode)
      Get
        Return _childAccounts
      End Get
      Set(ByVal value As List(Of ManagedCustomerTreeNode))
        _childAccounts = value
      End Set
    End Property

    ''' <summary>
    ''' Returns a <see cref="System.String"/> that represents this instance.
    ''' </summary>
    ''' <returns>
    ''' A <see cref="System.String"/> that represents this instance.
    ''' </returns>
    Public Overrides Function ToString() As String
      Return String.Format("{0}, {1}", _account.customerId, _account.name)
    End Function

    ''' <summary>
    ''' Returns a string representation of the current level of the tree and
    ''' recursively returns the string representation of the levels below it.
    ''' </summary>
    ''' <param name="depth">The depth of the node.</param>
    ''' <param name="sb">The String Builder containing the tree
    ''' representation.</param>
    ''' <returns>The tree string representation.</returns>
    Public Function ToTreeString(ByVal depth As Integer, ByVal sb As StringBuilder) _
        As StringBuilder
      sb.Append("-"c, depth * 2)
      sb.Append(Me)
      sb.AppendLine()
      For Each childAccount As ManagedCustomerTreeNode In _childAccounts
        childAccount.ToTreeString(depth + 1, sb)
      Next
      Return sb
    End Function

  End Class

End Namespace

Send feedback about...

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