/// <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.V3.GoogleAdsService); // Construct a GAQL query which will retrieve AccountBudgetProposals. String searchQuery = @"SELECT account_budget_proposal.id, account_budget_proposal.account_budget, account_budget_proposal.billing_setup, account_budget_proposal.status, account_budget_proposal.proposed_name, account_budget_proposal.proposed_notes, account_budget_proposal.proposed_purchase_order_number, account_budget_proposal.proposal_type, account_budget_proposal.approval_date_time, account_budget_proposal.creation_date_time FROM account_budget_proposal"; // Creates a request that will retrieve all account budget proposals using pages of the // specified page size. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { PageSize = PAGE_SIZE, Query = searchQuery, CustomerId = customerId.ToString() }; try { // Issues the search request. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); // Iterates over all rows in all pages and prints the requested field values for // the account budget in each row. foreach (GoogleAdsRow googleAdsRow in searchPagedResponse) { AccountBudgetProposal proposal = googleAdsRow.AccountBudgetProposal; Console.WriteLine($"Account budget proposal with ID '{proposal.Id}' " + $"status '{proposal.Status}', account_budget '{proposal.AccountBudget}' " + $"billing_setup '{proposal.BillingSetup}', " + $"proposed_name '{proposal.ProposedName}', " + $"proposed_notes '{proposal.ProposedNotes}', " + $"proposed_po_number '{proposal.ProposedPurchaseOrderNumber}', " + $"proposal_type '{proposal.ProposalType}', " + $"approval_date_time '{proposal.ApprovalDateTime}', " + $"creation_date_time '{proposal.CreationDateTime}'."); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); } }
/// <summary> /// Retrieves all the attributes for a feed and returns them in a map using the /// attribute names as keys. /// </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="feedResourceName">The resource name of the feed.</param> /// <returns>The attributes of the feed.</returns> private Dictionary <string, FeedAttribute> GetFeedAttributes(GoogleAdsClient client, long customerId, string feedResourceName) { // Get the GoogleAdsServiceClient. GoogleAdsServiceClient googleAdsService = client.GetService(Services.V4.GoogleAdsService); string query = $"SELECT feed.attributes, feed.name FROM feed WHERE " + $"feed.resource_name = '{feedResourceName}'"; SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), Query = query }; Dictionary <string, FeedAttribute> feedAttributes = new Dictionary <string, FeedAttribute>(); Feed feed = googleAdsService.Search(request).First().Feed; Console.WriteLine($"Found the following attributes for feed with name '{feed.Name}'"); foreach (FeedAttribute feedAttribute in feed.Attributes) { Console.WriteLine($"\t'{feedAttribute.Name}' with id {feedAttribute.Id} and " + $"type '{feedAttribute.Type}'"); feedAttributes[feedAttribute.Name] = feedAttribute; } return(feedAttributes); }
// [END add_performance_max_retail_campaign_8] // [START add_performance_max_retail_campaign_9] /// <summary> /// Retrieves the list of customer conversion goals. /// </summary> /// <param name="client">The Google Ads Client.</param> /// <param name="customerId">The customer's id.</param> /// <returns>A list customer conversion goals.</returns> private List <CustomerConversionGoal> GetCustomerConversionGoals( GoogleAdsClient client, long customerId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsServiceClient = client.GetService(Services.V10.GoogleAdsService); List <CustomerConversionGoal> conversionGoals = new List <CustomerConversionGoal>(); SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), PageSize = 10000, Query = @"SELECT customer_conversion_goal.category, customer_conversion_goal.origin FROM customer_conversion_goal" }; // The number of conversion goals is typically less than 50 so we use // GoogleAdsService.search instead of search_stream. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsServiceClient.Search(request); // Iterate over the results and build the list of conversion goals. foreach (GoogleAdsRow row in searchPagedResponse) { conversionGoals.Add(row.CustomerConversionGoal); } return(conversionGoals); }
/// <summary> /// Retrieves details about a feed. The initial query retrieves the FeedAttributes, /// or columns, of the feed. Each FeedAttribute will also include the FeedAttributeId, /// which will be used in a subsequent step. The example then inserts a new key, value /// pair into a map for each FeedAttribute, which is the return value of the method. /// The keys are the placeholder types that the columns will be. The values are the /// FeedAttributes. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the flights feed is /// added.</param> /// <param name="feedResourceName">The resource name of the feed.</param> /// <returns> /// A Map containing the FlightPlaceholderField and FeedAttribute. /// </returns> public Dictionary <FlightPlaceholderField, FeedAttribute> GetFeed( GoogleAdsClient client, long customerId, string feedResourceName) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V5.GoogleAdsService); // Constructs the query. string query = $"SELECT feed.attributes FROM feed WHERE feed.resource_name = " + $"'{feedResourceName}'"; // Constructs the request. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), Query = query }; // Issues the search request and get the first result, since we only need the // single feed item we created previously. GoogleAdsRow googleAdsRow = googleAdsService.Search(request).First(); // Gets the attributes list from the feed and creates a map with keys of each attribute and // values of each corresponding ID. Dictionary <FlightPlaceholderField, FeedAttribute> feedAttributes = new Dictionary <FlightPlaceholderField, FeedAttribute>(); // Loops through the feed attributes to populate the map. foreach (FeedAttribute feedAttribute in googleAdsRow.Feed.Attributes) { switch (feedAttribute.Name) { case "Flight Description": feedAttributes[FlightPlaceholderField.FlightDescription] = feedAttribute; break; case "Destination ID": feedAttributes[FlightPlaceholderField.DestinationId] = feedAttribute; break; case "Flight Price": feedAttributes[FlightPlaceholderField.FlightPrice] = feedAttribute; break; case "Flight Sale Price": feedAttributes[FlightPlaceholderField.FlightSalePrice] = feedAttribute; break; case "Final URLs": feedAttributes[FlightPlaceholderField.FinalUrls] = feedAttribute; break; // The full list of FlightPlaceholderFields can be found here // https://developers.google.com/google-ads/api/reference/rpc/latest/FlightPlaceholderFieldEnum.FlightPlaceholderField default: throw new Exception("Invalid attribute name."); } } return(feedAttributes); }
/// <summary> /// Returns all rows that match the search query. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="GoogleAdsRow"/> resources. /// </returns> public override gax::PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> Search( SearchGoogleAdsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SearchGoogleAdsRequest(ref request, ref callSettings); return(new gaxgrpc::GrpcPagedEnumerable <SearchGoogleAdsRequest, SearchGoogleAdsResponse, GoogleAdsRow>(_callSearch, request, callSettings)); }
/// <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">Optional: ID of the ad group to restrict search to.</param> public void Run(GoogleAdsClient client, long customerId, long?adGroupId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V3.GoogleAdsService); string searchQuery = $@"SELECT ad_group.id, ad_group_ad.ad.id, ad_group_ad.ad.expanded_text_ad.headline_part1, ad_group_ad.ad.expanded_text_ad.headline_part2, ad_group_ad.status FROM ad_group_ad WHERE ad_group_ad.ad.type = EXPANDED_TEXT_AD "; if (adGroupId != null) { searchQuery += $" AND ad_group.id = {adGroupId}"; } // Create a request that will retrieve all ads using pages of the specified page size. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), PageSize = PAGE_SIZE, Query = searchQuery }; try { // Issue the search request. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); // Iterate over all rows in all pages and prints the requested field values for // the ad in each row. foreach (GoogleAdsRow googleAdsRow in searchPagedResponse) { Ad ad = googleAdsRow.AdGroupAd.Ad; ExpandedTextAdInfo expandedTextAdInfo = ad.ExpandedTextAd; Console.WriteLine("Expanded text ad with ID {0}, status '{1}', and headline " + "'{2} - {3}' was found in ad group with ID {4}.", ad.Id, googleAdsRow.AdGroupAd.Status, expandedTextAdInfo.HeadlinePart1, expandedTextAdInfo.HeadlinePart2, googleAdsRow.AdGroup.Id); } } 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="adGroupId">The ad group ID for which ad group bid modiifers will /// be retrieved.</param> public void Run(GoogleAdsClient client, long customerId, long?adGroupId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService(Services.V4.GoogleAdsService); string searchQuery = "SELECT ad_group.id, ad_group_bid_modifier.criterion_id, " + "ad_group_bid_modifier.bid_modifier, ad_group_bid_modifier.device.type, " + "campaign.id FROM ad_group_bid_modifier"; if (adGroupId != null) { searchQuery += $" WHERE ad_group.id = {adGroupId}"; } // Creates a request that will retrieve ad group bid modifiers using pages of the // specified page size. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), Query = searchQuery, PageSize = PAGE_SIZE }; try { // Issue the search request. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); // Iterates over all rows in all pages and prints the requested field values for // the ad group bid modifiers in each row. foreach (GoogleAdsRow googleAdsRow in searchPagedResponse) { AdGroupBidModifier adGroupBidModifier = googleAdsRow.AdGroupBidModifier; AdGroup adGroup = googleAdsRow.AdGroup; Campaign campaign = googleAdsRow.Campaign; Console.WriteLine("Ad group bid modifier with criterion ID {0}, bid " + "modifier value {1:0.00}, device type {2} was found in an ad group " + "with ID {3} of campaign ID {4}.", adGroupBidModifier.CriterionId, adGroupBidModifier.BidModifier, adGroupBidModifier.Device.Type, adGroup.Id, campaign.Id); } } 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 customer ID for which the call is made.</param> public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsServiceClient. GoogleAdsServiceClient googleAdsService = client.GetService(Services.V3.GoogleAdsService); // Creates the search query. string searchQuery = "SELECT asset.name, asset.image_asset.file_size, " + "asset.image_asset.full_size.width_pixels, " + "asset.image_asset.full_size.height_pixels, " + "asset.image_asset.full_size.url FROM asset WHERE asset.type = 'IMAGE'"; // Creates the request. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), Query = searchQuery }; try { // Issues the search request and prints the results. int count = 0; foreach (GoogleAdsRow row in googleAdsService.Search(request)) { Asset asset = row.Asset; ImageAsset imageAsset = asset.ImageAsset; // Displays the results. Console.WriteLine($"Image with name '{asset.Name}', file size " + $"{imageAsset.FileSize} bytes, width {imageAsset.FullSize.WidthPixels}px," + $" height {imageAsset.FullSize.HeightPixels}px, and url " + $"'{imageAsset.FullSize.Url}' found."); count++; } if (count == 0) { // Displays a response if no images are found. if (count == 0) { Console.WriteLine("No image assets found."); } } } 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> public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V4.GoogleAdsService); string searchQuery = "SELECT change_status.resource_name, " + "change_status.last_change_date_time, change_status.resource_type, " + "change_status.campaign, change_status.ad_group, change_status.resource_status, " + "change_status.ad_group_ad, change_status.ad_group_criterion, " + "change_status.campaign_criterion FROM change_status " + "WHERE change_status.last_change_date_time DURING LAST_7_DAYS " + "ORDER BY change_status.last_change_date_time"; // Create a request that will retrieve all changes using pages of the specified // page size. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { PageSize = PAGE_SIZE, Query = searchQuery, CustomerId = customerId.ToString() }; try { // Issue the search request. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); // Iterate over all rows in all pages and prints the requested field values for the // campaign in each row. foreach (GoogleAdsRow googleAdsRow in searchPagedResponse) { Console.WriteLine("Last change: {0}, Resource type: {1}, " + "Resource name: {2}, Resource status: {3}, Specific resource name: {4}", googleAdsRow.ChangeStatus.LastChangeDateTime, googleAdsRow.ChangeStatus.ResourceType, googleAdsRow.ChangeStatus.ResourceName, googleAdsRow.ChangeStatus.ResourceStatus, SpecificResourceName(googleAdsRow.ChangeStatus.ResourceType, googleAdsRow)); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
/// <summary>Snippet for SearchAsync</summary> public async Task SearchRequestObjectAsync() { // Snippet: SearchAsync(SearchGoogleAdsRequest, CallSettings) // Create client GoogleAdsServiceClient googleAdsServiceClient = await GoogleAdsServiceClient.CreateAsync(); // Initialize request argument(s) SearchGoogleAdsRequest request = new SearchGoogleAdsRequest { CustomerId = "", Query = "", ValidateOnly = false, ReturnTotalResultsCount = false, SummaryRowSetting = SummaryRowSettingEnum.Types.SummaryRowSetting.Unspecified, }; // Make the request PagedAsyncEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> response = googleAdsServiceClient.SearchAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((GoogleAdsRow item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((SearchGoogleAdsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (GoogleAdsRow item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page <GoogleAdsRow> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (GoogleAdsRow item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet }
/// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsServiceClient. GoogleAdsServiceClient googleAdsService = client.GetService(Services.V6.GoogleAdsService); // Creates the search query. string searchQuery = "SELECT asset.name, asset.image_asset.file_size, " + "asset.image_asset.full_size.width_pixels, " + "asset.image_asset.full_size.height_pixels, " + "asset.image_asset.full_size.url FROM asset WHERE asset.type = 'IMAGE'"; // Creates the request. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), Query = searchQuery, ReturnTotalResultsCount = true }; try { // Issue the search request. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); long totalImageAssetCount = searchPagedResponse.AsRawResponses() .First().TotalResultsCount; foreach (GoogleAdsRow row in searchPagedResponse) { Asset asset = row.Asset; ImageAsset imageAsset = asset.ImageAsset; // Displays the results. Console.WriteLine($"Image with name '{asset.Name}', file size " + $"{imageAsset.FileSize} bytes, width {imageAsset.FullSize.WidthPixels}px," + $" height {imageAsset.FullSize.HeightPixels}px, and url " + $"'{imageAsset.FullSize.Url}' found."); } Console.WriteLine($"Total image assets found: {totalImageAssetCount}"); } 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> public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V1.GoogleAdsService); // Create a request that will retrieve all campaigns using pages of the specified // page size. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { PageSize = PAGE_SIZE, Query = @"SELECT campaign.id, campaign.name, campaign.network_settings.target_content_network FROM campaign ORDER BY campaign.id", CustomerId = customerId.ToString() }; try { // Issue the search request. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); foreach (SearchGoogleAdsResponse response in searchPagedResponse.AsRawResponses()) { Console.WriteLine(response.FieldMask.Paths); foreach (GoogleAdsRow googleAdsRow in response.Results) { Console.WriteLine("Campaign with ID {0} and name '{1}' was found.", googleAdsRow.Campaign.Id, googleAdsRow.Campaign.Name); } } // Iterate over all rows in all pages and prints the requested field values for the // campaign in each row. foreach (GoogleAdsRow googleAdsRow in searchPagedResponse) { 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}"); } }
/// <summary> /// Gets a list of google ads rows. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="query">The query to execute.</param> /// <returns>The list of google ads rows.</returns> internal static IEnumerable <GoogleAdsRow> GetGoogleAdsRows(GoogleAdsClient client, string query) { GoogleAdsServiceClient googleAdsService = client.GetService( Services.V6.GoogleAdsService); SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { Query = query, CustomerId = client.Config.ClientCustomerId.ToString() }; return(googleAdsService.Search(request)); }
// [END add_shopping_product_listing_group_tree] /// <summary> /// Removes all the ad group criteria that define the existing listing group tree for an /// ad group. Returns without an error if all listing group criterion are successfully /// removed. /// </summary> /// <param name="client">The Google Ads API client..</param> /// <param name="customerId">The client customer ID.</param> /// <param name="adGroupId">The ID of the ad group that the new listing group tree will /// be removed from.</param> /// <exception cref="GoogleAdsException">Thrown if an API request failed with one or more /// service errors.</exception> private void RemoveListingGroupTree(GoogleAdsClient client, long customerId, long adGroupId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V10.GoogleAdsService); // Get the AdGroupCriterionService. AdGroupCriterionServiceClient adGroupCriterionService = client.GetService(Services.V10.AdGroupCriterionService); String searchQuery = "SELECT ad_group_criterion.resource_name FROM " + "ad_group_criterion WHERE ad_group_criterion.type = LISTING_GROUP AND " + "ad_group_criterion.listing_group.parent_ad_group_criterion IS NULL " + $"AND ad_group.id = {adGroupId}"; // Creates a request that will retrieve all listing groups where the parent ad group // criterion is NULL (and hence the root node in the tree) for a given ad group ID. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), PageSize = PAGE_SIZE, Query = searchQuery }; // Issues the search request. GoogleAdsRow googleAdsRow = googleAdsService.Search(request).FirstOrDefault(); if (googleAdsRow == null) { return; } AdGroupCriterion adGroupCriterion = googleAdsRow.AdGroupCriterion; Console.WriteLine("Found ad group criterion with the resource name: '{0}'.", adGroupCriterion.ResourceName); AdGroupCriterionOperation operation = new AdGroupCriterionOperation() { Remove = adGroupCriterion.ResourceName }; MutateAdGroupCriteriaResponse response = adGroupCriterionService.MutateAdGroupCriteria( customerId.ToString(), new AdGroupCriterionOperation[] { operation }); Console.WriteLine($"Removed {response.Results.Count}."); }
// [END set_custom_client_timeouts] /// <summary> /// Makes an unary 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_1] private void MakeUnaryCall(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"; SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), Query = query }; // Issue a search request. var googleAdsRows = googleAdsService.Search(request, callSettings); foreach (GoogleAdsRow googleAdsRow in googleAdsRows) { // Iterates over all rows in all messages and collects the campaign IDs. writer.WriteLine(googleAdsRow.Campaign.Id); } Console.WriteLine("The search paged call completed before the timeout."); } catch (GoogleAdsException ex) { if (ex.StatusCode == StatusCode.DeadlineExceeded) { Console.WriteLine("The search paged call did not complete before the timeout."); } else { throw; } } finally { Console.WriteLine($"All campaign IDs retrieved: {writer}."); } }
// [START navigate_search_result_pages_caching_tokens] /// <summary> /// Fetches and prints the results of a page of a search using a cache of page tokens. /// </summary> /// <param name="googleAdsService">The Google Ads API Service client.</param> /// <param name="request">The request.</param> /// <param name="pageNumber">The number of the page to fetch and print results for.</param> /// <param name="pageTokens">The cache of page tokens to use and update.</param> /// <returns></returns> private static void FetchAndPrintPageResults(GoogleAdsServiceClient googleAdsService, SearchGoogleAdsRequest request, int pageNumber, Dictionary <int, string> pageTokens) { int currentPageNumber = pageNumber; // There is no need to fetch the pages we already know the page tokens for. if (pageTokens.ContainsKey(pageNumber - 1)) { Console.WriteLine("The token of the requested page was cached, we will use it " + "to get the results."); currentPageNumber = pageNumber; } else { Console.WriteLine("The token of the requested page was never cached, we will " + $"use the closest page we know the token for (page #{pageNumber}) and " + $"sequentially get pages from there."); currentPageNumber = pageNumber; while (!pageTokens.ContainsKey(currentPageNumber)) { currentPageNumber--; } } SearchGoogleAdsResponse response = null; // Fetches next pages in sequence and caches their tokens until the requested page // results are returned. while (currentPageNumber <= pageNumber) { // Fetches the next page. Console.WriteLine($"Fetching page #{currentPageNumber}..."); request.PageToken = pageTokens[currentPageNumber - 1]; response = googleAdsService.Search(request) .AsRawResponses().First(); CacheNextPageToken(pageTokens, response, currentPageNumber); currentPageNumber++; } // Prints the results of the requested page. Console.WriteLine($"Printing results found for the page #{pageNumber}"); foreach (GoogleAdsRow row in response.Results) { Campaign c = row.Campaign; Console.WriteLine($" - Campaign with ID {c.Id} and name '{c.Name}'"); } }
/// <summary> /// Retrieves details about a feed. /// </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="feedResourceName">The feed resource name.</param> /// <returns></returns> /// <exception cref="NotImplementedException"></exception> private Dictionary <DsaPageFeedCriterionField, FeedAttribute> GetFeed( GoogleAdsClient client, long customerId, string feedResourceName) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V3.GoogleAdsService); // Construct the query. String query = $"SELECT feed.attributes FROM feed WHERE feed.resource_name" + $" = '{feedResourceName}'"; // Construct the request. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), Query = query }; // Issue the search request. Feed feed = googleAdsService.Search(customerId.ToString(), query).First().Feed; Dictionary <DsaPageFeedCriterionField, FeedAttribute> retval = new Dictionary <DsaPageFeedCriterionField, FeedAttribute>(); foreach (FeedAttribute attribute in feed.Attributes) { DsaPageFeedCriterionField key; switch (attribute.Name) { case "Page URL": key = DsaPageFeedCriterionField.PageUrl; break; case "Label": key = DsaPageFeedCriterionField.Label; break; default: throw new Exception("Unable to map attribute name to DSA page feed" + " criterion."); } retval[key] = attribute; } return(retval); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsServiceClient. GoogleAdsServiceClient googleAdsService = client.GetService(Services.V6.GoogleAdsService); // Creates a request that will retrieve all video and image files. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), Query = "SELECT media_file.id, media_file.name, media_file.type " + "FROM media_file where media_file.type in ('IMAGE', 'VIDEO') ORDER BY " + "media_file.id" }; try { // Issues the search request and prints the results. int count = 0; foreach (GoogleAdsRow row in googleAdsService.Search(request)) { MediaFile mediaFile = row.MediaFile; Console.WriteLine($"Media file with ID {mediaFile.Id}, name " + $"'{mediaFile.Name}', and type '{mediaFile.Type}' was found."); count++; } if (count == 0) { // Displays a response if no media files are found. if (count == 0) { Console.WriteLine("No media files found."); } } } 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> public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V10.GoogleAdsService); // Construct a query to retrieve the customer. // Add a limit of 1 row to clarify that selecting from the customer resource // will always return only one row, which will be for the customer // ID specified in the request. string query = "SELECT customer.id, customer.descriptive_name, " + "customer.currency_code, customer.time_zone, customer.tracking_url_template, " + "customer.auto_tagging_enabled FROM customer LIMIT 1"; // Executes the query and gets the Customer object from the single row of the response. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), Query = query }; try { // Issue the search request. Customer customer = googleAdsService.Search(request).First().Customer; // Print account information. Console.WriteLine("Customer with ID {0}, descriptive name '{1}', currency " + "code '{2}', timezone '{3}', tracking URL template '{4}' and auto tagging " + "enabled '{5}' was retrieved.", customer.Id, customer.DescriptiveName, customer.CurrencyCode, customer.TimeZone, customer.TrackingUrlTemplate, customer.AutoTaggingEnabled); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
/// <summary> /// Retrieves a feed item and its attribute values given a resource name. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the flights feed is /// added.</param> /// <param name="feedItemResourceName">Feed item resource name.</param> /// <returns>FeedItem with the given resource name.</returns> private FeedItem GetFeedItem(GoogleAdsClient client, long customerId, string feedItemResourceName) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V5.GoogleAdsService); // Constructs the query. string query = "SELECT feed_item.attribute_values FROM feed_item WHERE " + $"feed_item.resource_name = '{feedItemResourceName}'"; // Constructs the request. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), Query = query }; return(googleAdsService.Search(request).First().FeedItem); }
/// <summary> /// Handles the Click event of the btnGetCampaigns control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnGetCampaigns_Click(object sender, EventArgs e) { string customerId = txtCustomerId.Text; // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V1.GoogleAdsService); // Create a request that will retrieve all campaigns using pages of the specified // page size. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { PageSize = 500, Query = "SELECT campaign.id, campaign.name, campaign.status FROM campaign " + "ORDER BY campaign.id", CustomerId = customerId.ToString() }; // Issue the search request. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); // Iterate over all rows in all pages and prints the requested field values for the // campaign in each row. foreach (GoogleAdsRow googleAdsRow in searchPagedResponse) { TableRow row = new TableRow(); row.Cells.Add(new TableCell() { Text = googleAdsRow.Campaign.Id.ToString() }); row.Cells.Add(new TableCell() { Text = googleAdsRow.Campaign.Name }); row.Cells.Add(new TableCell() { Text = googleAdsRow.Campaign.Status.ToString() }); CampaignTable.Rows.Add(row); } }
/// <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="labelId">ID of the label for which campaigns are retrieved.</param> // [START GetCampaignsByLabel] public void Run(GoogleAdsClient client, long customerId, long labelId) { // Get the GoogleAdsServiceClient. GoogleAdsServiceClient googleAdsService = client.GetService(Services.V6.GoogleAdsService); // Creates a request that will retrieve all campaign labels with the specified // labelId using pages of the specified page size. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), Query = "SELECT campaign.id, campaign.name, label.id, label.name " + $"FROM campaign_label WHERE label.id = {labelId} ORDER BY campaign.id", }; try { int count = 0; // Issues the search request and prints the result. foreach (GoogleAdsRow googleAdsRow in googleAdsService.Search(request)) { count++; Console.WriteLine($"Campaign found with name '{googleAdsRow.Campaign.Name}'" + $", ID {googleAdsRow.Campaign.Id}, and label: " + $"'${googleAdsRow.Label.Name}'."); } if (count == 0) { Console.WriteLine("No campaigns were found."); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
GetAllExistingListingGroupFilterAssetsInAssetGroup( GoogleAdsClient client, long customerId, string assetGroupResourceName) { List <AssetGroupListingGroupFilter> resources = new List <AssetGroupListingGroupFilter>(); // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V10.GoogleAdsService); SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), PageSize = 10000, Query = $@" SELECT asset_group_listing_group_filter.resource_name, asset_group_listing_group_filter.parent_listing_group_filter FROM asset_group_listing_group_filter WHERE asset_group_listing_group_filter.asset_group = '{assetGroupResourceName}' " }; // The below enumerable will automatically iterate through the pages of the search // request. The limit to the number of listing group filters permitted in a Performance // Max campaign can be found here: // https://developers.google.com/google-ads/api/docs/best-practices/system-limits PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); foreach (GoogleAdsRow row in searchPagedResponse) { resources.Add(row.AssetGroupListingGroupFilter); } return(resources); }
/// <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.V2.GoogleAdsService); // Define a GAQL query to retrieve all billing setup information. string searchQuery = @" SELECT billing_setup.id, billing_setup.status, billing_setup.payments_account, billing_setup.payments_account_info.payments_account_id, billing_setup.payments_account_info.payments_account_name, billing_setup.payments_account_info.payments_profile_id, billing_setup.payments_account_info.payments_profile_name, billing_setup.payments_account_info.secondary_payments_profile_id FROM billing_setup"; // Creates a request that will retrieve all billing setups using pages of the specified // page size. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { PageSize = PAGE_SIZE, Query = searchQuery, CustomerId = customerId.ToString() }; try { PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); foreach (SearchGoogleAdsResponse response in searchPagedResponse.AsRawResponses()) { foreach (GoogleAdsRow googleAdsRow in response.Results) { BillingSetup billingSetup = googleAdsRow.BillingSetup; Console.WriteLine("Billing setup with ID '{0}', status '{1}', " + "payments account '{2}', payments account Id '{3}', " + "payments account name '{4}', payments profile id '{5}', " + "payments profile name '{6}', secondary payments profile id '{7}'.", billingSetup.Id, billingSetup.Status, billingSetup.PaymentsAccount, billingSetup.PaymentsAccountInfo.PaymentsAccountId, billingSetup.PaymentsAccountInfo.PaymentsAccountName, billingSetup.PaymentsAccountInfo.PaymentsProfileId, billingSetup.PaymentsAccountInfo.PaymentsProfileName, billingSetup.PaymentsAccountInfo.SecondaryPaymentsProfileId); } } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); } }
/// <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.V3.GoogleAdsService); // Construct a GAQL query which will retrieve AccountBudgetProposals. String searchQuery = @"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.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"; // Creates a request that will retrieve all account budgets using pages of the // specified page size. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { PageSize = PAGE_SIZE, Query = searchQuery, CustomerId = customerId.ToString() }; try { // Issues the search request. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); // Iterates over all rows in all pages and prints the requested field values for // the account budget in each row. foreach (GoogleAdsRow googleAdsRow in searchPagedResponse) { 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}'), approved " + "start time '{7}' (proposed '{8}'), approved end time '{9}' " + "(proposed '{10}')", 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.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; } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> /// <param name="campaignId">Id of the campaign for which disapproved ads /// are retrieved.</param> public void Run(GoogleAdsClient client, long customerId, long campaignId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V5.GoogleAdsService); string searchQuery = $@" SELECT ad_group_ad.ad.id, ad_group_ad.ad.type, ad_group_ad.policy_summary.approval_status, ad_group_ad.policy_summary.policy_topic_entries FROM ad_group_ad WHERE campaign.id = {campaignId} AND ad_group_ad.policy_summary.approval_status = DISAPPROVED"; // Create a request that will retrieve all Disapproved Ads SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { PageSize = PAGE_SIZE, Query = searchQuery, CustomerId = customerId.ToString(), ReturnTotalResultsCount = true }; try { // Issue the search request. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); long disapprovedAdsCount = searchPagedResponse.AsRawResponses() .First().TotalResultsCount; // Iterate over all rows in all rows returned and count disapproved Ads foreach (GoogleAdsRow googleAdsRow in searchPagedResponse) { AdGroupAdPolicySummary policySummary = googleAdsRow.AdGroupAd.PolicySummary; AdGroupAd adGroupAd = googleAdsRow.AdGroupAd; Ad ad = adGroupAd.Ad; Console.WriteLine( "Ad with ID {0} and type '{1}' was disapproved with the " + "following policy topic entries: ", ad.Id, ad.Type); // Display the policy topic entries related to the ad disapproval. foreach (PolicyTopicEntry policyTopicEntry in policySummary.PolicyTopicEntries) { Console.WriteLine(" topic: {0}, type: '{1}'", policyTopicEntry.Topic, policyTopicEntry.Type); // Display the attributes and values that triggered the policy topic. if (policyTopicEntry.Evidences != null) { foreach (PolicyTopicEvidence evidence in policyTopicEntry.Evidences) { if (evidence.TextList != null) { for (int i = 0; i < evidence.TextList.Texts.Count; i++) { Console.WriteLine(" evidence text[{0}]: {1}", i, evidence.TextList.Texts[i]); } } } } } } Console.WriteLine("Number of disapproved ads found: {0}", disapprovedAdsCount); } 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> public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsServiceClient . GoogleAdsServiceClient googleAdsService = client.GetService(Services.V10.GoogleAdsService); // Creates the query. string query = "SELECT product_bidding_category_constant.localized_name, " + "product_bidding_category_constant.product_bidding_category_constant_parent " + "FROM product_bidding_category_constant WHERE " + "product_bidding_category_constant.country_code IN ('US') ORDER BY " + "product_bidding_category_constant.localized_name ASC"; // Creates the request. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), Query = query }; // Creates a list of top level category nodes. List <CategoryNode> rootCategories = new List <CategoryNode>(); // Creates a map of category ID to category node for all categories found in the // results. // This Map is a convenience lookup to enable fast retrieval of existing nodes. Dictionary <string, CategoryNode> biddingCategories = new Dictionary <string, CategoryNode>(); try { // Performs the search request. foreach (GoogleAdsRow googleAdsRow in googleAdsService.Search(request)) { ProductBiddingCategoryConstant productBiddingCategory = googleAdsRow.ProductBiddingCategoryConstant; string localizedName = productBiddingCategory.LocalizedName; string resourceName = productBiddingCategory.ResourceName; CategoryNode node = null; if (biddingCategories.ContainsKey(resourceName)) { node = biddingCategories[resourceName]; } else { node = new CategoryNode(resourceName, localizedName); biddingCategories[resourceName] = node; } if (string.IsNullOrEmpty(node.LocalizedName)) { // Ensures that the name attribute for the node is set. Name will be null for //nodes added to biddingCategories as a result of being a parentNode below. node.LocalizedName = localizedName; } if (!string.IsNullOrEmpty( productBiddingCategory.ProductBiddingCategoryConstantParent)) { string parentResourceName = productBiddingCategory.ProductBiddingCategoryConstantParent; CategoryNode parentNode = null; if (biddingCategories.ContainsKey(parentResourceName)) { parentNode = biddingCategories[parentResourceName]; } else { parentNode = new CategoryNode(parentResourceName); biddingCategories[parentResourceName] = parentNode; } parentNode.Children.Add(node); } else { rootCategories.Add(node); } } DisplayCategories(rootCategories, ""); } 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> public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsServiceClient. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V5.GoogleAdsService); // Define a GAQL query to retrieve all billing setup information. string searchQuery = @" SELECT billing_setup.id, billing_setup.status, billing_setup.payments_account, billing_setup.payments_account_info.payments_account_id, billing_setup.payments_account_info.payments_account_name, billing_setup.payments_account_info.payments_profile_id, billing_setup.payments_account_info.payments_profile_name, billing_setup.payments_account_info.secondary_payments_profile_id FROM billing_setup"; // Creates a request that will retrieve all billing setups using pages of the specified // page size. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { PageSize = PAGE_SIZE, Query = searchQuery, CustomerId = customerId.ToString() }; try { PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); foreach (SearchGoogleAdsResponse response in searchPagedResponse.AsRawResponses()) { foreach (GoogleAdsRow googleAdsRow in response.Results) { BillingSetup billingSetup = googleAdsRow.BillingSetup; Console.WriteLine($"Billing setup with ID '{billingSetup.Id}'has status " + $"status '{billingSetup.Status}'."); // A missing billing setup will have no payments account information. if (billingSetup.PaymentsAccount != null) { Console.WriteLine( $"\tPayments account: {billingSetup.PaymentsAccount}\n" + "\tPayments account Id: " + $"{billingSetup.PaymentsAccountInfo.PaymentsAccountId}\n" + "\tPayments account name: " + $"{billingSetup.PaymentsAccountInfo.PaymentsAccountName}\n" + "\tPayments profile id: " + $"{billingSetup.PaymentsAccountInfo.PaymentsProfileId}\n" + "\tPayments profile name: " + $"{billingSetup.PaymentsAccountInfo.PaymentsProfileName}\n" + "\tSecondary payments profile id: " + $"{billingSetup.PaymentsAccountInfo.SecondaryPaymentsProfileId}"); } else { Console.WriteLine("Payments account details missing or incomplete."); } } } } 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 customer ID for which the call is made.</param> public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsServiceClient. GoogleAdsServiceClient googleAdsService = client.GetService(Services.V10.GoogleAdsService); // The cache of page tokens. The first page's token is always an empty string. Dictionary <int, string> pageTokens = new Dictionary <int, string>(); CacheNextPageToken(pageTokens, null, 0); Console.WriteLine("---0. Fetch page #1 to get metadata"); // Creates a query that retrieves the campaigns. string query = $"SELECT campaign.id, campaign.name FROM campaign ORDER BY " + $"campaign.name LIMIT {RESULTS_LIMIT}"; // Issues a paginated search request. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { Query = query, CustomerId = customerId.ToString(), // Sets the number of results to return per page. PageSize = PAGE_SIZE, // Requests to return the total results count. This is necessary to determine // how many pages of results there are. ReturnTotalResultsCount = true }; try { SearchGoogleAdsResponse response = googleAdsService.Search(request) .AsRawResponses().First(); CacheNextPageToken(pageTokens, response, 1); // Determines the total number of results and prints it. // The total results count does not take into consideration the LIMIT clause of // the query so we need to find the minimal value between the limit and the total // results count. long totalNumberOfResults = Math.Min(RESULTS_LIMIT, response.TotalResultsCount); Console.WriteLine($"Total number of campaigns found: {totalNumberOfResults}."); // Determines the total number of pages and prints it. int totalNumberOfPages = (int)Math.Ceiling((double)totalNumberOfResults / PAGE_SIZE); Console.WriteLine($"Total number of pages: {totalNumberOfPages}."); if (totalNumberOfResults == 0) { Console.WriteLine("Could not find any campaigns."); return; } // Demonstrates how the logic works when iterating pages forward. We select a // page that is in the middle of the result set so that only a subset of the page // tokens will be cached. int middlePageNumber = (int)Math.Ceiling((double)totalNumberOfPages / 2); Console.WriteLine($"--- 1. Print results of the page #{middlePageNumber}"); FetchAndPrintPageResults(googleAdsService, request, middlePageNumber, pageTokens); // Demonstrates how the logic works when iterating pages backward with some page // tokens that are not already cached. Console.WriteLine("--- 2. Print results from the last page to the first"); for (int i = totalNumberOfPages; i > 0; i--) { Console.WriteLine($"--- Printing results for page #{i}"); FetchAndPrintPageResults(googleAdsService, request, i, pageTokens); } } 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="adGroupId">Optional: ID of the ad group to restrict search to.</param> public void Run(GoogleAdsClient client, long customerId, long?adGroupId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V5.GoogleAdsService); string searchQuery = $@"SELECT ad_group.id, ad_group_ad.ad.id, ad_group_ad.ad.responsive_search_ad.headlines, ad_group_ad.ad.responsive_search_ad.descriptions, ad_group_ad.status FROM ad_group_ad WHERE ad_group_ad.ad.type = RESPONSIVE_SEARCH_AD AND ad_group_ad.status != 'REMOVED'"; if (adGroupId != null) { searchQuery += $" AND ad_group.id = {adGroupId}"; } // Create a request that will retrieve all ads using pages of the specified page size. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), PageSize = PAGE_SIZE, Query = searchQuery }; try { // Issue the search request. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); // Iterates over all rows in all pages and prints the requested field values for // the ad in each row. foreach (GoogleAdsRow googleAdsRow in searchPagedResponse) { Ad ad = googleAdsRow.AdGroupAd.Ad; Console.WriteLine($"Responsive search ad with resource name '{ad.ResourceName}'," + $"status '{googleAdsRow.AdGroupAd.Status}' was found."); // Prints the ad text asset detail. ResponsiveSearchAdInfo responsiveSearchAdInfo = ad.ResponsiveSearchAd; Console.WriteLine("Headlines:{0},\nDescriptions:{1}", FormatAdTextAssetsAsString(responsiveSearchAdInfo.Headlines), FormatAdTextAssetsAsString(responsiveSearchAdInfo.Descriptions)); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }