示例#1
0
        /// <summary>
        /// Return the name of the most specific resource that changed.
        /// </summary>
        /// <param name="resourceType">Type of the resource.</param>
        /// <param name="row">Each returned row contains all possible changed fields</param>
        /// <returns>The resource name of the changed field based on the resource type.
        /// The changed field's parent is also populated, but is not used.</returns>
        string SpecificResourceName(ChangeStatusResourceType resourceType, GoogleAdsRow row)
        {
            string resourceName = "";

            switch (resourceType)
            {
            case ChangeStatusResourceType.AdGroup:
                resourceName = row.ChangeStatus.AdGroup;
                break;

            case ChangeStatusResourceType.AdGroupAd:
                resourceName = row.ChangeStatus.AdGroupAd;
                break;

            case ChangeStatusResourceType.AdGroupCriterion:
                resourceName = row.ChangeStatus.AdGroupCriterion;
                break;

            case ChangeStatusResourceType.Campaign:
                resourceName = row.ChangeStatus.Campaign;
                break;

            case ChangeStatusResourceType.CampaignCriterion:
                resourceName = row.ChangeStatus.CampaignCriterion;
                break;

            case ChangeStatusResourceType.Unknown:
            case ChangeStatusResourceType.Unspecified:
            default:
                resourceName = "";
                break;
            }
            return(resourceName);
        }
        /// <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);
        }
示例#3
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);
            }
        }
示例#4
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);
        }
示例#5
0
 public GoogleAdsCampaign(GoogleAdsRow result)
 {
     ID        = result.Campaign.Id;
     Name      = result.Campaign.Name;
     StartDate = BudgetMethods.ConvertStringToDateTime(result.Campaign.StartDate);
     EndDate   = BudgetMethods.ConvertStringToDateTime(result.Campaign.EndDate);
 }
示例#6
0
 public GoogleAdsMetrics(GoogleAdsRow result)
 {
     Impressions      = result.Metrics.Impressions;
     Clicks           = result.Metrics.Clicks;
     ConversionsValue = result.Metrics.ConversionsValue;
     Conversions      = result.Metrics.Conversions;
     TotalCost        = BudgetMethods.ConvertMicroToDouble(result.Metrics.CostMicros);
 }
        // [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}.");
        }
示例#8
0
        public GoogleAdsBudgetDTO(GoogleAdsRow resultRoot)
        {
            ApprovedSpendingLimit = BudgetMethods.ConvertMicroToDecimal(resultRoot.AccountBudget.ApprovedSpendingLimitMicros);

            ProposedSpendingLimit = BudgetMethods.ConvertMicroToDecimal(resultRoot.AccountBudget.ProposedSpendingLimitMicros);

            ApprovedStartDateTime = BudgetMethods.ConvertStringToDateTime(resultRoot.AccountBudget.ApprovedStartDateTime);

            ProposedStartDateTime = BudgetMethods.ConvertStringToDateTime(resultRoot.AccountBudget.ProposedStartDateTime);

            ApprovedEndDateTime = BudgetMethods.ConvertStringToDateTime(resultRoot.AccountBudget.ApprovedEndDateTime);

            ProposedEndDateTime = BudgetMethods.ConvertStringToDateTime(resultRoot.AccountBudget.ProposedEndDateTime);

            AmountServed = BudgetMethods.ConvertMicroToDecimal(resultRoot.AccountBudget.AmountServedMicros);
        }
        /// <summary>
        /// Returns the DSA settings for a campaign. Throws an error if the campaign does not
        /// exist or is not a DSA campaign.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">ID of the campaign for which DSA settings are fetched.</param>
        /// <returns>The DSA settings.</returns>
        private DynamicSearchAdsSetting GetDsaSetting(GoogleAdsClient client, long customerId,
                                                      long campaignId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V3.GoogleAdsService);

            // Creates the query.
            // You must request all DSA fields in order to update the DSA settings in the
            // following step.
            string query =
                "SELECT "
                + "campaign.id, "
                + "campaign.name, "
                + "campaign.dynamic_search_ads_setting.domain_name, "
                + "campaign.dynamic_search_ads_setting.language_code, "
                + "campaign.dynamic_search_ads_setting.use_supplied_urls_only "
                + "FROM "
                + "campaign "
                + "WHERE "
                + "campaign.id = "
                + campaignId;

            GoogleAdsRow result = googleAdsService.Search(
                customerId.ToString(), query).FirstOrDefault();

            if (result == null)
            {
                throw new Exception("No campaign found with ID: " + campaignId);
            }

            // Gets the DSA settings.
            DynamicSearchAdsSetting dynamicSearchAdsSetting =
                result.Campaign.DynamicSearchAdsSetting;

            // Throws an exception if the campaign is not a DSA campaign.
            if (dynamicSearchAdsSetting == null || string.IsNullOrEmpty(
                    dynamicSearchAdsSetting.DomainName))
            {
                throw new Exception($"Campaign with ID {campaignId} is not a DSA campaign.");
            }

            return(dynamicSearchAdsSetting);
        }
示例#10
0
        /// <summary>
        /// Gets the Google My Business feed mapping.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="gmbFeedResourceName">The GMB feed resource name.</param>
        /// <returns>The newly created feed mapping.</returns>
        private static FeedMapping GetGMBFeedMapping(GoogleAdsClient client, long customerId,
                                                     string gmbFeedResourceName)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V3.GoogleAdsService);

            // Create the query.
            string query = $"SELECT feed_mapping.resource_name, feed_mapping.status FROM " +
                           $"feed_mapping WHERE feed_mapping.feed = '{gmbFeedResourceName}' and " +
                           $"feed_mapping.status = ENABLED and feed_mapping.placeholder_type = LOCATION" +
                           $" LIMIT 1";

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

            // Display the results.
            GoogleAdsRow googleAdsRow = result.FirstOrDefault();

            return((googleAdsRow == null) ? null : googleAdsRow.FeedMapping);
        }
示例#11
0
        // [END add_customer_match_user_list]

        /// <summary>
        /// Retrieves, checks, and prints the status of the offline user data job.
        /// </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="offlineUserDataJobResourceName">Resource name of the of the offline user
        /// data job.</param>
        /// <param name="userListResourceName">Resource name of the Customer Match user list.</param>
        private static void CheckJobStatusAndPrintResults(GoogleAdsClient client, long customerId,
                                                          string offlineUserDataJobResourceName, string userListResourceName)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient service = client.GetService(Services.V10.GoogleAdsService);

            string query = "SELECT offline_user_data_job.resource_name, " +
                           "offline_user_data_job.id, offline_user_data_job.status, " +
                           "offline_user_data_job.type, offline_user_data_job.failure_reason " +
                           "FROM offline_user_data_job WHERE " +
                           $"offline_user_data_job.resource_name = '{offlineUserDataJobResourceName}'";

            // Issues the query and gets the GoogleAdsRow containing the job from the response.
            GoogleAdsRow googleAdsRow = service.Search(customerId.ToString(), query).First();

            OfflineUserDataJob offlineUserDataJob = googleAdsRow.OfflineUserDataJob;

            Console.WriteLine($"Offline user data job ID {offlineUserDataJob.Id} with type " +
                              $"'{offlineUserDataJob.Type}' has status: {offlineUserDataJob.Status}");

            switch (offlineUserDataJob.Status)
            {
            case OfflineUserDataJobStatus.Success:
                // Prints information about the user list.
                PrintCustomerMatchUserListInfo(client, customerId, userListResourceName);
                break;

            case OfflineUserDataJobStatus.Failed:
                Console.WriteLine($"  Failure reason: {offlineUserDataJob.FailureReason}");
                break;

            case OfflineUserDataJobStatus.Pending:
            case OfflineUserDataJobStatus.Running:
                Console.WriteLine("To check the status of the job periodically, use the " +
                                  $"following GAQL query with GoogleAdsService.search:\n\n{query}");
                break;
            }
        }
示例#12
0
 public GoogleAdsCampaignDTO(GoogleAdsRow result)
 {
     Campaign = new GoogleAdsCampaign(result);
     Metrics  = new GoogleAdsMetrics(result);
 }