Пример #1
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");
                }
            }
                                                );
        }
        // [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);
        }
Пример #3
0
        /// <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);
        }
Пример #4
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));
            }
        }
Пример #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);
        }
Пример #6
0
        /// <summary>
        /// Gets the customer user access given an email address.
        /// </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="emailAddress">Email address of the user whose access role should be
        /// retrieved.</param>
        /// <returns>The user ID if a customer is found, or null if no matching customers were
        /// found.</returns>
        private long?GetUserAccess(GoogleAdsClient client, long customerId, string emailAddress)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V6.GoogleAdsService);

            // Create the search query. Use the LIKE query for filtering to ignore the text case
            // for email address when searching for a match.
            string searchQuery = "Select customer_user_access.user_id, " +
                                 "customer_user_access.email_address, customer_user_access.access_role," +
                                 "customer_user_access.access_creation_date_time from customer_user_access " +
                                 $"where customer_user_access.email_address LIKE '{emailAddress}'";

            // Retrieves the user accesses.
            PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
                googleAdsService.Search(customerId.ToString(), searchQuery);

            GoogleAdsRow result = searchPagedResponse.FirstOrDefault();

            // Displays the results.
            if (result != null)
            {
                CustomerUserAccess access = result.CustomerUserAccess;
                Console.WriteLine("Customer user access with User ID = {0}, Email Address = " +
                                  "{1}, Access Role = {2} and Creation Time = {3} was found in " +
                                  "Customer ID: {4}.", access.UserId, access.EmailAddress, access.AccessRole,
                                  access.AccessCreationDateTime, customerId);
                return(access.UserId);
            }
            else
            {
                Console.WriteLine("No customer user access with requested email was found.");
                return(null);
            }
        }
        /// <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.");
                }
            });
        }
        /// <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);
        }
Пример #9
0
        private static CustomerFeed[] GetLocationExtensionCustomerFeeds(GoogleAdsClient client,
                                                                        long customerId)
        {
            List <CustomerFeed>    customerFeeds    = new List <CustomerFeed>();
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V5.GoogleAdsService);

            // Create the query. A location extension customer feed can be identified by filtering
            // for placeholder_types=LOCATION (location extension feeds) or
            // placeholder_types =AFFILIATE_LOCATION (affiliate location extension feeds)
            string query = $"SELECT customer_feed.resource_name, customer_feed.feed, " +
                           $"customer_feed.status, customer_feed.matching_function.function_string from " +
                           $"customer_feed " +
                           $"WHERE customer_feed.placeholder_types CONTAINS " +
                           $"ANY(LOCATION, AFFILIATE_LOCATION) and customer_feed.status=ENABLED";

            PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> result =
                googleAdsService.Search(customerId.ToString(), query);

            foreach (GoogleAdsRow row in result)
            {
                customerFeeds.Add(row.CustomerFeed);
            }
            return(customerFeeds.ToArray());
        }
        /// <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.");
                }
            });
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerIds">The Google Ads customer Id.</param>
        /// <param name="loginCustomerId">Optional login customer ID if your access to the CIDs
        ///     is via a manager account.</param>
        public void Run(GoogleAdsClient client, long[] customerIds, long?loginCustomerId)
        {
            // If a manager ID is supplied, update the login credentials.
            if (loginCustomerId.HasValue)
            {
                client.Config.LoginCustomerId = loginCustomerId.ToString();
            }

            // Get the GoogleAdsService. A single client can be shared by all threads.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V10.GoogleAdsService);

            try
            {
                // Begin downloading reports and block program termination until complete.
                Task task = RunDownloadParallelAsync(googleAdsService, customerIds);
                task.Wait();
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Пример #12
0
        /// <summary>
        /// Gets the location extension feeds.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <returns>The list of location extension feeds.</returns>
        private static Feed[] GetLocationExtensionFeeds(GoogleAdsClient client, long customerId)
        {
            List <Feed>            feeds            = new List <Feed>();
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V5.GoogleAdsService);

            // Create the query.
            string query = $"SELECT feed.resource_name, feed.status, " +
                           $"feed.places_location_feed_data.email_address, " +
                           $"feed.affiliate_location_feed_data.chain_ids " +
                           $" from feed where feed.status = ENABLED";

            PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> result =
                googleAdsService.Search(customerId.ToString(), query);

            foreach (GoogleAdsRow row in result)
            {
                // A location extension feed can be identified by checking whether the
                // PlacesLocationFeedData field is set (Location extensions feeds) or
                // AffiliateLocationFeedData field is set (Affiliate location extension feeds)
                Feed feed = row.Feed;
                if (feed.PlacesLocationFeedData != null || feed.AffiliateLocationFeedData != null)
                {
                    feeds.Add(feed);
                }
            }
            return(feeds.ToArray());
        }
Пример #13
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>
        /// 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}");
            }
        }
Пример #15
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
        }
Пример #16
0
        /// <summary>
        /// Fetches an experiment and display its details.
        /// </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="experimentResourceName">Resource name of the experiment.</param>
        /// <returns></returns>
        private static void DisplayExperimentDetails(GoogleAdsClient client, long customerId,
                                                     string experimentResourceName)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService =
                client.GetService(Services.V2.GoogleAdsService);

            // Once the draft is created, you can modify the draft campaign as if it were
            // a real campaign. For example, you may add criteria, adjust bids, or even
            // include additional ads. Adding a criterion is shown here.
            string query = $@"
                SELECT
                    campaign_experiment.experiment_campaign
                FROM
                    campaign_experiment
                WHERE
                    campaign_experiment.resource_name = '{experimentResourceName}'";

            // Get the expriment campaign resource name.
            string experimentCampaignResourceName = googleAdsService.Search(
                customerId.ToString(), query).First().CampaignExperiment.ExperimentCampaign;

            Console.WriteLine($"Experiment campaign with resource ID =" +
                              $" '{experimentCampaignResourceName}' finished creating.");
        }
Пример #17
0
        /// <summary>
        /// Fetches the draft campaign associated with a campaign draft.
        /// </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="draftResourceName">Resource name of the draft.</param>
        /// <returns></returns>
        private static string FetchDraftCampaign(GoogleAdsClient client, long customerId,
                                                 string draftResourceName)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService =
                client.GetService(Services.V4.GoogleAdsService);

            // Once the draft is created, you can modify the draft campaign as if it were
            // a real campaign. For example, you may add criteria, adjust bids, or even
            // include additional ads. Adding a criterion is shown here.
            string query = $@"
                SELECT
                    campaign_draft.draft_campaign
                FROM
                    campaign_draft
                WHERE
                    campaign_draft.resource_name = '{draftResourceName}'";


            // Get the draft campaign resource name.
            string draftCampaignResourceName = googleAdsService.Search(
                customerId.ToString(), query).First().CampaignDraft.DraftCampaign;

            return(draftCampaignResourceName);
        }
Пример #18
0
        /// <summary>
        /// Retrieves the manager link resource name of a customer client link given its resource
        /// name.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="managerCustomerId">The manager customer ID.</param>
        /// <param name="clientCustomerId">The client customer ID.</param>
        /// <param name="customerClientLinkResourceName">The customer client link resource
        /// name.</param>
        /// <returns>The manager link resource name.</returns>
        private string GetManagerLinkResourceName(GoogleAdsClient client, long managerCustomerId,
                                                  long clientCustomerId, string customerClientLinkResourceName)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService =
                client.GetService(Services.V1.GoogleAdsService);

            // Create a client with the manager customer ID as login customer ID.
            client.Config.LoginCustomerId = managerCustomerId.ToString();

            // Creates the query.
            string query = "SELECT customer_client_link.manager_link_id FROM " +
                           "customer_client_link WHERE customer_client_link.resource_name = " +
                           $"'{customerClientLinkResourceName}'";

            // Issue a search request by specifying the page size.
            GoogleAdsRow result = googleAdsService.Search(
                managerCustomerId.ToString(), query).First();

            // Gets the ID and resource name associated to the manager link found.
            long   managerLinkId           = result.CustomerManagerLink.ManagerLinkId.Value;
            string managerLinkResourceName = ResourceNames.CustomerManagerLink(
                clientCustomerId, managerCustomerId, managerLinkId);

            // Prints the result.
            Console.WriteLine($"Retrieved the manager link of the customer client link: its ID " +
                              $"is {managerLinkId} and its resource name is '{managerLinkResourceName}'.");
            // Returns the resource name of the manager link found.
            return(managerLinkResourceName);
        }
Пример #19
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.");
        }
Пример #20
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.V2.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.
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> result =
                    googleAdsService.Search(customerId.ToString(), query);

                // Display the results.
                foreach (GoogleAdsRow criterionRow in result)
                {
                    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}");
            }
        }
Пример #21
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="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;
            }
        }
Пример #22
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="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;
            }
        }
Пример #23
0
        public async static Task <dynamic> ImpressionsYesterday(List <string> companyNames)
        {
            var dailyImpressionsDTO = new DailyImpressionsDTO();

            dailyImpressionsDTO.DailyImpressionsSummary = new List <CompanyDailyImpressionsSummary>();

            foreach (string company in companyNames)
            {
                string customerID;

                try
                {
                    using (Entities db = new Entities())
                    {
                        customerID = AliasMethods.GetAlias(company, db, "GoogleAdsCustomerID");
                    }
                }
                catch
                {
                    return(new ArgumentException($"No ID found for the company { company }"));
                }

                try
                {
                    GoogleAdsClient client = new GoogleAdsClient();

                    // Get the GoogleAdsService.
                    GoogleAdsServiceClient googleAdsService = client.GetService(
                        Services.V4.GoogleAdsService);

                    string dailyImpressionsQuery = "SELECT "
                                                   + "campaign.id, "
                                                   + "campaign.name, "
                                                   + "metrics.impressions "
                                                   + "FROM campaign "
                                                   + "WHERE campaign.serving_status='SERVING' "
                                                   + "AND segments.date DURING YESTERDAY";

                    RepeatedField <GoogleAdsRow> dailyImpressionsResults = RequestMethods.SearchRequest(customerID, dailyImpressionsQuery, googleAdsService);

                    if (dailyImpressionsResults.Any(x => x.Metrics.Impressions > 0 && x.Metrics.Impressions < 100))
                    {
                        dailyImpressionsDTO.DailyImpressionsSummary.Add(new CompanyDailyImpressionsSummary(company, dailyImpressionsResults));
                    }
                }
                catch (GoogleAdsException e)
                {
                    Debug.WriteLine("Failure:");
                    Debug.WriteLine($"Message: {e.Message}");
                    Debug.WriteLine($"Failure: {e.Failure}");
                    Debug.WriteLine($"Request ID: {e.RequestId}");
                }
            }

            return(await SendEmailAlert(dailyImpressionsDTO));
        }
Пример #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>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V3.GoogleAdsService);

            // Creates a query that retrieves hotel-ads statistics for each campaign and ad group.
            // Returned statistics will be segmented by the check-in day of week and length of
            // stay.
            String query =
                $@"SELECT
                      campaign.id,
                      campaign.advertising_channel_type,
                      ad_group.id,
                      ad_group.status,
                      metrics.impressions,
                      metrics.hotel_average_lead_value_micros,
                      segments.hotel_check_in_day_of_week,
                      segments.hotel_length_of_stay
                  FROM hotel_performance_view
                  WHERE
                      segments.date DURING LAST_7_DAYS
                    AND campaign.advertising_channel_type = 'HOTEL'
                    AND ad_group.status = 'ENABLED'
                 ORDER BY metrics.impressions DESC
                 LIMIT 50";

            try
            {
                // Issue a search request.
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> result =
                    googleAdsService.Search(customerId.ToString(), query);

                // Display the results.
                foreach (GoogleAdsRow row in result)
                {
                    Console.WriteLine(
                        $"Ad group ID {row.AdGroup.Id} in campaign ID {row.Campaign.Id} " +
                        $"with hotel check-in on {row.Segments.HotelCheckInDayOfWeek} and " +
                        $"{row.Segments.HotelLengthOfStay} day(s) of stay had " +
                        $"{row.Metrics.Impressions} impression(s) and " +
                        $"{row.Metrics.HotelAverageLeadValueMicros:0.00} average lead value " +
                        "(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;
            }
        }
Пример #25
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);

            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;
            }
        }
Пример #26
0
        /// <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;
            }
        }
Пример #27
0
        /// <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>Snippet for Mutate</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void Mutate()
 {
     // Create client
     GoogleAdsServiceClient googleAdsServiceClient = GoogleAdsServiceClient.Create();
     // Initialize request argument(s)
     string customerId = "";
     IEnumerable <MutateOperation> mutateOperations = new MutateOperation[]
     {
         new MutateOperation(),
     };
     // Make the request
     MutateGoogleAdsResponse response = googleAdsServiceClient.Mutate(customerId, mutateOperations);
 }
Пример #29
0
        /// <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;
            }
        }
Пример #30
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.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}");
            }
        }