Пример #1
0
        /// <summary>Snippet for SearchStream</summary>
        public async Task SearchStreamRequestObject()
        {
            // Snippet: SearchStream(SearchGoogleAdsStreamRequest, CallSettings)
            // Create client
            GoogleAdsServiceClient googleAdsServiceClient = GoogleAdsServiceClient.Create();
            // Initialize request argument(s)
            SearchGoogleAdsStreamRequest request = new SearchGoogleAdsStreamRequest
            {
                CustomerId        = "",
                Query             = "",
                SummaryRowSetting = SummaryRowSettingEnum.Types.SummaryRowSetting.Unspecified,
            };

            // Make the request, returning a streaming response
            GoogleAdsServiceClient.SearchStreamStream response = googleAdsServiceClient.SearchStream(request);

            // Read streaming responses from server until complete
            // Note that C# 8 code can use await foreach
            AsyncResponseStream <SearchGoogleAdsStreamResponse> responseStream = response.GetResponseStream();

            while (await responseStream.MoveNextAsync())
            {
                SearchGoogleAdsStreamResponse responseItem = responseStream.Current;
                // Do something with streamed response
            }
            // The response stream has completed
            // End snippet
        }
Пример #2
0
        public IActionResult GetCampaigns(long customerId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V10.GoogleAdsService);

            string query = "SELECT campaign.id, campaign.name, campaign.status FROM campaign " +
                           "ORDER BY campaign.id limit 100";

            List <string> campaigns = new List <string>();

            try
            {
                // Issue a search request.
                googleAdsService.SearchStream(customerId.ToString(), query,
                                              delegate(SearchGoogleAdsStreamResponse resp)
                {
                    foreach (GoogleAdsRow googleAdsRow in resp.Results)
                    {
                        // Note: We don't use the default JSON converter, to enable
                        // better JSON rendering of enum values.
                        campaigns.Add(JsonFormatter.Default.Format(googleAdsRow.Campaign));
                    }
                }
                                              );

                return(Content($"[{string.Join(",\n", campaigns)}]"));
            }
            catch (GoogleAdsException e)
            {
                return(Problem(e.Message));
            }
        }
Пример #3
0
        // [END migrate_promotion_feed_to_asset_1]

        /// <summary>
        /// Finds and returns all of the ad groups that are associated with the specified Promotion
        /// extension feed item.
        /// </summary>
        /// <param name="googleAdsServiceClient">An initialized Google Ads API Service
        /// client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="extensionFeedItemResourceName">Resource name of the extension feed item to
        /// migrate.</param>
        /// <returns>A list of ad group IDs.</returns>
        private List <long> GetTargetedAdGroupIds(
            GoogleAdsServiceClient googleAdsServiceClient, long customerId,
            string extensionFeedItemResourceName)
        {
            List <long> adGroupIds = new List <long>();

            string query = @"
                SELECT ad_group.id, ad_group_extension_setting.extension_feed_items
                FROM ad_group_extension_setting
                WHERE ad_group_extension_setting.extension_type = 'PROMOTION'
                  AND ad_group.status != 'REMOVED'";

            googleAdsServiceClient.SearchStream(customerId.ToString(), query,
                                                delegate(SearchGoogleAdsStreamResponse response)
            {
                foreach (GoogleAdsRow googleAdsRow in response.Results)
                {
                    // Add the ad group ID to the list of IDs if the extension feed item is
                    // associated with this extension setting.
                    if (googleAdsRow.AdGroupExtensionSetting.ExtensionFeedItems.Contains(
                            extensionFeedItemResourceName))
                    {
                        Console.WriteLine(
                            $"Found matching ad group with ID {googleAdsRow.AdGroup.Id}.");
                        adGroupIds.Add(googleAdsRow.AdGroup.Id);
                    }
                }
            }
                                                );

            return(adGroupIds);
        }
        /// <summary>
        /// Search for targetable languages by their name.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="languageName">The language name to search for.</param>
        private void SearchTargetableLanguages(GoogleAdsClient client, long customerId,
                                               string languageName)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService =
                client.GetService(Services.V4.GoogleAdsService);

            // Create a query that retrieves the language constants by the keyword included
            // in the name.
            string query = $"SELECT language_constant.id, language_constant.code, " +
                           $"language_constant.name, language_constant.targetable " +
                           $"FROM language_constant " +
                           $"WHERE language_constant.name LIKE '%{languageName}%'";

            // Issue a search request.
            googleAdsService.SearchStream(customerId.ToString(), query,
                                          delegate(SearchGoogleAdsStreamResponse resp)
            {
                foreach (GoogleAdsRow criterionRow in resp.Results)
                {
                    LanguageConstant language = criterionRow.LanguageConstant;
                    // Display the results.
                    Console.WriteLine($"Language with ID {language.Id}, code " +
                                      $"'{language.Code}', name '{language.Name}'and targetable:" +
                                      $" '{language.Targetable}' was found.");
                }
            });
        }
Пример #5
0
        // [END setup_remarketing_3]

        /// <summary>
        /// Finds all of user list ad group criteria under a campaign.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">The campaign in which to search the ad group criteria.</param>
        /// <returns>A list of ad group criteria resource names.</returns>
        // [START setup_remarketing_2]
        private List <string> GetUserListAdGroupCriteria(
            GoogleAdsClient client, long customerId, long campaignId)
        {
            // Get the GoogleAdsService client.
            GoogleAdsServiceClient googleAdsServiceClient =
                client.GetService(Services.V10.GoogleAdsService);

            List <string> userListCriteriaResourceNames = new List <string>();

            // Create a query that will retrieve all of the ad group criteria under a campaign.
            string query = $@"
                SELECT ad_group_criterion.criterion_id
                FROM ad_group_criterion
                WHERE
                  campaign.id = {campaignId}
                  AND ad_group_criterion.type = 'USER_LIST'";

            // Issue the search request.
            googleAdsServiceClient.SearchStream(customerId.ToString(), query,
                                                delegate(SearchGoogleAdsStreamResponse resp)
            {
                // Display the results and add the resource names to the list.
                foreach (GoogleAdsRow googleAdsRow in resp.Results)
                {
                    string adGroupCriterionResourceName =
                        googleAdsRow.AdGroupCriterion.ResourceName;
                    Console.WriteLine("Ad group criterion with resource name " +
                                      $"{adGroupCriterionResourceName} was found.");
                    userListCriteriaResourceNames.Add(adGroupCriterionResourceName);
                }
            });

            return(userListCriteriaResourceNames);
        }
        /// <summary>
        /// Searches the targetable carriers by country code.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="countryCode">The country code.</param>
        private void SearchTargetableCarriers(GoogleAdsClient client, long customerId,
                                              string countryCode)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService =
                client.GetService(Services.V4.GoogleAdsService);

            // Create a query that retrieves the targetable carriers by country code.
            string query = $"SELECT carrier_constant.id, carrier_constant.name, " +
                           $"carrier_constant.country_code FROM carrier_constant " +
                           $"WHERE carrier_constant.country_code = '{countryCode}'";

            // Issue a search request.
            googleAdsService.SearchStream(customerId.ToString(), query,
                                          delegate(SearchGoogleAdsStreamResponse resp)
            {
                // Display the results.
                foreach (GoogleAdsRow criterionRow in resp.Results)
                {
                    CarrierConstant carrier = criterionRow.CarrierConstant;
                    Console.WriteLine($"Carrier with ID {carrier.Id}, name '{carrier.Name}' " +
                                      $"and country code '{carrier.CountryCode}' was found.");
                }
            });
        }
Пример #7
0
        /// <summary>
        /// Prints information about the Customer Match user list.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which calls are made.
        /// </param>
        /// <param name="userListResourceName">The resource name of the Customer Match user list
        /// to print information about.</param>
        private void PrintCustomerMatchUserListInfo(GoogleAdsClient client, long customerId,
                                                    string userListResourceName)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient service =
                client.GetService(Services.V4.GoogleAdsService);

            // Creates a query that retrieves the user list.
            string query =
                "SELECT user_list.size_for_display, user_list.size_for_search " +
                "FROM user_list " +
                $"WHERE user_list.resource_name = '{userListResourceName}'";

            // Issues a search stream request.
            service.SearchStream(customerId.ToString(), query,
                                 delegate(SearchGoogleAdsStreamResponse resp)
            {
                // Display the results.
                foreach (GoogleAdsRow userListRow in resp.Results)
                {
                    UserList userList = userListRow.UserList;
                    Console.WriteLine("The estimated number of users that the user list " +
                                      $"'{userList.ResourceName}' has is {userList.SizeForDisplay}" +
                                      $" for Display and {userList.SizeForSearch} for Search.");
                }
            }
                                 );

            Console.WriteLine("Reminder: It may take several hours for the user list to be " +
                              "populated with the users so getting zeros for the estimations is expected.");
        }
Пример #8
0
        // [END create_cross_account_strategy]

        // [START list_manager_strategies]
        /// <summary>
        /// Lists all cross-account bidding strategies in a specified manager account.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="managerCustomerId">The manager customer ID.</param>
        private void ListManagerOwnedBiddingStrategies(GoogleAdsClient client,
                                                       long managerCustomerId)
        {
            GoogleAdsServiceClient googleAdsServiceClient =
                client.GetService(Services.V10.GoogleAdsService);

            // Create a GAQL query that will retrieve all cross-account bidding strategies.
            string query = @"
                SELECT
                  bidding_strategy.id,
                  bidding_strategy.name,
                  bidding_strategy.type,
                  bidding_strategy.currency_code
                FROM bidding_strategy";

            // Issue a streaming search request, then iterate through and print the results.
            googleAdsServiceClient.SearchStream(managerCustomerId.ToString(), query,
                                                delegate(SearchGoogleAdsStreamResponse resp)
            {
                Console.WriteLine("Cross-account bid strategies in manager account " +
                                  $"{managerCustomerId}:");

                foreach (GoogleAdsRow googleAdsRow in resp.Results)
                {
                    BiddingStrategy biddingStrategy = googleAdsRow.BiddingStrategy;

                    Console.WriteLine($"\tID: {biddingStrategy.Id}\n" +
                                      $"\tName: {biddingStrategy.Name}\n" +
                                      "\tStrategy type: " +
                                      $"{Enum.GetName(typeof(BiddingStrategyType), biddingStrategy.Type)}\n" +
                                      $"\tCurrency: {biddingStrategy.CurrencyCode}\n\n");
                }
            }
                                                );
        }
        /// <summary>
        /// Makes a server streaming call using a custom client timeout.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        // [START set_custom_client_timeouts]
        private void MakeServerStreamingCall(GoogleAdsClient client, long customerId)
        {
            StringWriter writer = new StringWriter();

            // Set a custom timeout.
            CallSettings callSettings = CallSettings.FromExpiration(
                Expiration.FromTimeout(TimeSpan.FromMilliseconds(CLIENT_TIMEOUT_MILLIS)));

            try
            {
                // Get the GoogleAdsService.
                GoogleAdsServiceClient googleAdsService = client.GetService(
                    Services.V10.GoogleAdsService);

                string query = "SELECT campaign.id FROM campaign";
                SearchGoogleAdsStreamRequest request = new SearchGoogleAdsStreamRequest()
                {
                    CustomerId = customerId.ToString(),
                    Query      = query
                };
                // Issue a search request.
                googleAdsService.SearchStream(request,
                                              delegate(SearchGoogleAdsStreamResponse resp)
                {
                    // Iterates over all rows in all messages and collects the campaign IDs.
                    foreach (GoogleAdsRow googleAdsRow in resp.Results)
                    {
                        writer.WriteLine(googleAdsRow.Campaign.Id);
                    }
                },
                                              callSettings
                                              );
                Console.WriteLine("The server streaming call completed before the timeout");
            }
            catch (GoogleAdsException ex)
            {
                if (ex.StatusCode == StatusCode.DeadlineExceeded)
                {
                    Console.WriteLine("The server streaming call did not complete before the " +
                                      "timeout.");
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                Console.WriteLine($"All campaign IDs retrieved: {writer}.");
            }
        }
        /// <summary>
        /// Initiates one asynchronous report download.
        /// </summary>
        /// <param name="googleAdsService">The Google Ads service client.</param>
        /// <param name="customerId">The customer ID from which data is requested.</param>
        /// <param name="queryKey">The name of the query to be downloaded.</param>
        /// <param name="queryValue">The query for the download request.</param>
        /// <param name="responses">Collection of all successful report downloads.</param>
        /// <returns>The asynchronous operation.</returns>
        /// <exception cref="GoogleAdsException">Thrown if errors encountered in the execution of
        ///     the request.</exception>
        private Task <bool> DownloadReportAsync(
            GoogleAdsServiceClient googleAdsService, long customerId, string queryKey,
            string queryValue, ConcurrentBag <ReportDownload> responses)
        {
            try
            {
                // Issue an asynchronous download request.
                googleAdsService.SearchStream(
                    customerId.ToString(), queryValue,
                    delegate(SearchGoogleAdsStreamResponse resp)
                {
                    // Store the results.
                    responses.Add(new ReportDownload()
                    {
                        CustomerId = customerId,
                        QueryKey   = queryKey,
                        Response   = resp
                    });
                }
                    );
                return(Task.FromResult(true));
            }
            catch (AggregateException ae)
            {
                Console.WriteLine($"Download failed for {queryKey} and CID {customerId}!");

                GoogleAdsException gae = GoogleAdsException.FromTaskException(ae);

                var download = new ReportDownload()
                {
                    CustomerId = customerId,
                    QueryKey   = queryKey,
                    Exception  = gae
                };
                if (gae != null)
                {
                    Console.WriteLine($"Message: {gae.Message}");
                    Console.WriteLine($"Failure: {gae.Failure}");
                    Console.WriteLine($"Request ID: {gae.RequestId}");
                    download.Exception = gae;
                }
                else
                {
                    download.Exception = ae;
                }

                responses.Add(download);
                return(Task.FromResult(false));
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the AdGroupService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V10.GoogleAdsService);

            // [START get_pending_invitations]
            // Create the search query.
            string query =
                @"SELECT
                    customer_user_access_invitation.invitation_id,
                    customer_user_access_invitation.email_address,
                    customer_user_access_invitation.access_role,
                    customer_user_access_invitation.creation_date_time
                  FROM
                    customer_user_access_invitation
                  WHERE
                    customer_user_access_invitation.invitation_status=PENDING";

            try
            {
                // Issue a search request.
                googleAdsService.SearchStream(customerId.ToString(), query,
                                              delegate(SearchGoogleAdsStreamResponse resp)
                {
                    foreach (GoogleAdsRow googleAdsRow in resp.Results)
                    {
                        Console.WriteLine("A pending invitation with invitation ID = {0}, " +
                                          "email address = '{1}', access role = '{2}' and created on {3}" +
                                          " was found.",
                                          googleAdsRow.CustomerUserAccessInvitation.InvitationId,
                                          googleAdsRow.CustomerUserAccessInvitation.EmailAddress,
                                          googleAdsRow.CustomerUserAccessInvitation.AccessRole,
                                          googleAdsRow.CustomerUserAccessInvitation.CreationDateTime
                                          );
                    }
                }
                                              );
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
            // [END get_pending_invitations]
        }
Пример #12
0
        public static RepeatedField <GoogleAdsRow> SearchRequest(string customerID, string query, GoogleAdsServiceClient googleAdsService)
        {
            RepeatedField <GoogleAdsRow> results = new RepeatedField <GoogleAdsRow>();

            // Issue a search request.
            googleAdsService.SearchStream(customerID, query,
                                          delegate(SearchGoogleAdsStreamResponse resp)
            {
                for (int i = 0; i < resp.Results.Count; i++)
                {
                    results.Add(resp.Results[i]);
                }
            }
                                          );

            return(results);
        }
Пример #13
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="feedId">ID of the feed associated with the feed item set.</param>
        /// <param name="feedItemSetId">ID of the feed item set.</param>
        public void Run(GoogleAdsClient client, long customerId, long feedId, long feedItemSetId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V6.GoogleAdsService);

            string feedItemSetResourceName = ResourceNames.FeedItemSet(
                customerId, feedId, feedItemSetId);

            // Creates a query that retrieves all feed item set links associated with the
            // specified feed item set.
            string query = $@"
                SELECT
                    feed_item_set_link.feed_item
                FROM
                    feed_item_set_link
                WHERE
                    feed_item_set_link.feed_item_set = '{feedItemSetResourceName}'";

            try
            {
                Console.WriteLine("The feed items with the following resource names are linked " +
                                  $"with the feed item set with ID {feedItemSetId}:");

                // Issue a search request.
                googleAdsService.SearchStream(customerId.ToString(), query,
                                              delegate(SearchGoogleAdsStreamResponse resp)
                {
                    foreach (GoogleAdsRow googleAdsRow in resp.Results)
                    {
                        Console.WriteLine(googleAdsRow.FeedItemSetLink.FeedItem);
                    }
                }
                                              );
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Пример #14
0
        // [END list_manager_strategies]

        // [START list_accessible_strategies]
        /// <summary>
        /// Lists all bidding strategies available to specified client customer account. This
        /// includes both portfolio bidding strategies owned by the client customer account and
        /// cross-account bidding strategies shared by any of its managers.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads client customer ID for which the call is
        /// made.</param>
        private void ListCustomerAccessibleBiddingStrategies(GoogleAdsClient client,
                                                             long customerId)
        {
            GoogleAdsServiceClient googleAdsServiceClient =
                client.GetService(Services.V10.GoogleAdsService);

            // Create a GAQL query that will retrieve all accessible bidding strategies.
            string query = @"
                SELECT
                  accessible_bidding_strategy.resource_name,
                  accessible_bidding_strategy.id,
                  accessible_bidding_strategy.name,
                  accessible_bidding_strategy.type,
                  accessible_bidding_strategy.owner_customer_id,
                  accessible_bidding_strategy.owner_descriptive_name
                FROM accessible_bidding_strategy";

            // Uncomment the following WHERE clause addition to the query to filter results to
            // *only* cross-account bidding strategies shared with the current customer by a manager
            // (and not also include the current customer's portfolio bidding strategies).
            // query += $" WHERE accessible_bidding_strategy.owner_customer_id != {customerId}";

            // Issue a streaming search request, then iterate through and print the results.
            googleAdsServiceClient.SearchStream(customerId.ToString(), query,
                                                delegate(SearchGoogleAdsStreamResponse resp)
            {
                Console.WriteLine($"All bid strategies accessible by account {customerId}:");

                foreach (GoogleAdsRow googleAdsRow in resp.Results)
                {
                    AccessibleBiddingStrategy biddingStrategy =
                        googleAdsRow.AccessibleBiddingStrategy;

                    Console.WriteLine($"\tID: {biddingStrategy.Id}\n" +
                                      $"\tName: {biddingStrategy.Name}\n" +
                                      $"\tStrategy type: {biddingStrategy.Type.ToString()}\n" +
                                      $"\tOwner customer ID: {biddingStrategy.OwnerCustomerId}\n" +
                                      $"\tOwner description: {biddingStrategy.OwnerDescriptiveName}\n\n");
                }
            }
                                                );
        }
Пример #15
0
        /// <summary>Snippet for SearchStream</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task SearchStream()
        {
            // Create client
            GoogleAdsServiceClient googleAdsServiceClient = GoogleAdsServiceClient.Create();
            // Initialize request argument(s)
            string customerId = "";
            string query      = "";

            // Make the request, returning a streaming response
            GoogleAdsServiceClient.SearchStreamStream response = googleAdsServiceClient.SearchStream(customerId, query);

            // Read streaming responses from server until complete
            // Note that C# 8 code can use await foreach
            AsyncResponseStream <SearchGoogleAdsStreamResponse> responseStream = response.GetResponseStream();

            while (await responseStream.MoveNextAsync())
            {
                SearchGoogleAdsStreamResponse responseItem = responseStream.Current;
                // Do something with streamed response
            }
            // The response stream has completed
        }
Пример #16
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V4.GoogleAdsService);

            // Create a query that will retrieve all campaigns.
            string query = @"SELECT
                            campaign.id,
                            campaign.name,
                            campaign.network_settings.target_content_network
                        FROM campaign
                        ORDER BY campaign.id";

            try
            {
                // Issue a search request.
                googleAdsService.SearchStream(customerId.ToString(), query,
                                              delegate(SearchGoogleAdsStreamResponse resp)
                {
                    foreach (GoogleAdsRow googleAdsRow in resp.Results)
                    {
                        Console.WriteLine("Campaign with ID {0} and name '{1}' was found.",
                                          googleAdsRow.Campaign.Id, googleAdsRow.Campaign.Name);
                    }
                }
                                              );
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Пример #17
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer Id.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V4.GoogleAdsService);

            // Create the query.
            string query =
                $@"SELECT
                 campaign.id,
                 campaign.name,
                 ad_group.id,
                 ad_group.name,
                 ad_group_criterion.criterion_id,
                 ad_group_criterion.keyword.text,
                 ad_group_criterion.keyword.match_type,
                 metrics.impressions,
                 metrics.clicks,
                 metrics.cost_micros,
                 metrics.video_quartile_25_rate
             FROM keyword_view
             WHERE segments.date DURING LAST_7_DAYS
                 AND campaign.advertising_channel_type = 'SEARCH'
                 AND ad_group.status = 'ENABLED'
                 AND ad_group_criterion.status IN ('ENABLED','PAUSED')
             ORDER BY metrics.impressions DESC
             LIMIT 50";

            try
            {
                // Issue a search request.
                googleAdsService.SearchStream(customerId.ToString(), query,
                                              delegate(SearchGoogleAdsStreamResponse resp)
                {
                    // Display the results.
                    foreach (GoogleAdsRow criterionRow in resp.Results)
                    {
                        Console.WriteLine(
                            $"Keyword with text " +
                            $"'{criterionRow.AdGroupCriterion.Keyword.Text}', match type " +
                            $"'{criterionRow.AdGroupCriterion.Keyword.MatchType}' and ID " +
                            $"{criterionRow.AdGroupCriterion.CriterionId} in ad group " +
                            $"'{criterionRow.AdGroup.Name}' with ID " +
                            $"{criterionRow.AdGroup.Id} in campaign " +
                            $"'{criterionRow.Campaign.Name}' with ID " +
                            $"{criterionRow.Campaign.Id} had " +
                            $"{criterionRow.Metrics.Impressions.ToString()} impressions, " +
                            $"{criterionRow.Metrics.Clicks} clicks, and " +
                            $"{criterionRow.Metrics.CostMicros} cost (in micros) during the " +
                            $"last 7 days.");
                    }
                }
                                              );
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Пример #18
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsServiceClient.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V4.GoogleAdsService);

            // Construct a GAQL query which will retrieve AccountBudgetProposals.
            String query =
                @"SELECT
                    account_budget.status,
                    account_budget.billing_setup,
                    account_budget.approved_spending_limit_micros,
                    account_budget.approved_spending_limit_type,
                    account_budget.proposed_spending_limit_micros,
                    account_budget.proposed_spending_limit_type,
                    account_budget.adjusted_spending_limit_micros,
                    account_budget.adjusted_spending_limit_type,
                    account_budget.approved_start_date_time,
                    account_budget.proposed_start_date_time,
                    account_budget.approved_end_date_time,
                    account_budget.approved_end_time_type,
                    account_budget.proposed_end_date_time,
                    account_budget.proposed_end_time_type
                 FROM
                     account_budget";

            try
            {
                // Issues the search request.
                googleAdsService.SearchStream(customerId.ToString(), query,
                                              delegate(SearchGoogleAdsStreamResponse resp)
                {
                    // Displays the results
                    foreach (GoogleAdsRow googleAdsRow in resp.Results)
                    {
                        AccountBudget budget = googleAdsRow.AccountBudget;

                        Console.WriteLine(String.Format("Account budget '{0}' with status '{1}', " +
                                                        "billing setup '{2}', amount served {3:0.00}, total adjustments " +
                                                        "{4:0.00}, approved spending limit '{5}' (proposed '{6}', " +
                                                        "adjusted '{7}'), approved start time '{8}' (proposed '{9}'), " +
                                                        "approved end time '{10}' (proposed '{11}')",
                                                        budget.ResourceName,
                                                        budget.Status,
                                                        budget.BillingSetup,
                                                        budget.AmountServedMicros.Value / 1_000_000.0,
                                                        budget.TotalAdjustmentsMicros.Value / 1_000_000.0,
                                                        budget.ApprovedSpendingLimitMicros.HasValue
                                    ? String.Format(
                                                            "%.2f", budget.ApprovedSpendingLimitMicros.Value / 1_000_000.0)
                                    : budget.ApprovedSpendingLimitType.ToString(),
                                                        budget.ProposedSpendingLimitMicros.HasValue
                                    ? String.Format(
                                                            "%.2f", budget.ProposedSpendingLimitMicros.Value / 1_000_000.0)
                                    : budget.ProposedSpendingLimitType.ToString(),
                                                        budget.AdjustedSpendingLimitMicros.HasValue
                                    ? String.Format(
                                                            "%.2f", budget.AdjustedSpendingLimitMicros.Value / 1_000_000.0)
                                    : budget.AdjustedSpendingLimitType.ToString(),
                                                        budget.ApprovedStartDateTime,
                                                        budget.ProposedStartDateTime,
                                                        String.IsNullOrEmpty(budget.ApprovedEndDateTime)
                                    ? budget.ApprovedEndTimeType.ToString()
                                    : budget.ApprovedEndDateTime,
                                                        String.IsNullOrEmpty(budget.ProposedEndDateTime)
                                    ? budget.ProposedEndTimeType.ToString()
                                    : budget.ProposedEndDateTime));
                    }
                }
                                              );
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Пример #19
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        // [START get_change_details]
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V10.GoogleAdsService);

            // Construct a query to find details for recent changes in your account.
            // The LIMIT clause is required for the change_event resource.
            // The maximum size is 10000, but a low limit was set here for demonstrative
            // purposes.
            // The WHERE clause on change_date_time is also required. It must specify a
            // window of at most 30 days within the past 30 days.

            string startDate   = DateTime.Today.Subtract(TimeSpan.FromDays(25)).ToString("yyyyMMdd");
            string endDate     = DateTime.Today.Add(TimeSpan.FromDays(1)).ToString("yyyyMMdd");
            string searchQuery = $@"
                SELECT
                    change_event.resource_name,
                    change_event.change_date_time,
                    change_event.change_resource_name,
                    change_event.user_email,
                    change_event.client_type,
                    change_event.change_resource_type,
                    change_event.old_resource,
                    change_event.new_resource,
                    change_event.resource_change_operation,
                    change_event.changed_fields
                FROM
                    change_event
                WHERE
                    change_event.change_date_time >= '{startDate}' AND
                    change_event.change_date_time <= '{endDate}'
                ORDER BY
                    change_event.change_date_time DESC
                LIMIT 5";

            try
            {
                // Issue a search request.
                googleAdsService.SearchStream(customerId.ToString(), searchQuery,
                                              delegate(SearchGoogleAdsStreamResponse resp)
                {
                    // Display the results.
                    foreach (GoogleAdsRow googleAdsRow in resp.Results)
                    {
                        ChangeEvent changeEvent     = googleAdsRow.ChangeEvent;
                        ChangedResource oldResource = changeEvent.OldResource;
                        ChangedResource newResource = changeEvent.NewResource;

                        bool knownResourceType     = true;
                        IMessage oldResourceEntity = null;
                        IMessage newResourceEntity = null;
                        switch (changeEvent.ChangeResourceType)
                        {
                        case ChangeEventResourceType.Ad:
                            oldResourceEntity = oldResource.Ad;
                            newResourceEntity = newResource.Ad;
                            break;

                        case ChangeEventResourceType.AdGroup:
                            oldResourceEntity = oldResource.AdGroup;
                            newResourceEntity = newResource.AdGroup;
                            break;

                        case ChangeEventResourceType.AdGroupAd:
                            oldResourceEntity = oldResource.AdGroupAd;
                            newResourceEntity = newResource.AdGroupAd;
                            break;

                        case ChangeEventResourceType.AdGroupAsset:
                            oldResourceEntity = oldResource.AdGroupAsset;
                            newResourceEntity = newResource.AdGroupAsset;
                            break;

                        case ChangeEventResourceType.AdGroupBidModifier:
                            oldResourceEntity = oldResource.AdGroupBidModifier;
                            newResourceEntity = newResource.AdGroupBidModifier;
                            break;

                        case ChangeEventResourceType.AdGroupCriterion:
                            oldResourceEntity = oldResource.AdGroupCriterion;
                            newResourceEntity = newResource.AdGroupCriterion;
                            break;

                        case ChangeEventResourceType.AdGroupFeed:
                            oldResourceEntity = oldResource.AdGroupFeed;
                            newResourceEntity = newResource.AdGroupFeed;
                            break;

                        case ChangeEventResourceType.Asset:
                            oldResourceEntity = oldResource.Asset;
                            newResourceEntity = newResource.Asset;
                            break;

                        case ChangeEventResourceType.AssetSet:
                            oldResourceEntity = oldResource.AssetSet;
                            newResourceEntity = newResource.AssetSet;
                            break;

                        case ChangeEventResourceType.AssetSetAsset:
                            oldResourceEntity = oldResource.AssetSetAsset;
                            newResourceEntity = newResource.AssetSetAsset;
                            break;

                        case ChangeEventResourceType.Campaign:
                            oldResourceEntity = oldResource.Campaign;
                            newResourceEntity = newResource.Campaign;
                            break;

                        case ChangeEventResourceType.CampaignAsset:
                            oldResourceEntity = oldResource.CampaignAsset;
                            newResourceEntity = newResource.CampaignAsset;
                            break;

                        case ChangeEventResourceType.CampaignAssetSet:
                            oldResourceEntity = oldResource.CampaignAssetSet;
                            newResourceEntity = newResource.CampaignAssetSet;
                            break;

                        case ChangeEventResourceType.CampaignBudget:
                            oldResourceEntity = oldResource.CampaignBudget;
                            newResourceEntity = newResource.CampaignBudget;
                            break;

                        case ChangeEventResourceType.CampaignCriterion:
                            oldResourceEntity = oldResource.CampaignCriterion;
                            newResourceEntity = newResource.CampaignCriterion;
                            break;

                        case ChangeEventResourceType.CampaignFeed:
                            oldResourceEntity = oldResource.CampaignFeed;
                            newResourceEntity = newResource.CampaignFeed;
                            break;

                        case ChangeEventResourceType.CustomerAsset:
                            oldResourceEntity = oldResource.CustomerAsset;
                            newResourceEntity = newResource.CustomerAsset;
                            break;

                        case ChangeEventResourceType.Feed:
                            oldResourceEntity = oldResource.Feed;
                            newResourceEntity = newResource.Feed;
                            break;

                        case ChangeEventResourceType.FeedItem:
                            oldResourceEntity = oldResource.FeedItem;
                            newResourceEntity = newResource.FeedItem;
                            break;

                        default:
                            knownResourceType = false;
                            break;
                        }

                        if (!knownResourceType)
                        {
                            Console.WriteLine($"Unknown change_resource_type " +
                                              $"'{changeEvent.ChangeResourceType}'.");
                            continue;
                        }

                        Console.WriteLine($"On #{changeEvent.ChangeDateTime}, user " +
                                          $"{changeEvent.UserEmail} used interface {changeEvent.ClientType} " +
                                          $"to perform a(n) '{changeEvent.ResourceChangeOperation}' " +
                                          $"operation on a '{changeEvent.ChangeResourceType}' with " +
                                          $"resource name {changeEvent.ChangeResourceName}.");

                        foreach (string fieldMaskPath in changeEvent.ChangedFields.Paths)
                        {
                            if (changeEvent.ResourceChangeOperation ==
                                ResourceChangeOperation.Create)
                            {
                                object newValue = FieldMasks.GetFieldValue(
                                    fieldMaskPath, newResourceEntity);
                                Console.WriteLine($"\t{fieldMaskPath} set to '{newValue}'.");
                            }
                            else if (changeEvent.ResourceChangeOperation ==
                                     ResourceChangeOperation.Update)
                            {
                                object oldValue = FieldMasks.GetFieldValue(fieldMaskPath,
                                                                           oldResourceEntity);
                                object newValue = FieldMasks.GetFieldValue(fieldMaskPath,
                                                                           newResourceEntity);

                                Console.WriteLine($"\t{fieldMaskPath} changed from " +
                                                  $"'{oldValue}' to '{newValue}'.");
                            }
                        }
                    }
                });
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">The campaign ID to get the criterion bid modifier
        ///     simulations.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V10.GoogleAdsService);

            // Creates a query that retrieves the criterion bid modifier simulations.
            string query = $@"
                SELECT
                    campaign_criterion_simulation.criterion_id,
                    campaign_criterion_simulation.start_date,
                    campaign_criterion_simulation.end_date,
                    campaign_criterion_simulation.bid_modifier_point_list.points
                FROM campaign_criterion_simulation
                WHERE campaign_criterion_simulation.type = BID_MODIFIER
                AND campaign_criterion_simulation.campaign_id = {campaignId}";

            try
            {
                // Issue a search request.
                googleAdsService.SearchStream(customerId.ToString(), query,
                                              delegate(SearchGoogleAdsStreamResponse response)
                {
                    // Iterates over all rows in all messages and prints the requested field
                    // values for the campaign criterion bid modifier simulation in each row.
                    foreach (GoogleAdsRow googleAdsRow in response.Results)
                    {
                        CampaignCriterionSimulation simulation =
                            googleAdsRow.CampaignCriterionSimulation;
                        Console.WriteLine($@"Found campaign-level criterion bid modifier
                                simulation for criterion with ID
                                {simulation.CriterionId}, start date
                                {simulation.StartDate}, end date
                                {simulation.EndDate}, and points:");
                        foreach (BidModifierSimulationPoint point in
                                 simulation.BidModifierPointList.Points)
                        {
                            Console.WriteLine($"\tbid modifier: {point.BidModifier:F} " +
                                              $"=> clicks: {point.Clicks}, " +
                                              $"cost: {point.CostMicros}, " +
                                              $"impressions: {point.Impressions}, " +
                                              $"parent clicks: {point.ParentClicks}, " +
                                              $"parent cost: {point.ParentCostMicros}, " +
                                              $"parent impressions: {point.ParentImpressions}, " +
                                              $"parent required budget: {point.ParentRequiredBudgetMicros}");
                        }

                        Console.WriteLine();
                    }
                }
                                              );
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="outputFilePath">The path to which the CSV file is written.</param>
        public void Run(GoogleAdsClient client, long customerId, string outputFilePath)
        {
            GoogleAdsServiceClient googleAdsServiceClient =
                client.GetService(Services.V10.GoogleAdsService);

            // Create a query that retrieves campaigns.
            string query = @"
                SELECT
                    campaign.id,
                    campaign.name,
                    segments.date,
                    metrics.impressions,
                    metrics.clicks,
                    metrics.cost_micros
                FROM campaign
                WHERE segments.date DURING LAST_30_DAYS
                    AND campaign.status = 'ENABLED'
                ORDER BY segments.date DESC";

            // Issues a search request.
            googleAdsServiceClient.SearchStream(customerId.ToString(), query,
                                                delegate(SearchGoogleAdsStreamResponse response)
            {
                if (response.Results.Count() == 0)
                {
                    Console.WriteLine("No results found!");
                    return;
                }

                CsvFile csvFile = new CsvFile();

                // Set the header for the CSV file.
                csvFile.Headers.AddRange(response.FieldMask.Paths);

                // Iterate over all returned rows and extract the information.
                foreach (GoogleAdsRow googleAdsRow in response.Results)
                {
                    csvFile.Records.Add(new string[]
                    {
                        googleAdsRow.Campaign.Id.ToString(),
                        googleAdsRow.Campaign.Name,
                        googleAdsRow.Segments.Date,
                        googleAdsRow.Metrics.Impressions.ToString(),
                        googleAdsRow.Metrics.Clicks.ToString(),
                        googleAdsRow.Metrics.CostMicros.ToString()
                    });
                }

                if (outputFilePath == null)
                {
                    outputFilePath =
                        Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
                        Path.DirectorySeparatorChar +
                        GetType().Name +
                        DateTime.Now.ToString("-yyyyMMMMdd-HHmmss") + ".csv";
                }
                else if (!outputFilePath.EndsWith(".csv"))
                {
                    outputFilePath += ".csv";
                }

                // Create the file with the specified path, write all lines, and close it.
                csvFile.Write(outputFilePath);

                Console.WriteLine(
                    $"Successfully wrote {response.Results.Count()} entries to {outputFilePath}.");
            }
                                                );
        }
Пример #22
0
        /// <summary>
        /// Gets the requested Promotion-type extension feed item.
        ///
        /// Note that extension feed items pertain to feeds that were created by Google. Use
        /// FeedService to instead retrieve a user-created Feed.
        /// </summary>
        /// <param name="googleAdsServiceClient">An initialized Google Ads API Service
        /// client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="feedItemId">ID of the extension feed item to migrate.</param>
        /// <returns>The requested ExtensionFeedItem, or null if no matching item was
        /// found.</returns>
        private ExtensionFeedItem GetExtensionFeedItem(
            GoogleAdsServiceClient googleAdsServiceClient,
            long customerId, long feedItemId)
        {
            // Create a query that will retrieve the requested Promotion-type extension feed item
            // and ensure that all fields are populated.
            string extensionFeedItemQuery = $@"
                SELECT
                    extension_feed_item.id,
                    extension_feed_item.ad_schedules,
                    extension_feed_item.device,
                    extension_feed_item.status,
                    extension_feed_item.start_date_time,
                    extension_feed_item.end_date_time,
                    extension_feed_item.targeted_campaign,
                    extension_feed_item.targeted_ad_group,
                    extension_feed_item.promotion_feed_item.discount_modifier,
                    extension_feed_item.promotion_feed_item.final_mobile_urls,
                    extension_feed_item.promotion_feed_item.final_url_suffix,
                    extension_feed_item.promotion_feed_item.final_urls,
                    extension_feed_item.promotion_feed_item.language_code,
                    extension_feed_item.promotion_feed_item.money_amount_off.amount_micros,
                    extension_feed_item.promotion_feed_item.money_amount_off.currency_code,
                    extension_feed_item.promotion_feed_item.occasion,
                    extension_feed_item.promotion_feed_item.orders_over_amount.amount_micros,
                    extension_feed_item.promotion_feed_item.orders_over_amount.currency_code,
                    extension_feed_item.promotion_feed_item.percent_off,
                    extension_feed_item.promotion_feed_item.promotion_code,
                    extension_feed_item.promotion_feed_item.promotion_end_date,
                    extension_feed_item.promotion_feed_item.promotion_start_date,
                    extension_feed_item.promotion_feed_item.promotion_target,
                    extension_feed_item.promotion_feed_item.tracking_url_template
                FROM extension_feed_item
                WHERE
                    extension_feed_item.extension_type = 'PROMOTION'
                    AND extension_feed_item.id = {feedItemId}
                LIMIT 1";

            ExtensionFeedItem fetchedExtensionFeedItem = null;

            // Issue a search request to get the extension feed item contents.
            googleAdsServiceClient.SearchStream(customerId.ToString(), extensionFeedItemQuery,
                                                delegate(SearchGoogleAdsStreamResponse response)
            {
                fetchedExtensionFeedItem = response.Results.First().ExtensionFeedItem;
            }
                                                );
            Console.WriteLine(
                $"Retrieved details for ad extension with ID {fetchedExtensionFeedItem.Id}.");

            // Create a query to retrieve any URL customer parameters attached to the feed item.
            string urlCustomParametersQuery = $@"
                SELECT feed_item.url_custom_parameters
                FROM feed_item
                WHERE feed_item.id = {feedItemId}";

            // Issue a search request to get any URL custom parameters.
            googleAdsServiceClient.SearchStream(customerId.ToString(), urlCustomParametersQuery,
                                                delegate(SearchGoogleAdsStreamResponse response)
            {
                RepeatedField <CustomParameter> urlCustomParameters =
                    response.Results.First().FeedItem.UrlCustomParameters;
                Console.WriteLine(
                    $"Retrieved {urlCustomParameters.Count} attached URL custom parameters.");
                if (urlCustomParameters.Count > 0)
                {
                    fetchedExtensionFeedItem.PromotionFeedItem.UrlCustomParameters.Add(
                        urlCustomParameters);
                }
            }
                                                );

            return(fetchedExtensionFeedItem);
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupId">The ad group ID for which to get ad group criterion CPC bid
        ///     simulations.</param>
        public void Run(GoogleAdsClient client, long customerId, long adGroupId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService =
                client.GetService(Services.V4.GoogleAdsService);

            try
            {
                // Creates a query that retrieves the ad group criterion CPC bid simulations.
                string query = $@"
                    SELECT
                        ad_group_criterion_simulation.ad_group_id,
                        ad_group_criterion_simulation.criterion_id,
                        ad_group_criterion_simulation.start_date,
                        ad_group_criterion_simulation.end_date,
                        ad_group_criterion_simulation.cpc_bid_point_list.points
                    FROM
                        ad_group_criterion_simulation
                    WHERE
                        ad_group_criterion_simulation.type = CPC_BID AND
                        ad_group_criterion_simulation.ad_group_id = {adGroupId}";

                // Issue a search stream request.
                googleAdsService.SearchStream(customerId.ToString(), query,
                                              delegate(SearchGoogleAdsStreamResponse response)
                {
                    // Iterates over all rows in all messages and prints the requested field
                    // values for the ad group criterion CPC bid simulation in each row.
                    foreach (GoogleAdsRow googleAdsRow in response.Results)
                    {
                        AdGroupCriterionSimulation simulation =
                            googleAdsRow.AdGroupCriterionSimulation;

                        Console.WriteLine("Found ad group criterion CPC bid simulation for " +
                                          $"ad group ID {simulation.AdGroupId}, " +
                                          $"criterion ID {simulation.CriterionId}, " +
                                          $"start date {simulation.StartDate}, " +
                                          $"end date {simulation.EndDate}");

                        foreach (CpcBidSimulationPoint point in
                                 simulation.CpcBidPointList.Points)
                        {
                            Console.WriteLine($"\tbid: {point.CpcBidMicros} => " +
                                              $"clicks: {point.Clicks}, " +
                                              $"cost: {point.CostMicros}, " +
                                              $"impressions: {point.Impressions}, " +
                                              $"biddable conversions: {point.BiddableConversions}, " +
                                              "biddable conversions value: " +
                                              $"{point.BiddableConversionsValue}");
                        }

                        Console.WriteLine();
                    }
                }
                                              );
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Пример #24
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="omitUnselectedResourceNames">Specifies whether to omit unselected resource
        /// names from response.</param>
        public void Run(GoogleAdsClient client, long customerId, bool?omitUnselectedResourceNames)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V10.GoogleAdsService);

            try
            {
                string query =
                    $@"SELECT
                        ad_group.id,
                        ad_group.status,
                        ad_group_criterion.criterion_id,
                        ad_group_criterion.keyword.text,
                        ad_group_criterion.keyword.match_type
                    FROM ad_group_criterion
                    WHERE ad_group_criterion.type = 'KEYWORD'
                        AND ad_group.status = 'ENABLED'
                        AND ad_group_criterion.status IN ('ENABLED', 'PAUSED')";

                // Adds omit_unselected_resource_names=true to the PARAMETERS clause of the
                // Google Ads Query Language (GAQL) query, which excludes the resource names of
                // all resources that aren't explicitly requested in the SELECT clause.
                // Enabling this option reduces payload size, but if you plan to use a returned
                // object in subsequent mutate operations, make sure you explicitly request its
                // "resource_name" field in the SELECT clause.
                //
                // Read more about PARAMETERS:
                // https://developers.google.com/google-ads/api/docs/query/structure#parameters
                if (omitUnselectedResourceNames.HasValue && omitUnselectedResourceNames.Value)
                {
                    query += " PARAMETERS omit_unselected_resource_names=true";
                }

                googleAdsService.SearchStream(customerId.ToString(), query,
                                              delegate(SearchGoogleAdsStreamResponse resp)
                {
                    foreach (GoogleAdsRow criterionRow in resp.Results)
                    {
                        AdGroup adGroup            = criterionRow.AdGroup;
                        AdGroupCriterion criterion = criterionRow.AdGroupCriterion;
                        string andResourceName     = null;
                        if (omitUnselectedResourceNames.HasValue &&
                            omitUnselectedResourceNames.Value)
                        {
                            andResourceName = "";
                        }
                        else
                        {
                            andResourceName = $" and resource name '{adGroup.ResourceName}'";
                        }

                        Console.WriteLine("Keyword with text '{0}', id = '{1}' and " +
                                          "match type = '{2}' was retrieved for ad group '{3}'{4}.",
                                          criterion.Keyword.Text, criterion.CriterionId,
                                          criterion.Keyword.MatchType, adGroup.Id, andResourceName);
                    }
                }
                                              );
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }