/// <summary> /// Creates a new shopping campaign for Smart Shopping ads in the specified client account. /// </summary> /// <param name="client">The Google Ads API client.</param> /// <param name="customerId">The client customer ID.</param> /// <param name="budgetResourceName">The resource name of the budget for the campaign. /// </param> /// <param name="merchantCenterAccountId">The Merchant Center account ID.</param> /// <returns>Resource name of the newly created campaign.</returns> /// <exception cref="GoogleAdsException">Thrown if an API request failed with one or more /// service errors.</exception> private string AddSmartShoppingCampaign(GoogleAdsClient client, long customerId, string budgetResourceName, long merchantCenterAccountId) { // Get the CampaignService. CampaignServiceClient campaignService = client.GetService(Services.V4.CampaignService); // Configures the shopping settings. ShoppingSetting shoppingSetting = new ShoppingSetting() { // Sets the sales country of products to include in the campaign. SalesCountry = "US", MerchantId = merchantCenterAccountId, }; // Create the standard shopping campaign. Campaign campaign = new Campaign() { Name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(), // Configures settings related to shopping campaigns including advertising channel // type, sub-type and shopping setting. AdvertisingChannelType = AdvertisingChannelType.Shopping, AdvertisingChannelSubType = AdvertisingChannelSubType.ShoppingSmartAds, ShoppingSetting = shoppingSetting, // Recommendation: Set the campaign to PAUSED when creating it to prevent // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve Status = CampaignStatus.Paused, // Bidding strategy must be set directly on the campaign. // Setting a portfolio bidding strategy by resourceName is not supported. // Maximize conversion value is the only strategy supported for Smart Shopping // campaigns. // An optional ROAS (Return on Advertising Spend) can be set for // MaximizeConversionValue. // The ROAS value must be specified as a ratio in the API. It is calculated by // dividingW "total value" by "total spend". // For more information on maximize conversion value, see the support article: // http://support.google.com/google-ads/answer/7684216) MaximizeConversionValue = new MaximizeConversionValue() { TargetRoas = 3.5 }, // Sets the budget. CampaignBudget = budgetResourceName }; // Creates a campaign operation. CampaignOperation operation = new CampaignOperation() { Create = campaign }; // Issues a mutate request to add the campaign. MutateCampaignsResponse response = campaignService.MutateCampaigns(customerId.ToString(), new CampaignOperation[] { operation }); MutateCampaignResult result = response.Results[0]; Console.WriteLine("Added a Smart Shopping campaign with resource name: '{0}'.", result.ResourceName); return(result.ResourceName); }
/// <summary> /// Creates a new standard shopping campaign in the specified client account. /// </summary> /// <param name="client">The Google Ads API client.</param> /// <param name="customerId">The client customer ID.</param> /// <param name="budgetResourceName">The resource name of the budget for the campaign. /// </param> /// <param name="merchantCenterAccountId">The Merchant Center account ID.</param> /// <returns>Resource name of the newly created campaign.</returns> /// <exception cref="GoogleAdsException">Thrown if an API request failed with one or more /// service errors.</exception> private string AddStandardShoppingCampaign(GoogleAdsClient client, long customerId, string budgetResourceName, long merchantCenterAccountId) { // Get the CampaignService. CampaignServiceClient campaignService = client.GetService(Services.V1.CampaignService); // Configures the shopping settings. ShoppingSetting shoppingSetting = new ShoppingSetting() { // Sets the sales country of products to include in the campaign. SalesCountry = "US", // Sets the priority of the campaign. Higher numbers take priority over lower // numbers. For Shopping Product Ad campaigns, allowed values are between 0 and 2, // inclusive. CampaignPriority = 0, MerchantId = merchantCenterAccountId, // Enables local inventory ads for this campaign. EnableLocal = true }; // Create the standard shopping campaign. Campaign campaign = new Campaign() { Name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(), // Configures settings related to shopping campaigns including advertising channel // type and shopping setting. AdvertisingChannelType = AdvertisingChannelType.Shopping, ShoppingSetting = shoppingSetting, // Recommendation: Set the campaign to PAUSED when creating it to prevent // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve Status = CampaignStatus.Paused, // Sets the bidding strategy to Manual CPC (with eCPC enabled) // Recommendation: Use one of the automated bidding strategies for Shopping // campaigns to help you optimize your advertising spend. More information can be // found here: https://support.google.com/google-ads/answer/6309029 ManualCpc = new ManualCpc() { EnhancedCpcEnabled = true }, // Sets the budget. CampaignBudget = budgetResourceName }; // Creates a campaign operation. CampaignOperation operation = new CampaignOperation() { Create = campaign }; // Issues a mutate request to add the campaign. MutateCampaignsResponse response = campaignService.MutateCampaigns(customerId.ToString(), new CampaignOperation[] { operation }); MutateCampaignResult result = response.Results[0]; Console.WriteLine("Added a standard shopping campaign with resource name: '{0}'.", result.ResourceName); return(result.ResourceName); }
/// <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">ID of the ad group to which targeting criteria are added. /// </param> public void Run(GoogleAdsClient client, long customerId, long adGroupId) { // Get the AdGroupCriterionService. AdGroupCriterionServiceClient adGroupCriterionService = client.GetService(Services.V6.AdGroupCriterionService); string adGroupResourceName = ResourceNames.AdGroup(customerId, adGroupId); // Creates a positive ad group criterion for gender. AdGroupCriterion genderAdGroupCriterion = new AdGroupCriterion() { AdGroup = adGroupResourceName, // Targets male. Gender = new GenderInfo() { Type = GenderType.Male } }; // Creates a negative ad group criterion for age range. AdGroupCriterion ageRangeNegativeAdGroupCriterion = new AdGroupCriterion() { AdGroup = adGroupResourceName, // Makes this ad group criterion negative. Negative = true, // Targets the age range of 18 to 24. AgeRange = new AgeRangeInfo() { Type = AgeRangeType.AgeRange1824 } }; // Creates ad group criterion operations for both ad group criteria. AdGroupCriterionOperation[] operations = new AdGroupCriterionOperation[] { new AdGroupCriterionOperation() { Create = genderAdGroupCriterion }, new AdGroupCriterionOperation() { Create = ageRangeNegativeAdGroupCriterion } }; try { // Issues a mutate request to add the ad group criteria and print out some // information. MutateAdGroupCriteriaResponse response = adGroupCriterionService.MutateAdGroupCriteria( customerId.ToString(), operations); Console.WriteLine($"Added {response.Results.Count} demographic ad group" + $" criteria:"); foreach (MutateAdGroupCriterionResult result in response.Results) { Console.WriteLine(result.ResourceName); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
/// <summary> /// Creates the Google My Business feed. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> /// <param name="gmbEmailAddress">The Google My Business login email address.</param> /// <param name="businessAccountId">The Google My Business account ID.</param> /// <param name="gmbAccessToken">The OAuth2 access token for The Google My Business /// account.</param> /// <returns>ID of the newly created Google My Business feed.</returns> // [START AddGoogleMyBusinessLocationExtensions] private static string CreateGMBFeed(GoogleAdsClient client, long customerId, string gmbEmailAddress, string businessAccountId, string gmbAccessToken) { // Optional: Delete all existing location extension feeds. This is an optional step, // and is required for this code example to run correctly more than once. // 1. Google Ads only allows one location extension feed per email address. // 2. A Google Ads account cannot have a location extension feed and an affiliate // location extension feed at the same time. DeleteLocationExtensionFeeds(client, customerId); // Get the FeedServiceClient. FeedServiceClient feedService = client.GetService(Services.V6.FeedService); // Creates a feed that will sync to the Google My Business account specified by // gmbEmailAddress. Do not add FeedAttributes to this object as Google Ads will add // them automatically because this will be a system generated feed. Feed gmbFeed = new Feed() { Name = "Google My Business feed #" + ExampleUtilities.GetRandomString(), PlacesLocationFeedData = new PlacesLocationFeedData() { EmailAddress = gmbEmailAddress, // If the EmailAddress is for a GMB manager instead of the GMB // account owner, then set BusinessAccountId to the Google+ Page ID of // a location for which the manager has access. This information is available // through the Google My Business API. See // https://developers.google.com/my-business/reference/rest/v4/accounts.locations#locationkey // for details. BusinessAccountId = string.IsNullOrEmpty(businessAccountId) ? null : businessAccountId, // Used to filter Google My Business listings by labels. If entries exist in // label_filters, only listings that have at least one of the labels set are // candidates to be synchronized into FeedItems. If no entries exist in // label_filters, then all listings are candidates for syncing. LabelFilters = { "Stores in New York" }, // Sets the authentication info to be able to connect Google Ads to the GMB // account. OauthInfo = new OAuthInfo() { HttpMethod = "GET", HttpRequestUrl = GOOGLE_ADS_SCOPE, HttpAuthorizationHeader = $"Bearer {gmbAccessToken}" }, }, // Since this feed's feed items will be managed by Google, // you must set its origin to GOOGLE. Origin = FeedOrigin.Google }; FeedOperation operation = new FeedOperation() { Create = gmbFeed }; // Adds the feed. MutateFeedsResponse response = feedService.MutateFeeds(customerId.ToString(), new[] { operation }); // Displays the results. string gmbFeedResourceName = response.Results[0].ResourceName; Console.WriteLine($"GMB feed created with resource name: {gmbFeedResourceName}."); return(gmbFeedResourceName); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> // [START GetBillingSetup] public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsServiceClient. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V6.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 (GoogleAdsRow googleAdsRow in searchPagedResponse) { BillingSetup billingSetup = googleAdsRow.BillingSetup; Console.WriteLine($"Billing setup with ID '{billingSetup.Id}'has status " + $"'{billingSetup.Status}'."); // A missing billing setup will have no payments account information. if (billingSetup.HasPaymentsAccount) { Console.WriteLine( $"\tPayments account: {billingSetup.PaymentsAccount}\n" + "\tPayments account Id: " + $"{billingSetup.PaymentsAccountInfo.PaymentsAccountId}\n" + "\tPayments profile id: " + $"{billingSetup.PaymentsAccountInfo.PaymentsProfileId}\n"); // A pending billing setup will not have values for certain fields. if (billingSetup.Status != BillingSetupStatus.Pending) { Console.WriteLine( "\tPayments account name: " + $"{billingSetup.PaymentsAccountInfo.PaymentsAccountName}\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> /// Adds a new item to the feed. /// </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="feedAttributes">The feed attributes.</param> /// <param name="feedResourceName">The resource name of the feed.</param> private void CreateFeedItem(GoogleAdsClient client, long customerId, Dictionary <FlightPlaceholderField, FeedAttribute> feedAttributes, string feedResourceName) { // Get the FeedItemServiceClient. FeedItemServiceClient feedItemService = client.GetService( Services.V3.FeedItemService); // Creates the flight description feed attribute value. FeedItemAttributeValue flightDescription = new FeedItemAttributeValue() { FeedAttributeId = feedAttributes[FlightPlaceholderField.FlightDescription].Id, StringValue = "Earth to Mars" }; // Creates the destination ID feed attribute value. FeedItemAttributeValue destinationId = new FeedItemAttributeValue() { FeedAttributeId = feedAttributes[FlightPlaceholderField.DestinationId].Id, StringValue = "Mars" }; // Creates the flight price feed attribute value. FeedItemAttributeValue flightPrice = new FeedItemAttributeValue() { FeedAttributeId = feedAttributes[FlightPlaceholderField.FlightPrice].Id, StringValue = "499.99 USD" }; // Creates the flight sale price feed attribute value. FeedItemAttributeValue flightSalePrice = new FeedItemAttributeValue() { FeedAttributeId = feedAttributes[FlightPlaceholderField.FlightSalePrice].Id, StringValue = "299.99 USD" }; // Creates the final URLs feed attribute value. FeedItemAttributeValue finalUrls = new FeedItemAttributeValue() { FeedAttributeId = feedAttributes[FlightPlaceholderField.FinalUrls].Id, StringValues = { "http://www.example.com/flights/" } }; // Creates the FeedItem, specifying the Feed ID and the attributes created above. FeedItem feedItem = new FeedItem() { Feed = feedResourceName, AttributeValues = { flightDescription, destinationId, flightPrice, flightSalePrice, finalUrls } }; // Creates an operation to add the FeedItem. FeedItemOperation operation = new FeedItemOperation() { Create = feedItem }; // Adds the feed item. MutateFeedItemsResponse response = feedItemService.MutateFeedItems(customerId.ToString(), new FeedItemOperation[] { operation }); foreach (MutateFeedItemResult result in response.Results) { Console.WriteLine($"Created feed item with resource name '{result.ResourceName}'."); } }
/// <summary> /// Creates a new asset for the call. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID.</param> /// <param name="phoneCountry">The phone number country.</param> /// <param name="phoneNumber">The phone number itself.</param> /// <param name="conversionActionId">The conversion action ID or null.</param> /// <returns>The resource name of the created call asset</returns> private string AddExtensionAsset( GoogleAdsClient client, long customerId, string phoneCountry, string phoneNumber, long?conversionActionId) { // Creates the call asset. CallAsset callAsset = new CallAsset() { // Sets the country code and phone number of the business to call. CountryCode = phoneCountry, PhoneNumber = phoneNumber, // Optional: Specifies all day and time intervals for which the asset may serve. AdScheduleTargets = { new AdScheduleInfo() { // Sets the day of this schedule as Monday. DayOfWeek = DayOfWeek.Monday, // Sets the start hour to 9am. StartHour = 9, // Sets the end hour to 5pm. EndHour = 17, // Sets the start and end minute of zero, for example: 9:00 and 5:00. StartMinute = MinuteOfHour.Zero, EndMinute = MinuteOfHour.Zero } } }; // Sets the conversion action ID to the one provided if any. if (conversionActionId.HasValue) { callAsset.CallConversionAction = ResourceNames.ConversionAction(customerId, conversionActionId.Value); callAsset.CallConversionReportingState = CallConversionReportingState.UseResourceLevelCallConversionAction; } // Creates an asset operation wrapping the call asset in an asset. AssetOperation assetOperation = new AssetOperation() { Create = new Asset() { CallAsset = callAsset } }; AssetServiceClient assetServiceClient = client.GetService(Services.V10.AssetService); // Issues a mutate request to add the asset and prints its information. MutateAssetsResponse response = assetServiceClient.MutateAssets( customerId.ToString(), new[] { assetOperation } ); string createdAssetResourceName = response.Results.First().ResourceName; Console.WriteLine( $"Created a call asset with resource name: '{createdAssetResourceName}'." ); return(createdAssetResourceName); }
/// <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="locationIds">The list of location IDs to restrict the search.</param> /// <param name="languageId">The language to restrict the search.</param> /// <param name="keywordTexts">The list of seed keywords.</param> /// <param name="pageUrl">The seed page URL.</param> public void Run(GoogleAdsClient client, long customerId, long[] locationIds, long languageId, string[] keywordTexts, string pageUrl) { KeywordPlanIdeaServiceClient keywordPlanIdeaService = client.GetService(Services.V5.KeywordPlanIdeaService); // Make sure that keywords and/or page URL were specified. The request must have // exactly one of urlSeed, keywordSeed, or keywordAndUrlSeed set. if (keywordTexts.Length == 0 && string.IsNullOrEmpty(pageUrl)) { throw new ArgumentException("At least one of keywords or page URL is required, " + "but neither was specified."); } // Specify the optional arguments of the request as a keywordSeed, UrlSeed, // or KeywordAndUrlSeed. GenerateKeywordIdeasRequest request = new GenerateKeywordIdeasRequest() { CustomerId = customerId.ToString(), }; if (keywordTexts.Length == 0) { // Only page URL was specified, so use a UrlSeed. request.UrlSeed = new UrlSeed() { Url = pageUrl }; } else if (string.IsNullOrEmpty(pageUrl)) { // Only keywords were specified, so use a KeywordSeed. request.KeywordSeed = new KeywordSeed(); request.KeywordSeed.Keywords.AddRange(keywordTexts); } else { // Both page URL and keywords were specified, so use a KeywordAndUrlSeed. request.KeywordAndUrlSeed = new KeywordAndUrlSeed(); request.KeywordAndUrlSeed.Url = pageUrl; request.KeywordAndUrlSeed.Keywords.AddRange(keywordTexts); } // Create a list of geo target constants based on the resource name of specified // location IDs. foreach (long locationId in locationIds) { request.GeoTargetConstants.Add(ResourceNames.GeoTargetConstant(locationId)); } request.Language = ResourceNames.LanguageConstant(languageId); // Set the network. To restrict to only Google Search, change the parameter below to // KeywordPlanNetwork.GoogleSearch. request.KeywordPlanNetwork = KeywordPlanNetwork.GoogleSearchAndPartners; try { // Generate keyword ideas based on the specified parameters. var response = keywordPlanIdeaService.GenerateKeywordIdeas(request); // Iterate over the results and print its detail. foreach (GenerateKeywordIdeaResult result in response) { KeywordPlanHistoricalMetrics metrics = result.KeywordIdeaMetrics; Console.WriteLine($"Keyword idea text '{result.Text}' has " + $"{metrics.AvgMonthlySearches} average monthly searches and competition " + $"is {metrics.Competition}."); } } 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.V4.GoogleAdsService); String searchQuery = $@"SELECT ad_group_ad.ad.id, ad_group_ad.ad.type, ad_group_ad.policy_summary FROM ad_group_ad WHERE campaign.id = {campaignId}"; // Create a request that will retrieve all Disapproved Ads SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { PageSize = PAGE_SIZE, Query = searchQuery, CustomerId = customerId.ToString() }; int disapprovedAdsCount = 0; try { // Issue the search request. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = googleAdsService.Search(request); // 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; if (adGroupAd.PolicySummary.ApprovalStatus != PolicyApprovalStatus.Disapproved) { continue; } disapprovedAdsCount++; 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> /// Updates attribute value of the feed item. In order to update a FeedItemAttributeValue /// you must update the FeedItem. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> /// <param name="feedId">ID of the feed containing the feed item to be updated.</param> /// <param name="feedItemId">ID of the feed item to be updated.</param> /// <param name="flightPlaceholderFieldName">the placeholder type for the attribute to be /// updated.</param> /// <param name="attributeValue">String value with which to update the /// FeedAttributeValue.</param> private void UpdateFeedItem(GoogleAdsClient client, long customerId, long feedId, long feedItemId, string flightPlaceholderFieldName, string attributeValue) { // Get the FeedItemServiceClient. FeedItemServiceClient feedItemService = client.GetService(Services.V6.FeedItemService); // Gets the feed resource name. string feedResourceName = ResourceNames.Feed(customerId, feedId); // Gets a map of the placeholder values and feed attributes. Dictionary <FlightPlaceholderField, FeedAttribute> feedAttributes = GetFeed(client, customerId, feedResourceName); // Gets the ID of the attribute to update. This is needed to specify which // FeedItemAttributeValue will be updated in the given FeedItem. FlightPlaceholderField placeholderField = (FlightPlaceholderField)Enum.Parse( typeof(FlightPlaceholderField), flightPlaceholderFieldName); long attributeId = feedAttributes[placeholderField].Id; // Gets the feed item resource name. string feedItemResourceName = ResourceNames.FeedItem(customerId, feedId, feedItemId); // Retrieves the feed item and its associated attributes based on its resource name. FeedItem feedItem = GetFeedItem(client, customerId, feedItemResourceName); // Creates the updated FeedItemAttributeValue. FeedItemAttributeValue feedItemAttributeValue = new FeedItemAttributeValue() { FeedAttributeId = attributeId, StringValue = attributeValue }; // Creates a new FeedItem from the existing FeedItem. Any FeedItemAttributeValues that // are not included in the updated FeedItem will be removed from the FeedItem, which is // why you must create the FeedItem from the existing FeedItem and set the field(s) // that will be updated. int attributeIndex = feedItem.AttributeValues .Select((item, index) => new { item, index }) .Where(itemIndexPair => itemIndexPair.item.FeedAttributeId == feedItemAttributeValue.FeedAttributeId) .Select(itemIndexPair => itemIndexPair.index + 1) .FirstOrDefault() - 1; if (attributeIndex == -1) { throw new ArgumentException("No matching feed attribute found for " + $"value '{feedItemAttributeValue}'."); } feedItem.AttributeValues[attributeIndex] = feedItemAttributeValue; // Creates the operation. FeedItemOperation operation = new FeedItemOperation() { Update = feedItem, UpdateMask = FieldMasks.AllSetFieldsOf(feedItem) }; // Updates the feed item. MutateFeedItemsResponse response = feedItemService.MutateFeedItems(customerId.ToString(), new[] { operation }); foreach (MutateFeedItemResult result in response.Results) { Console.WriteLine($"Updated feed item with resource name '{result.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.V6.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> /// 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); // 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}"); throw; } }
/// <summary> /// Displays the result from the mutate operation. /// </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 to which keywords are added.</param> /// <param name="threadIndex">The thread ID.</param> private async Task CreateKeyword(GoogleAdsClient client, int threadIndex, long customerId, long adGroupId) { await Task.Run(() => { // Get the AdGroupCriterionServiceClient. AdGroupCriterionServiceClient adGroupCriterionService = client.GetService(Services.V10.AdGroupCriterionService); List <AdGroupCriterionOperation> operations = new List <AdGroupCriterionOperation>(); for (int i = 0; i < NUM_KEYWORDS; i++) { AdGroupCriterion criterion = new AdGroupCriterion() { Keyword = new KeywordInfo() { Text = $"mars cruise thread {threadIndex} seed {i}", MatchType = KeywordMatchType.Exact }, AdGroup = ResourceNames.AdGroup(customerId, adGroupId), Status = AdGroupCriterionStatus.Paused }; // Creates the operation. operations.Add(new AdGroupCriterionOperation() { Create = criterion }); } int retryCount = 0; int retrySeconds = 30; const int NUM_RETRIES = 3; while (retryCount < NUM_RETRIES) { try { // Makes the validateOnly mutate request. MutateAdGroupCriteriaResponse response = adGroupCriterionService.MutateAdGroupCriteria( new MutateAdGroupCriteriaRequest() { CustomerId = customerId.ToString(), Operations = { operations }, PartialFailure = false, ValidateOnly = true }); Console.WriteLine($"[{threadIndex}] Validated {operations.Count} " + $"ad group criteria:"); break; } catch (GoogleAdsException e) { // Checks if any of the errors are QuotaError.RESOURCE_EXHAUSTED or // QuotaError.RESOURCE_TEMPORARILY_EXHAUSTED. // Note: The code assumes that the developer token is approved for // Standard Access. if (e.Failure != null) { bool isRateExceededError = false; e.Failure.Errors .Where(err => err.ErrorCode.QuotaError == QuotaError.ResourceExhausted || err.ErrorCode.QuotaError == QuotaError.ResourceTemporarilyExhausted) .ToList() .ForEach(delegate(GoogleAdsError err) { Console.Error.WriteLine($"[{threadIndex}] Received rate " + $"exceeded error. Message says, \"{err.Message}\"."); isRateExceededError = true; } ); if (isRateExceededError) { Console.Error.WriteLine( $"[{threadIndex}] Will retry after {retrySeconds} seconds."); Thread.Sleep(retrySeconds * 1000); retryCount++; // Uses an exponential backoff policy to avoid polling too // aggressively. retrySeconds *= 2; } } else { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); break; } } finally { if (retryCount == NUM_RETRIES) { throw new Exception($"[{ threadIndex }] Could not recover after " + $"making {retryCount} attempts."); } } } }); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for the conversion action is /// added.</param> /// <param name="adGroupId">The ad group ID for which to update the audience targeting /// restriction.</param> public void Run(GoogleAdsClient client, long customerId, long adGroupId) { // Get the GoogleAdsService client. GoogleAdsServiceClient googleAdsServiceClient = client.GetService(Services.V6.GoogleAdsService); // Create a search request that retrieves the targeting settings from a given ad group. string query = $@" SELECT ad_group.id, ad_group.name, ad_group.targeting_setting.target_restrictions FROM ad_group WHERE ad_group.id = {adGroupId}"; try { // Issue the search request. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchResponse = googleAdsServiceClient.Search(customerId.ToString(), query); // Create an empty TargetingSetting instance. TargetingSetting targetingSetting = new TargetingSetting(); // Create a flag that specifies whether or not we should update the targeting // setting. We should only do this if we find an AUDIENCE target restriction with // bid_only set to false. bool shouldUpdateTargetingSetting = false; // Iterate over all rows in all pages and prints the requested field values for the // ad group in each row. foreach (GoogleAdsRow googleAdsRow in searchResponse) { AdGroup adGroup = googleAdsRow.AdGroup; Console.WriteLine($"Ad group with ID {adGroup.Id} and name '{adGroup.Name}' " + "was found with the following targeting restrictions:"); RepeatedField <TargetRestriction> targetRestrictions = adGroup.TargetingSetting.TargetRestrictions; // Loop through and print each of the target restrictions. Reconstruct the // TargetingSetting object with the updated audience target restriction because // Google will overwrite the entire targeting_setting field of the ad group when // the field mask includes targeting_setting in an update operation. foreach (TargetRestriction targetRestriction in targetRestrictions) { TargetingDimension targetingDimension = targetRestriction.TargetingDimension; bool bidOnly = targetRestriction.BidOnly; Console.WriteLine("\tTargeting restriction with targeting dimension " + $"'{targetingDimension}' and bid only set to '{bidOnly}'."); // Add the target restriction to the TargetingSetting object as is if the // targeting dimension has a value other than AUDIENCE because those should // not change. if (targetingDimension != TargetingDimension.Audience) { targetingSetting.TargetRestrictions.Add(targetRestriction); } else if (!bidOnly) { shouldUpdateTargetingSetting = true; // Add an AUDIENCE target restriction with bid_only set to true to the // targeting setting object. This has the effect of setting the AUDIENCE // target restriction to "Observation". For more details about the // targeting setting, visit // https://support.google.com/google-ads/answer/7365594. targetingSetting.TargetRestrictions.Add(new TargetRestriction { TargetingDimension = TargetingDimension.Audience, BidOnly = true }); } } } // Only update the TargetSetting on the ad group if there is an AUDIENCE // TargetRestriction with bid_only set to false. if (shouldUpdateTargetingSetting) { UpdateTargetingSetting(client, customerId, adGroupId, targetingSetting); } else { Console.WriteLine("No target restrictions to update."); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
/// <summary> /// Creates the feed. /// </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> /// <returns>Resource name of the newly created feed.</returns> private string CreateFeed(GoogleAdsClient client, long customerId) { // Get the FeedService. FeedServiceClient feedService = client.GetService(Services.V3.FeedService); // Creates a Flight Description attribute. FeedAttribute flightDescriptionAttribute = new FeedAttribute() { Type = FeedAttributeType.String, Name = "Flight Description" }; // Creates a Destination ID attribute. FeedAttribute destinationIdAttribute = new FeedAttribute() { Type = FeedAttributeType.String, Name = "Destination ID" }; // Creates a Flight Price attribute. FeedAttribute flightPriceAttribute = new FeedAttribute() { Type = FeedAttributeType.String, Name = "Flight Price" }; // Creates a Flight Sale Price attribute. FeedAttribute flightSalesPriceAttribute = new FeedAttribute() { Type = FeedAttributeType.String, Name = "Flight Sale Price" }; // Creates a Final URLs attribute. FeedAttribute finalUrlsAttribute = new FeedAttribute() { Type = FeedAttributeType.UrlList, Name = "Final URLs" }; // Creates the feed. Feed feed = new Feed() { Name = "Flights Feed #" + ExampleUtilities.GetRandomString(), Attributes = { flightDescriptionAttribute, destinationIdAttribute, flightPriceAttribute, flightSalesPriceAttribute, finalUrlsAttribute } }; // Creates the operation. FeedOperation operation = new FeedOperation() { Create = feed }; // Adds the feed. MutateFeedsResponse response = feedService.MutateFeeds(customerId.ToString(), new[] { operation }); string feedResourceName = response.Results[0].ResourceName; // Displays the result. Console.WriteLine($"Feed with resource name '{feedResourceName}' was created."); return(feedResourceName); }
/// <summary> /// Creates a list of ExtensionFeedItems. /// </summary> ///<param name="client">The Google Ads API client.</param> ///<param name="customerId">The client customer ID.</param> ///<param name="campaignResourceName">The resource name of the campaign to target.</param> private static List <string> CreateExtensionFeedItems(GoogleAdsClient client, long customerId, string campaignResourceName) { // Get the ExtensionFeedItemServiceClient. ExtensionFeedItemServiceClient extensionFeedItemService = client.GetService(Services.V2.ExtensionFeedItemService); SitelinkFeedItem sitelinkFeedItem1 = CreateSitelinkFeedItem( "Store Hours", "http://www.example.com/storehours"); // Creates an ExtensionFeedItem from the SitelinkFeedItem. ExtensionFeedItem extensionFeedItem1 = new ExtensionFeedItem() { ExtensionType = ExtensionType.Sitelink, SitelinkFeedItem = sitelinkFeedItem1, TargetedCampaign = campaignResourceName }; List <ExtensionFeedItemOperation> operations = new List <ExtensionFeedItemOperation>(); // Creates an ExtensionFeedItemOperation and adds it to the operations List. operations.Add(new ExtensionFeedItemOperation() { Create = extensionFeedItem1 }); SitelinkFeedItem sitelinkFeedItem2 = CreateSitelinkFeedItem( "Thanksgiving Specials", "http://www.example.com/thanksgiving"); DateTime startTime = new DateTime(DateTime.Now.Year, 11, 20, 0, 0, 0); if (startTime < DateTime.Now) { // Move the startTime to next year if the current date is past November 20th. startTime = startTime.AddYears(1); } // Converts to a string in the required format. string startTimeString = startTime.ToString("yyyy-MM-dd hh:mm:ss"); // Use the same year as startTime when creating endTime. DateTime endTime = new DateTime(startTime.Year, 11, 27, 23, 59, 59); string unitedStates = ResourceNames.GeoTargetConstant(2840); ExtensionFeedItem extensionFeedItem2 = new ExtensionFeedItem() { ExtensionType = ExtensionType.Sitelink, SitelinkFeedItem = sitelinkFeedItem2, TargetedCampaign = campaignResourceName, // StartDateTime should be formatted in "yyyy-MM-dd hh:mm:ss" format. StartDateTime = startTime.ToString("yyyy-MM-dd hh:mm:ss"), // EndDateTime should be formatted in "yyyy-MM-dd hh:mm:ss" format. EndDateTime = endTime.ToString("yyyy-MM-dd hh:mm:ss"), // Targets this sitelink for United States only. // A list of country codes can be referenced here: // https://developers.google.com/adwords/api/docs/appendix/geotargeting TargetedGeoTargetConstant = ResourceNames.GeoTargetConstant(2840) }; operations.Add(new ExtensionFeedItemOperation() { Create = extensionFeedItem2 }); SitelinkFeedItem sitelinkFeedItem3 = CreateSitelinkFeedItem( "Wifi available", "http://www.example.com/mobile/wifi"); ExtensionFeedItem extensionFeedItem3 = new ExtensionFeedItem() { ExtensionType = ExtensionType.Sitelink, SitelinkFeedItem = sitelinkFeedItem3, TargetedCampaign = campaignResourceName, Device = FeedItemTargetDevice.Mobile, TargetedKeyword = new KeywordInfo() { Text = "free wifi", MatchType = KeywordMatchType.Broad } }; operations.Add(new ExtensionFeedItemOperation() { Create = extensionFeedItem3 }); SitelinkFeedItem sitelinkFeedItem4 = CreateSitelinkFeedItem( "Happy hours", "http://www.example.com/happyhours"); ExtensionFeedItem extensionFeedItem4 = new ExtensionFeedItem() { ExtensionType = ExtensionType.Sitelink, SitelinkFeedItem = sitelinkFeedItem4, TargetedCampaign = campaignResourceName, AdSchedules = { CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Monday, 18, MinuteOfHour.Zero, 21, MinuteOfHour.Zero), CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Tuesday, 18, MinuteOfHour.Zero, 21, MinuteOfHour.Zero), CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Wednesday, 18, MinuteOfHour.Zero, 21, MinuteOfHour.Zero), CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Thursday, 18, MinuteOfHour.Zero, 21, MinuteOfHour.Zero), CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Friday, 18, MinuteOfHour.Zero, 21, MinuteOfHour.Zero), } }; operations.Add(new ExtensionFeedItemOperation() { Create = extensionFeedItem4 }); // Adds the ExtensionFeedItem. MutateExtensionFeedItemsResponse response = extensionFeedItemService.MutateExtensionFeedItems(customerId.ToString(), operations); Console.WriteLine($"Added {response.Results.Count}:"); List <string> resourceNames = new List <string>(); foreach (MutateExtensionFeedItemResult result in response.Results) { Console.WriteLine($"Created ExtensionFeedItems with " + $"resource name '{result.ResourceName}'."); resourceNames.Add(result.ResourceName); } return(resourceNames); }
/// <summary> /// Creates a feed mapping for a given feed. /// </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="feedAttributes">The feed attributes.</param> /// <param name="feedResourceName">The resource name of the feed.</param> private void CreateFeedMapping(GoogleAdsClient client, long customerId, Dictionary <FlightPlaceholderField, FeedAttribute> feedAttributes, string feedResourceName) { // Get the FeedMappingServiceClient. FeedMappingServiceClient feedMappingService = client.GetService( Services.V3.FeedMappingService); // Maps the FeedAttributeIds to the fieldId constants. AttributeFieldMapping flightDescriptionMapping = new AttributeFieldMapping() { FeedAttributeId = feedAttributes[FlightPlaceholderField.FlightDescription].Id, FlightField = FlightPlaceholderField.FlightDescription }; AttributeFieldMapping destinationIdMapping = new AttributeFieldMapping() { FeedAttributeId = feedAttributes[FlightPlaceholderField.DestinationId].Id, FlightField = FlightPlaceholderField.DestinationId }; AttributeFieldMapping flightPriceMapping = new AttributeFieldMapping() { FeedAttributeId = feedAttributes[FlightPlaceholderField.FlightPrice].Id, FlightField = FlightPlaceholderField.FlightPrice }; AttributeFieldMapping flightSalePriceMapping = new AttributeFieldMapping() { FeedAttributeId = feedAttributes[FlightPlaceholderField.FlightSalePrice].Id, FlightField = FlightPlaceholderField.FlightSalePrice }; AttributeFieldMapping finalUrlsMapping = new AttributeFieldMapping() { FeedAttributeId = feedAttributes[FlightPlaceholderField.FinalUrls].Id, FlightField = FlightPlaceholderField.FinalUrls }; // Creates the feed mapping. FeedMapping feedMapping = new FeedMapping() { PlaceholderType = PlaceholderType.DynamicFlight, Feed = feedResourceName, AttributeFieldMappings = { flightDescriptionMapping, destinationIdMapping, flightPriceMapping, flightSalePriceMapping, finalUrlsMapping } }; // Creates the operation. FeedMappingOperation operation = new FeedMappingOperation() { Create = feedMapping }; // Adds the FeedMapping. MutateFeedMappingsResponse response = feedMappingService.MutateFeedMappings( customerId.ToString(), new[] { operation }); // Displays the results. foreach (MutateFeedMappingResult result in response.Results) { Console.WriteLine($"Created feed mapping with resource name" + $" '{result.ResourceName}'."); } }
/// <summary> /// Creates the feed. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the real estate feed is /// added.</param> /// <returns>Resource name of the newly created feed.</returns> private string CreateFeed(GoogleAdsClient client, long customerId) { // Get the FeedService. FeedServiceClient feedService = client.GetService(Services.V2.FeedService); // Creates a Listing ID attribute. FeedAttribute listingIdAttribute = new FeedAttribute() { Type = FeedAttributeType.String, Name = "Listing ID" }; // Creates a Listing Name attribute. FeedAttribute listingNameAttribute = new FeedAttribute() { Type = FeedAttributeType.String, Name = "Listing Name" }; // Creates a Final URLs attribute. FeedAttribute finalUrlsAttribute = new FeedAttribute() { Type = FeedAttributeType.UrlList, Name = "Final URLs" }; // Creates an Image URL attribute FeedAttribute imageUrlAttribute = new FeedAttribute() { Type = FeedAttributeType.Url, Name = "Image URL" }; // Creates a Contextual Keywords attribute FeedAttribute contextualKeywordsAttribute = new FeedAttribute() { Type = FeedAttributeType.StringList, Name = "Contextual Keywords" }; // Creates the feed. Feed feed = new Feed() { Name = "Real Estate Feed #" + ExampleUtilities.GetRandomString(), Attributes = { listingIdAttribute, listingNameAttribute, finalUrlsAttribute, imageUrlAttribute, contextualKeywordsAttribute } }; // Creates the operation. FeedOperation operation = new FeedOperation() { Create = feed }; // Adds the feed. MutateFeedsResponse response = feedService.MutateFeeds(customerId.ToString(), new[] { operation }); string feedResourceName = response.Results[0].ResourceName; // Displays the result. Console.WriteLine($"Feed with resource name '{feedResourceName}' was created."); return(feedResourceName); }
/// <summary> /// Creates the text ads. /// </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">ID of the ad group in which ads are created.</param> /// <returns>The newly created ad group ad instances.</returns> private gagvr::AdGroupAd[] CreateTextAds(GoogleAdsClient client, long customerId, long adGroupId) { // Get the AdGroupAdService. gagvs::AdGroupAdServiceClient adGroupAdService = client.GetService( Services.V10.AdGroupAdService); List <gagvs::AdGroupAdOperation> operations = new List <gagvs::AdGroupAdOperation>(); for (int i = 0; i < NUMBER_OF_ADS; i++) { // Create the ad group ad object. gagvr::AdGroupAd adGroupAd = new gagvr::AdGroupAd { AdGroup = gagver::ResourceNames.AdGroup(customerId, adGroupId), // Optional: Set the status. Status = gag__AdGroupAdStatus.Paused, Ad = new gagvr::Ad { FinalUrls = { "http://www.example.com/" + i }, ExpandedTextAd = new gagvc::ExpandedTextAdInfo { Description = "Buy your tickets now!", HeadlinePart1 = "Cruise #" + i.ToString() + " to Mars", HeadlinePart2 = "Best Space Cruise Line", Path1 = "path1", Path2 = "path2" } } }; // Create the operation. operations.Add(new gagvs::AdGroupAdOperation { Create = adGroupAd }); } // Create the ads. gagvs::MutateAdGroupAdsResponse response = adGroupAdService.MutateAdGroupAds( customerId.ToString(), operations); // Retrieve the newly created ad group ads. List <string> newResourceNames = response.Results.Select(result => result.ResourceName).ToList(); gagvr::AdGroupAd[] newAdGroupAds = GetAdGroupAds(client, customerId, newResourceNames); // Display the results. foreach (gagvr::AdGroupAd newAdGroupAd in newAdGroupAds) { gagvr::Ad ad = newAdGroupAd.Ad; gagvc::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, newAdGroupAd.Status, expandedTextAdInfo.HeadlinePart1, expandedTextAdInfo.HeadlinePart2, adGroupId); } // Return the newly created ad group ads. return(newAdGroupAds); }
/// <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 real estate feed is /// added.</param> /// <param name="feedResourceName">The resource name of the feed.</param> /// <returns> /// A Map containing the RealEstatePlaceholderField and FeedAttribute. /// </returns> public Dictionary <RealEstatePlaceholderField, FeedAttribute> GetFeed( GoogleAdsClient client, long customerId, string feedResourceName) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V2.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 <RealEstatePlaceholderField, FeedAttribute> feedAttributes = new Dictionary <RealEstatePlaceholderField, FeedAttribute>(); // Loops through the feed attributes to populate the map. foreach (FeedAttribute feedAttribute in googleAdsRow.Feed.Attributes) { switch (feedAttribute.Name) { case "Listing ID": feedAttributes[RealEstatePlaceholderField.ListingId] = feedAttribute; break; case "Listing Name": feedAttributes[RealEstatePlaceholderField.ListingName] = feedAttribute; break; case "Final URLs": feedAttributes[RealEstatePlaceholderField.FinalUrls] = feedAttribute; break; case "Image URL": feedAttributes[RealEstatePlaceholderField.ImageUrl] = feedAttribute; break; case "Contextual Keywords": feedAttributes[RealEstatePlaceholderField.ContextualKeywords] = feedAttribute; break; // The full list of RealEstatePlaceholderField can be found here // https://developers.google.com/google-ads/api/reference/rpc/google.ads.googleads.v2.enums#RealEstatePlaceholderFieldenum. default: throw new Exception("Invalid attribute name."); } } return(feedAttributes); }
/// <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 service = client.GetService(Services.V3.GoogleAdsService); string query = @"SELECT recommendation.type, recommendation.campaign, recommendation.text_ad_recommendation FROM recommendation WHERE recommendation.type = TEXT_AD"; // Create a request that will retrieve all recommendations using pages of the // specified page size. SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), PageSize = PAGE_SIZE, Query = query }; try { // Issue the search request. PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse = service.Search(customerId.ToString(), query); // Iterates over all rows in all pages and prints the requested field values // for the recommendation in each row. foreach (GoogleAdsRow googleAdsRow in searchPagedResponse) { Recommendation recommendation = googleAdsRow.Recommendation; // [START_EXCLUDE] Ad recommendedAd = recommendation.TextAdRecommendation.Ad; Console.WriteLine($"Recommendation ({recommendation.ResourceName}) was " + $"found for campaign {recommendation.Campaign}:"); if (recommendedAd.ExpandedTextAd != null) { ExpandedTextAdInfo eta = recommendedAd.ExpandedTextAd; Console.WriteLine("\tHeadline 1 = {0}\n\tHeadline 2 = {1}\t" + "Description = {2}", eta.HeadlinePart1, eta.HeadlinePart2, eta.Description); } Console.WriteLine($"\tDisplay URL = {recommendedAd.DisplayUrl}"); foreach (string url in recommendedAd.FinalUrls) { Console.WriteLine($"\tFinal URL = {url}"); } foreach (string url in recommendedAd.FinalMobileUrls) { Console.WriteLine($"\tFinal Mobile URL = {url}"); } // [END_EXCLUDE] } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); } }
/// <summary> /// Creates a feed mapping for a given feed. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the real estate feed is /// added.</param> /// <param name="feedAttributes">The feed attributes.</param> /// <param name="feedResourceName">The resource name of the feed.</param> private void CreateFeedMapping(GoogleAdsClient client, long customerId, Dictionary <RealEstatePlaceholderField, FeedAttribute> feedAttributes, string feedResourceName) { // Get the FeedMappingServiceClient. FeedMappingServiceClient feedMappingService = client.GetService( Services.V2.FeedMappingService); // Maps the FeedAttributeIds to the placeholder values. The FeedAttributeId is the // ID of the FeedAttribute created in the CreatedFeed method. This can be thought of // as the generic ID of the column of the new feed. The placeholder value specifies // the type of column this is in the context of a real estate feed (e.g. // a LISTING_ID or LISTING_NAME). The FeedMapping associates the feed column by ID to // this type and controls how the feed attributes are presented in dynamic content. // See https://developers.google.com/google-ads/api/reference/rpc/google.ads.googleads.v2.enums#google.ads.googleads.v2.enums.RealEstatePlaceholderFieldEnum.RealEstatePlaceholderField // for the full list of placeholder values. AttributeFieldMapping listingIdMapping = new AttributeFieldMapping() { FeedAttributeId = feedAttributes[RealEstatePlaceholderField.ListingId].Id, RealEstateField = RealEstatePlaceholderField.ListingId }; AttributeFieldMapping listingNameMapping = new AttributeFieldMapping() { FeedAttributeId = feedAttributes[RealEstatePlaceholderField.ListingName].Id, RealEstateField = RealEstatePlaceholderField.ListingName }; AttributeFieldMapping finalUrlsMapping = new AttributeFieldMapping() { FeedAttributeId = feedAttributes[RealEstatePlaceholderField.FinalUrls].Id, RealEstateField = RealEstatePlaceholderField.FinalUrls }; AttributeFieldMapping imageUrlMapping = new AttributeFieldMapping() { FeedAttributeId = feedAttributes[RealEstatePlaceholderField.ImageUrl].Id, RealEstateField = RealEstatePlaceholderField.ImageUrl }; AttributeFieldMapping contextualKeywordsMapping = new AttributeFieldMapping() { FeedAttributeId = feedAttributes[RealEstatePlaceholderField.ContextualKeywords].Id, RealEstateField = RealEstatePlaceholderField.ContextualKeywords }; // Creates the feed mapping. FeedMapping feedMapping = new FeedMapping() { PlaceholderType = PlaceholderType.DynamicRealEstate, Feed = feedResourceName, AttributeFieldMappings = { listingIdMapping, listingNameMapping, finalUrlsMapping, imageUrlMapping, contextualKeywordsMapping } }; // Creates the operation. FeedMappingOperation operation = new FeedMappingOperation() { Create = feedMapping }; // Adds the FeedMapping. MutateFeedMappingsResponse response = feedMappingService.MutateFeedMappings( customerId.ToString(), new[] { operation }); // Displays the results. foreach (MutateFeedMappingResult result in response.Results) { Console.WriteLine($"Created feed mapping with resource name" + $" '{result.ResourceName}'."); } }
/// <summary> /// Adds the media files. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <returns>A map with key as image name, and value as image bytes.</returns> private Dictionary <string, string> AddMediaFiles(GoogleAdsClient client, long customerId) { // Get the MediaFileService. MediaFileServiceClient mediaFileService = client.GetService(Services.V4.MediaFileService); // Creates a bytes array from the logo image data. byte[] logoImageData = MediaUtilities.GetAssetDataFromUrl( "https://goo.gl/mtt54n", client.Config); // Creates the logo image. MediaFile mediaFileLogo = new MediaFile() { Type = MediaType.Image, Image = new MediaImage() { Data = ByteString.CopyFrom(logoImageData) }, MimeType = MimeType.ImagePng }; // Creates the operation for the logo image. MediaFileOperation mediaFileLogoOperation = new MediaFileOperation() { Create = mediaFileLogo }; // Creates a bytes array from the marketing image data. byte[] marketingImageData = MediaUtilities.GetAssetDataFromUrl( "https://goo.gl/3b9Wfh", client.Config); // Creates the marketing image. MediaFile mediaFileMarketing = new MediaFile() { Type = MediaType.Image, Image = new MediaImage() { Data = ByteString.CopyFrom(marketingImageData) }, MimeType = MimeType.ImageJpeg }; // Creates the operation for the marketing image. MediaFileOperation mediaFileMarketingOperation = new MediaFileOperation() { Create = mediaFileMarketing }; // Adds the media files. MutateMediaFilesResponse response = mediaFileService.MutateMediaFiles(customerId.ToString(), new[] { mediaFileLogoOperation, mediaFileMarketingOperation }); // Display the results. foreach (MutateMediaFileResult result in response.Results) { Console.WriteLine($"Created media file with resource name " + $"'{result.ResourceName}'."); } return(new Dictionary <string, string>() { { "logoResourceName", response.Results[0].ResourceName }, { "marketingImageResourceName", response.Results[1].ResourceName }, }); }
/// <summary> /// Adds a new item to the feed. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the real estate feed is /// added.</param> /// <param name="feedAttributes">The feed attributes.</param> /// <param name="feedResourceName">The resource name of the feed.</param> private void CreateFeedItem(GoogleAdsClient client, long customerId, Dictionary <RealEstatePlaceholderField, FeedAttribute> feedAttributes, string feedResourceName) { // Get the FeedItemServiceClient. FeedItemServiceClient feedItemService = client.GetService( Services.V2.FeedItemService); // Creates the listing ID feed attribute value. FeedItemAttributeValue listingId = new FeedItemAttributeValue() { FeedAttributeId = feedAttributes[RealEstatePlaceholderField.ListingId].Id, StringValue = "ABC123DEF" }; // Creates the listing name feed attribute value. FeedItemAttributeValue listingName = new FeedItemAttributeValue() { FeedAttributeId = feedAttributes[RealEstatePlaceholderField.ListingName].Id, StringValue = "Two bedroom with magnificent views" }; // Creates the final URLs feed attribute value. FeedItemAttributeValue finalUrls = new FeedItemAttributeValue() { FeedAttributeId = feedAttributes[RealEstatePlaceholderField.FinalUrls].Id, StringValue = "http://www.example.com/listings/" }; // Creates the image URL feed attribute value. FeedItemAttributeValue imageUrl = new FeedItemAttributeValue() { FeedAttributeId = feedAttributes[RealEstatePlaceholderField.ImageUrl].Id, StringValue = "http://www.example.com/listings/images?listing_id=ABC123DEF" }; // Creates the contextual keywords feed attribute value. FeedItemAttributeValue contextualKeywords = new FeedItemAttributeValue() { FeedAttributeId = feedAttributes[RealEstatePlaceholderField.ContextualKeywords].Id, StringValues = { "beach community", "ocean view", "two bedroom", } }; // Creates the FeedItem, specifying the Feed ID and the attributes created above. FeedItem feedItem = new FeedItem() { Feed = feedResourceName, AttributeValues = { listingId, listingName, finalUrls, imageUrl, contextualKeywords } }; // Creates an operation to add the FeedItem. FeedItemOperation operation = new FeedItemOperation() { Create = feedItem }; // Adds the feed item. MutateFeedItemsResponse response = feedItemService.MutateFeedItems(customerId.ToString(), new FeedItemOperation[] { operation }); foreach (MutateFeedItemResult result in response.Results) { Console.WriteLine($"Created feed item with resource name " + $"'{result.ResourceName}'."); } }
/// <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 CampaignService. CampaignServiceClient campaignService = client.GetService(Services.V0.CampaignService); // Create a budget to be used for the campaign. string budget = CreateBudget(client, customerId); List <CampaignOperation> operations = new List <CampaignOperation>(); for (int i = 0; i < NUM_CAMPAIGNS_TO_CREATE; i++) { // Create the campaign. Campaign campaign = new Campaign(); campaign.Name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(); campaign.AdvertisingChannelType = AdvertisingChannelType.Search; // Recommendation: Set the campaign to PAUSED when creating it to prevent // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve campaign.Status = CampaignStatus.Paused; // Set the bidding strategy and budget. campaign.ManualCpc = new ManualCpc(); campaign.CampaignBudget = budget; // Set the campaign network options. campaign.NetworkSettings = new NetworkSettings { TargetGoogleSearch = true, TargetSearchNetwork = true, TargetContentNetwork = false, TargetPartnerSearchNetwork = false }; // Optional: Set the start date. campaign.StartDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd"); // Optional: Set the end date. campaign.EndDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd"); // Create the operation. CampaignOperation operation = new CampaignOperation(); operation.Create = campaign; operations.Add(operation); } try { // Add the campaigns. MutateCampaignsResponse retVal = campaignService.MutateCampaigns( customerId.ToString(), operations.ToArray()); // Display the results. if (retVal.Results.Count > 0) { foreach (MutateCampaignResult newCampaign in retVal.Results) { Console.WriteLine("Campaign with resource ID = '{0}' was added.", newCampaign.ResourceName); } } else { Console.WriteLine("No campaigns were added."); } } 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 the conversion action is /// added.</param> public void Run(GoogleAdsClient client, long customerId) { // Get the RemarketingActionService. RemarketingActionServiceClient remarketingActionService = client.GetService(Services.V4.RemarketingActionService); // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService(Services.V4.GoogleAdsService); try { // Creates a remarketing action with the specified name. RemarketingAction remarketingAction = new RemarketingAction() { Name = $"Remarketing action # {ExampleUtilities.GetRandomString()}" }; // Creates a remarketing action operation. RemarketingActionOperation remarketingActionOperation = new RemarketingActionOperation() { Create = remarketingAction }; // Issues a mutate request to add the remarketing action and prints out // some information. MutateRemarketingActionsResponse response = remarketingActionService.MutateRemarketingActions( customerId.ToString(), new[] { remarketingActionOperation }); string remarketingActionResourceName = response.Results[0].ResourceName; Console.WriteLine($"Added remarketing action with resource name " + $"'{remarketingActionResourceName}'."); // Creates a query that retrieves the previously created remarketing action // with its generated tag snippets. var query = $"SELECT remarketing_action.id, remarketing_action.name, " + $"remarketing_action.tag_snippets FROM remarketing_action " + $"WHERE remarketing_action.resource_name = '{remarketingActionResourceName}'"; // Issues a search request and retrieve the results. There is only one row // because we limited the search using the resource name, which is unique. RemarketingAction result = googleAdsService.Search(customerId.ToString(), query) .First() .RemarketingAction; // Display the result. Console.WriteLine($"Remarketing action has ID {result.Id} and name" + $" '{result.Id}'."); Console.WriteLine("It has the following generated tag snippets:"); foreach (TagSnippet tagSnippet in result.TagSnippets) { Console.WriteLine($"Tag snippet with code type '{tagSnippet.Type}' and code " + $"page format '{tagSnippet.PageFormat}' has the following global site " + $"tag:{tagSnippet.GlobalSiteTag} \n\nand the following event snippet:" + $"{tagSnippet.EventSnippet}."); } } 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 to which the new user list will be /// added.</param> // [START AddExpressionRuleUserList] public void Run(GoogleAdsClient client, long customerId) { // Gets the UserListService. UserListServiceClient userListServiceClient = client.GetService(Services.V6.UserListService); // Creates the user targeting rules for each URL. UserListRuleItemInfo rule1 = BuildVisitedSiteRuleInfo("example.com/section1"); UserListRuleItemInfo rule2 = BuildVisitedSiteRuleInfo("example.com/section2"); // Combine the two rule items into a UserListRuleItemGroupInfo object so Google Ads will // AND their rules together. To instead OR the rules together, each rule should be // placed in its own rule item group. UserListRuleItemGroupInfo userListRuleItemGroupInfo = new UserListRuleItemGroupInfo(); userListRuleItemGroupInfo.RuleItems.Add(rule1); userListRuleItemGroupInfo.RuleItems.Add(rule2); UserListRuleInfo userListRuleInfo = new UserListRuleInfo(); userListRuleInfo.RuleItemGroups.Add(userListRuleItemGroupInfo); // Creates an ExpressionRuleUserListInfo object, or a boolean rule that defines this // user list. The default rule_type for a UserListRuleInfo object is OR of ANDs // (disjunctive normal form). That is, rule items will be ANDed together within rule // item groups and the groups themselves will be ORed together. ExpressionRuleUserListInfo expressionRuleUserListInfo = new ExpressionRuleUserListInfo { Rule = userListRuleInfo }; // Defines a representation of a user list that is generated by a rule. RuleBasedUserListInfo ruleBasedUserListInfo = new RuleBasedUserListInfo { // Optional: To include past users in the user list, set the prepopulation_status to // REQUESTED. PrepopulationStatus = UserListPrepopulationStatus.Requested, ExpressionRuleUserList = expressionRuleUserListInfo }; // Creates a new user list. UserList userList = new UserList { Name = "All visitors to example.com/section1 AND example.com/section2 " + $"#{ExampleUtilities.GetRandomString()}", Description = "Visitors of both example.com/section1 AND example.com/section2", MembershipStatus = UserListMembershipStatus.Open, MembershipLifeSpan = 365L, RuleBasedUserList = ruleBasedUserListInfo }; // Creates the operation. UserListOperation operation = new UserListOperation() { Create = userList }; try { // Adds the user list. MutateUserListsResponse response = userListServiceClient.MutateUserLists (customerId.ToString(), new[] { operation }); // Displays the results. Console.WriteLine("Created new user list with resource name: " + $"'{response.Results.First().ResourceName}'."); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <param name="campaignId">The campaign to which listing scope is added.</param> public void Run(GoogleAdsClient client, long customerId, long campaignId) { // Get the CampaignCriterionService. CampaignCriterionServiceClient campaignCriterionService = client.GetService(Services.V10.CampaignCriterionService); // A listing scope allows you to filter the products that will be included in a given // campaign. You can specify multiple dimensions with conditions that must be met for // a product to be included in a campaign. // A typical ListingScope might only have a few dimensions. This example demonstrates // a range of different dimensions you could use. ListingScopeInfo listingScope = new ListingScopeInfo() { Dimensions = { // Creates a ProductBrand dimension set to "google". new ListingDimensionInfo() { ProductBrand = new ProductBrandInfo() { Value = "google" } }, // Creates a ProductCustomAttribute dimension for INDEX0 set to // "top_selling_products". new ListingDimensionInfo() { ProductCustomAttribute = new ProductCustomAttributeInfo() { Index = ProductCustomAttributeIndex.Index0, Value = "top_selling_products" } }, // Creates a ProductType dimension for LEVEL1 set to "electronics". new ListingDimensionInfo() { ProductType = new ProductTypeInfo() { Level = ProductTypeLevel.Level1, Value = "electronics" } }, // Creates a ProductType dimension for LEVEL2 set to "smartphones". new ListingDimensionInfo() { ProductType = new ProductTypeInfo() { Level = ProductTypeLevel.Level2, Value = "smartphones" } }, } }; string campaignResourceName = ResourceNames.Campaign(customerId, campaignId); // Creates a campaign criterion to store the listing scope. CampaignCriterion campaignCriterion = new CampaignCriterion() { Campaign = campaignResourceName, ListingScope = listingScope }; CampaignCriterionOperation operation = new CampaignCriterionOperation() { Create = campaignCriterion }; try { // Calls the mutate method to add the campaign criterion. MutateCampaignCriteriaResponse response = campaignCriterionService.MutateCampaignCriteria( customerId.ToString(), new[] { operation }); Console.WriteLine($"Added {response.Results.Count} campaign criteria:"); foreach (MutateCampaignCriterionResult result in response.Results) { Console.WriteLine(result.ResourceName); } } 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="googleAdsClient">The Google Ads client instance.</param> /// <param name="managerCustomerId">Optional manager account ID. If none provided, this method /// will instead list the accounts accessible from the authenticated Google Ads account. /// </param> /// <param name="loginCustomerId">The login customer ID used to create the GoogleAdsClient. /// </param> public void Run(GoogleAdsClient googleAdsClient, long?managerCustomerId = null, long?loginCustomerId = null) { if (loginCustomerId.HasValue) { googleAdsClient.Config.LoginCustomerId = loginCustomerId.Value.ToString(); } GoogleAdsServiceClient googleAdsServiceClient = googleAdsClient.GetService(Services.V4.GoogleAdsService); CustomerServiceClient customerServiceClient = googleAdsClient.GetService(Services.V4.CustomerService); // List of Customer IDs to handle. List <long> seedCustomerIds = new List <long>(); // If a Manager ID was provided in the customerId parameter, it will be the only ID // in the list. Otherwise, we will issue a request for all customers accessible by // this authenticated Google account. if (managerCustomerId.HasValue) { seedCustomerIds.Add(managerCustomerId.Value); } else { Console.WriteLine( "No manager customer ID is specified. The example will print the hierarchies " + " of all accessible customer IDs:"); string[] customerResourceNames = customerServiceClient.ListAccessibleCustomers(); foreach (string customerResourceName in customerResourceNames) { Customer customer = customerServiceClient.GetCustomer(customerResourceName); Console.WriteLine(customer.Id.Value); seedCustomerIds.Add(customer.Id.Value); } Console.WriteLine(); } // Creates a query that retrieves all child accounts of the manager specified in // search calls below. const string query = @"SELECT customer_client.client_customer, customer_client.level, customer_client.manager, customer_client.descriptive_name, customer_client.currency_code, customer_client.time_zone, customer_client.id FROM customer_client WHERE customer_client.level <= 1"; foreach (long seedCustomerId in seedCustomerIds) { // Performs a breadth-first search to build a Dictionary that maps managers to their // child accounts (customerIdsToChildAccounts). Queue <long> unprocessedCustomerIds = new Queue <long>(); unprocessedCustomerIds.Enqueue(seedCustomerId); Dictionary <long, List <CustomerClient> > customerIdsToChildAccounts = new Dictionary <long, List <CustomerClient> >(); CustomerClient rootCustomerClient = null; while (unprocessedCustomerIds.Count > 0) { managerCustomerId = unprocessedCustomerIds.Dequeue(); PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> response = googleAdsServiceClient.Search( managerCustomerId.ToString(), query, pageSize: PAGE_SIZE ); // Iterates over all rows in all pages to get all customer clients under the // specified customer's hierarchy. foreach (GoogleAdsRow googleAdsRow in response) { CustomerClient customerClient = googleAdsRow.CustomerClient; // The customer client that with level 0 is the specified customer. if (customerClient.Level == 0) { if (rootCustomerClient == null) { rootCustomerClient = customerClient; } continue; } // For all level-1 (direct child) accounts that are a manager account, // the above query will be run against them to create a Dictionary of // managers mapped to their child accounts for printing the hierarchy // afterwards. if (!customerIdsToChildAccounts.ContainsKey(managerCustomerId.Value)) { customerIdsToChildAccounts.Add(managerCustomerId.Value, new List <CustomerClient>()); } customerIdsToChildAccounts[managerCustomerId.Value].Add(customerClient); if (customerClient.Manager.HasValue && customerClient.Manager.Value) { // A customer can be managed by multiple managers, so to prevent // visiting the same customer many times, we need to check if it's // already in the Dictionary. if (!customerIdsToChildAccounts.ContainsKey(customerClient.Id.Value) && customerClient.Level == 1) { unprocessedCustomerIds.Enqueue(customerClient.Id.Value); } } } } if (rootCustomerClient != null) { Console.WriteLine("The hierarchy of customer ID {0} is printed below:", rootCustomerClient.Id); PrintAccountHierarchy(rootCustomerClient, customerIdsToChildAccounts, 0); Console.WriteLine(); } else { Console.WriteLine( "Customer ID {0} is likely a test account, so its customer client " + " information cannot be retrieved.", managerCustomerId); } } }
/// <summary> /// Creates keywords for the keyword plan. /// </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="planAdGroupResource">The resource name of the ad group under which the /// keyword is created.</param> private static void CreateKeywordPlanAdGroupKeywords(GoogleAdsClient client, long customerId, string planAdGroupResource) { // Get the KeywordPlanAdGroupKeywordService. KeywordPlanAdGroupKeywordServiceClient serviceClient = client.GetService( Services.V6.KeywordPlanAdGroupKeywordService); // Create the adgroup level keywords for keyword plan. KeywordPlanAdGroupKeyword kpAdGroupKeyword1 = new KeywordPlanAdGroupKeyword() { KeywordPlanAdGroup = planAdGroupResource, CpcBidMicros = 2_000_000L, MatchType = KeywordMatchType.Broad, Text = "mars cruise" }; KeywordPlanAdGroupKeyword kpAdGroupKeyword2 = new KeywordPlanAdGroupKeyword() { KeywordPlanAdGroup = planAdGroupResource, CpcBidMicros = 1_500_000L, MatchType = KeywordMatchType.Phrase, Text = "cheap cruise" }; KeywordPlanAdGroupKeyword kpAdGroupKeyword3 = new KeywordPlanAdGroupKeyword() { KeywordPlanAdGroup = planAdGroupResource, CpcBidMicros = 1_990_000L, MatchType = KeywordMatchType.Exact, Text = "jupiter cruise" }; KeywordPlanAdGroupKeyword[] kpAdGroupKeywords = new KeywordPlanAdGroupKeyword[] { kpAdGroupKeyword1, kpAdGroupKeyword2, kpAdGroupKeyword3 }; // Create an operation for each plan keyword. List <KeywordPlanAdGroupKeywordOperation> operations = new List <KeywordPlanAdGroupKeywordOperation>(); foreach (KeywordPlanAdGroupKeyword kpAdGroupKeyword in kpAdGroupKeywords) { operations.Add(new KeywordPlanAdGroupKeywordOperation { Create = kpAdGroupKeyword }); } // Add the keywords. MutateKeywordPlanAdGroupKeywordsResponse response = serviceClient.MutateKeywordPlanAdGroupKeywords(customerId.ToString(), operations); // Display the results. foreach (MutateKeywordPlanAdGroupKeywordResult result in response.Results) { Console.WriteLine( $"Created ad group keyword for keyword plan: {result.ResourceName}."); } return; }