Keyword Performance Report in Visual Basic

The following example shows how to request and retrieve a keyword performance report using the following Reporting service operations.

This example has been developed and run within the environment described in Getting Started Using C# and Visual Basic with Bing Ads Services.

System_CLiX_note Note

This example uses the UserName and Password elements for authentication. For Managing User Authentication with OAuth, replace the UserName and Password elements with the AuthenticationToken, which is your OAuth access token.

Sub GetKeywordPerformanceReport( _
        ByVal username As String, _
        ByVal password As String, _
        ByVal appToken As String, _
        ByVal devToken As String, _
        ByVal accountIds() As Long, _
        ByVal zipFileName As String)
    
    ' Create and initialize the keyword performance report request 
    ' object.
    Dim reportRequest = New KeywordPerformanceReportRequest

    ' Specify the language for the report.
    reportRequest.Language = ReportLanguage.English

    ' Specify the format of the report.
    reportRequest.Format = ReportFormat.Xml
    reportRequest.ReturnOnlyCompleteData = False
    reportRequest.ReportName = "My Keyword Report"
    reportRequest.Aggregation = ReportAggregation.Monthly

    ' Specify the time frame of the report.
    reportRequest.Time = New ReportTime
    reportRequest.Time.PredefinedTime = ReportTimePeriod.LastSixMonths
    reportRequest.Time.CustomDates = Nothing
    reportRequest.Time.CustomDateRangeStart = Nothing
    reportRequest.Time.CustomDateRangeEnd = Nothing

    ' Specify the columns that will be in the report.
    ' Allocate the array.
    Array.Resize(reportRequest.Columns, 6)
    reportRequest.Columns(0) = KeywordPerformanceReportColumn.AccountName
    reportRequest.Columns(1) = KeywordPerformanceReportColumn.CampaignName
    reportRequest.Columns(2) = KeywordPerformanceReportColumn.Keyword
    reportRequest.Columns(3) = KeywordPerformanceReportColumn.TimePeriod
    reportRequest.Columns(4) = KeywordPerformanceReportColumn.Impressions
    reportRequest.Columns(5) = KeywordPerformanceReportColumn.Conversions

    ' Specify the scope of the report. This example goes only 
    ' to the account level, but you can request a report for any 
    ' number of accounts, ad groups, and campaigns.
    reportRequest.Scope = New AccountThroughAdGroupReportScope
    reportRequest.Scope.AccountIds = accountIds
    reportRequest.Scope.AdGroups = Nothing
    reportRequest.Scope.Campaigns = Nothing

    ' Specify the filter for the report. This example requests that the 
    ' report contains only the search ads that were displayed in the United 
    ' States.
    reportRequest.Filter = New KeywordPerformanceReportFilter
    reportRequest.Filter.AdDistribution = AdDistributionReportFilter.Search
    reportRequest.Filter.LanguageAndRegion = _
        LanguageAndRegionReportFilter.UnitedStates
    reportRequest.Filter.DeliveredMatchType = Nothing
    reportRequest.Filter.Keywords = Nothing

    ' Create and initialize the ReportingServiceClient object.
    Dim service = New ReportingServiceClient

    ' Submit the report request.
    Try
        ' Create and initialize the SubmitGenerateReportRequest object.
        Dim submitRequest = New SubmitGenerateReportRequest
        submitRequest.ApplicationToken = Nothing
        submitRequest.DeveloperToken = devToken
        submitRequest.UserName = username
        submitRequest.Password = password
        submitRequest.ReportRequest = reportRequest

        ' Submit the report request. This will throw an exception if 
        ' an error occurs.
        Dim submitResponse = service.SubmitGenerateReport(submitRequest)

        ' Poll to get the status of the report until it is complete.
#If (Not Debug) Then
        Dim waitMinutes As Integer = 15
#Else
        Dim waitMinutes As Integer = 0
#End If

        Dim maxWaitMinutes As Integer = 120
        Dim startTime As DateTime = DateTime.Now
        Dim elapsedMinutes As Integer = 0

        ' Initialize the GetReportStatusResponse object to Nothing in case 
        ' an error occurs.
        Dim statusResponse As PollGenerateReportResponse = Nothing

        Do
            ' Wait the specified number of minutes before polling.
            System.Threading.Thread.Sleep((waitMinutes * (60 * 1000)))
            elapsedMinutes = DateTime.Now.Subtract(startTime).Minutes

            Dim statusRequest = New PollGenerateReportRequest
            statusRequest.ApplicationToken = Nothing
            statusRequest.DeveloperToken = devToken
            statusRequest.UserName = username
            statusRequest.Password = password
            statusRequest.ReportRequestId = submitResponse.ReportRequestId

            ' Get the status of the report.
            statusResponse = service.PollGenerateReport(statusRequest)
            If (ReportRequestStatusType.Success = _
                statusResponse.ReportRequestStatus.Status) Then
                ' The report is ready.
                Exit Do
            ElseIf (ReportRequestStatusType.Pending = _
                    statusResponse.ReportRequestStatus.Status) Then
                ' The report is not yet ready. Loop again.
            Else
                ' An error occurred.
                Exit Do
            End If
        Loop While (elapsedMinutes < maxWaitMinutes)

        ' If the report was created, download it.
        If ((Not (statusResponse) Is Nothing) AndAlso _
            (ReportRequestStatusType.Success = _
             statusResponse.ReportRequestStatus.Status)) _
             Then

            ' Open a connection to the URL where the report is available.
            Dim webRequest As HttpWebRequest = webRequest.Create( _
                statusResponse.ReportRequestStatus.ReportDownloadUrl)
            Dim response = CType(webRequest.GetResponse, HttpWebResponse)
            Dim httpStream = response.GetResponseStream

            ' Open the destination file.
            Dim zipFileInfo = New FileInfo(zipFileName)
            If Not zipFileInfo.Directory.Exists Then
                zipFileInfo.Directory.Create()
            End If
            Dim fileStream = _
                New FileStream(zipFileInfo.FullName, FileMode.Create)
            Dim binaryWriter = New BinaryWriter(fileStream)
            Dim binaryReader = New BinaryReader(httpStream)
            Try
                ' Read the report, and then write it to the destination file.
                Dim bufferSize As Integer = 100000

                While True
                    ' Read the report data.
                    Dim buffer() = binaryReader.ReadBytes(bufferSize)

                    ' Write the report data to the destination file.
                    binaryWriter.Write(buffer)

                    ' If the end of the report is reached, break out of the 
                    ' loop.
                    If (buffer.Length <> bufferSize) Then
                        Exit While
                    End If

                End While
            Finally
                ' Clean up.
                binaryWriter.Close()
                binaryReader.Close()
                fileStream.Close()
                httpStream.Close()
            End Try
        End If

    ' Catch any generic errors.
    Catch fault As FaultException(Of AdApiFaultDetail)
        Dim faultDetail As AdApiFaultDetail = fault.Detail

        ' Write any errors.
        For Each adError As AdApiError In faultDetail.Errors
            Console.WriteLine(String.Format("Error {0}:", _
                adError.Code.ToString()))
            Console.WriteLine(String.Format(vbTab + "Message:  '{0}'", _
                adError.Message))
        Next

    ' Catch web service API errors.
    Catch fault As FaultException(Of ApiFaultDetail)
        Dim faultDetail As ApiFaultDetail = fault.Detail

        ' Write any operation errors.
        For Each opError As OperationError In faultDetail.OperationErrors
            Console.WriteLine(String.Format("Error {0}:", _
                opError.Code.ToString()))
            Console.WriteLine(String.Format(vbTab + "Message:  '{0}'", _
                opError.Message))
            Console.WriteLine(String.Format(vbTab + "Details: '{0}'", _
                opError.Details))
        Next

        ' Write any batch errors.
        For Each batchError As BatchError In faultDetail.BatchErrors
            Console.Write((batchError.Index.ToString() + " : "))
            Console.Write((batchError.Code.ToString() + " : '"))
            Console.WriteLine((batchError.Message + "'"))
        Next

    Finally
        ' Make sure that you close the service.
        service.Close()
    End Try
End Sub

Community Additions

Show: