/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { using (AdwordsUserListService userListService = (AdwordsUserListService)user.GetService(AdWordsService.v201809 .AdwordsUserListService)) using (ConversionTrackerService conversionTrackerService = (ConversionTrackerService)user.GetService(AdWordsService.v201809 .ConversionTrackerService)) { BasicUserList userList = new BasicUserList { name = "Mars cruise customers #" + ExampleUtilities.GetRandomString(), description = "A list of mars cruise customers in the last year.", status = UserListMembershipStatus.OPEN, membershipLifeSpan = 365 }; UserListConversionType conversionType = new UserListConversionType { name = userList.name }; userList.conversionTypes = new UserListConversionType[] { conversionType }; // Optional: Set the user list status. userList.status = UserListMembershipStatus.OPEN; // Create the operation. UserListOperation operation = new UserListOperation { operand = userList, @operator = Operator.ADD }; try { // Add the user list. UserListReturnValue retval = userListService.mutate(new UserListOperation[] { operation }); UserList newUserList = retval.value[0]; Console.WriteLine("User list with name '{0}' and id '{1}' was added.", newUserList.name, newUserList.id); List <string> conversionIds = new List <string>(); Array.ForEach(userList.conversionTypes, delegate(UserListConversionType item) { conversionIds.Add(item.id.ToString()); }); // Create the selector. Selector selector = new Selector() { fields = new string[] { ConversionTracker.Fields.Id, ConversionTracker.Fields.GoogleGlobalSiteTag, ConversionTracker.Fields.GoogleEventSnippet }, predicates = new Predicate[] { Predicate.In(ConversionTracker.Fields.Id, conversionIds.ToArray()) } }; // Get all conversion trackers. ConversionTrackerPage page = conversionTrackerService.get(selector); if (page != null && page.entries != null) { foreach (ConversionTracker tracker in page.entries) { Console.WriteLine( "Google global site tag:\n{0}\nGoogle event snippet:\n{1}", tracker.googleGlobalSiteTag, tracker.googleGlobalSiteTag); } } } catch (Exception e) { throw new System.ApplicationException( "Failed to add user lists (a.k.a. audiences).", e); } } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="baseCampaignId">Id of the campaign to use as base of the /// draft.</param> public void Run(AdWordsUser user, long baseCampaignId) { using (DraftService draftService = (DraftService)user.GetService(AdWordsService.v201806.DraftService)) using (CampaignCriterionService campaignCriterionService = (CampaignCriterionService)user.GetService(AdWordsService.v201806 .CampaignCriterionService)) { Draft draft = new Draft() { baseCampaignId = baseCampaignId, draftName = "Test Draft #" + ExampleUtilities.GetRandomString() }; DraftOperation draftOperation = new DraftOperation() { @operator = Operator.ADD, operand = draft }; try { draft = draftService.mutate(new DraftOperation[] { draftOperation }).value[0]; Console.WriteLine( "Draft with ID {0}, base campaign ID {1} and draft campaign ID " + "{2} created.", draft.draftId, draft.baseCampaignId, draft.draftCampaignId); // Once the draft is created, you can modify the draft campaign as if it // were a real campaign. For example, you may add criteria, adjust bids, // or even include additional ads. Adding a criterion is shown here. Language language = new Language() { id = 1003L // Spanish }; // Make sure to use the draftCampaignId when modifying the virtual draft // campaign. CampaignCriterion campaignCriterion = new CampaignCriterion() { campaignId = draft.draftCampaignId, criterion = language }; CampaignCriterionOperation criterionOperation = new CampaignCriterionOperation() { @operator = Operator.ADD, operand = campaignCriterion }; campaignCriterion = campaignCriterionService.mutate( new CampaignCriterionOperation[] { criterionOperation }).value[0]; Console.WriteLine( "Draft updated to include criteria in draft campaign ID {0}.", draft.draftCampaignId); } catch (Exception e) { throw new System.ApplicationException( "Failed to create draft campaign and add " + "criteria.", e); } } }
/// <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.V6.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> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { using (ConversionTrackerService conversionTrackerService = (ConversionTrackerService)user.GetService(AdWordsService.v201802. ConversionTrackerService)) { List <ConversionTracker> conversionTrackers = new List <ConversionTracker>(); // Create an Adwords conversion tracker. AdWordsConversionTracker adWordsConversionTracker = new AdWordsConversionTracker { name = "Earth to Mars Cruises Conversion #" + ExampleUtilities.GetRandomString(), category = ConversionTrackerCategory.DEFAULT, // Set optional fields. status = ConversionTrackerStatus.ENABLED, viewthroughLookbackWindow = 15, defaultRevenueValue = 23.41, alwaysUseDefaultRevenueValue = true }; conversionTrackers.Add(adWordsConversionTracker); // Create an upload conversion for offline conversion imports. UploadConversion uploadConversion = new UploadConversion { // Set an appropriate category. This field is optional, and will be set to // DEFAULT if not mentioned. category = ConversionTrackerCategory.LEAD, name = "Upload Conversion #" + ExampleUtilities.GetRandomString(), viewthroughLookbackWindow = 30, ctcLookbackWindow = 90, // Optional: Set the default currency code to use for conversions // that do not specify a conversion currency. This must be an ISO 4217 // 3-character currency code such as "EUR" or "USD". // If this field is not set on this UploadConversion, AdWords will use // the account's currency. defaultRevenueCurrencyCode = "EUR", // Optional: Set the default revenue value to use for conversions // that do not specify a conversion value. Note that this value // should NOT be in micros. defaultRevenueValue = 2.50 }; // Optional: To upload fractional conversion credits, mark the upload conversion // as externally attributed. See // https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions // to learn more about importing externally attributed conversions. // uploadConversion.isExternallyAttributed = true; conversionTrackers.Add(uploadConversion); try { // Create operations. List <ConversionTrackerOperation> operations = new List <ConversionTrackerOperation>(); foreach (ConversionTracker conversionTracker in conversionTrackers) { operations.Add(new ConversionTrackerOperation() { @operator = Operator.ADD, operand = conversionTracker }); } // Add conversion tracker. ConversionTrackerReturnValue retval = conversionTrackerService.mutate( operations.ToArray()); // Display the results. if (retval != null && retval.value != null) { foreach (ConversionTracker conversionTracker in retval.value) { Console.WriteLine("Conversion with ID {0}, name '{1}', status '{2}' and " + "category '{3}' was added.", conversionTracker.id, conversionTracker.name, conversionTracker.status, conversionTracker.category); if (conversionTracker is AdWordsConversionTracker) { AdWordsConversionTracker newAdWordsConversionTracker = (AdWordsConversionTracker)conversionTracker; Console.WriteLine("Google global site tag:\n{0}\nGoogle event snippet:\n{1}", newAdWordsConversionTracker.googleGlobalSiteTag, newAdWordsConversionTracker.googleEventSnippet ); } } } else { Console.WriteLine("No conversion trackers were added."); } } catch (Exception e) { throw new System.ApplicationException("Failed to add conversion trackers.", e); } } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to which ads are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService)user.GetService(AdWordsService.v201406.AdGroupAdService); // Create standard third party redirect ad. ThirdPartyRedirectAd standardAd = new ThirdPartyRedirectAd(); standardAd.name = String.Format("Example third party ad #{0}", ExampleUtilities.GetRandomString()); standardAd.url = "http://www.example.com"; standardAd.dimensions = new Dimensions(); standardAd.dimensions.height = 250; standardAd.dimensions.width = 300; standardAd.snippet = "<img src=\"http://goo.gl/HJM3L\"/>"; // DoubleClick Rich Media Expandable format ID. standardAd.certifiedVendorFormatId = 232; standardAd.isCookieTargeted = false; standardAd.isUserInterestTargeted = false; standardAd.isTagged = false; standardAd.richMediaAdType = RichMediaAdRichMediaAdType.STANDARD; // Expandable Ad properties. standardAd.expandingDirections = new ThirdPartyRedirectAdExpandingDirection[] { ThirdPartyRedirectAdExpandingDirection.EXPANDING_UP, ThirdPartyRedirectAdExpandingDirection.EXPANDING_DOWN }; standardAd.adAttributes = new RichMediaAdAdAttribute[] { RichMediaAdAdAttribute.ROLL_OVER_TO_EXPAND }; // Create in-stream third party redirect ad. ThirdPartyRedirectAd inStreamAd = new ThirdPartyRedirectAd(); inStreamAd.name = String.Format("Example third party ad #{0}", ExampleUtilities.GetRandomString()); inStreamAd.url = "http://www.example.com"; // Set the duration to 15 secs. inStreamAd.adDuration = 15000; inStreamAd.sourceUrl = "http://ad.doubleclick.net/pfadx/N270.126913.6102203221521/B3876671.21;dcadv=2215309;sz=0x0;ord=%5btimestamp%5d;dcmt=text/xml"; inStreamAd.certifiedVendorFormatId = 303; inStreamAd.richMediaAdType = RichMediaAdRichMediaAdType.IN_STREAM_VIDEO; List <AdGroupAdOperation> operations = new List <AdGroupAdOperation>(); foreach (ThirdPartyRedirectAd redirectAd in new ThirdPartyRedirectAd[] { standardAd, inStreamAd }) { // Set the ad group id. AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.adGroupId = adGroupId; adGroupAd.ad = redirectAd; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.@operator = Operator.ADD; operation.operand = adGroupAd; operations.Add(operation); } AdGroupAdReturnValue retVal = null; try { // Create the ads retVal = service.mutate(operations.ToArray()); if (retVal != null && retVal.value != null) { // If you are adding multiple type of Ads, then you may need to check // for // // if (adGroupAd.ad is ThirdPartyRedirectAd) { ... } // // to identify the ad type. foreach (AdGroupAd newAdGroupAd in retVal.value) { Console.WriteLine("New third party redirect ad with url = \"{0}\" and id = {1}" + " was created.", ((ThirdPartyRedirectAd)newAdGroupAd.ad).url, newAdGroupAd.ad.id); } } else { Console.WriteLine("No third party redirect ads were created."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to create third party redirect ads.", ex); } }
/// <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> // [START AddShoppingSmartAd_3] private string AddSmartShoppingCampaign(GoogleAdsClient client, long customerId, string budgetResourceName, long merchantCenterAccountId) { // Get the CampaignService. CampaignServiceClient campaignService = client.GetService(Services.V6.CampaignService); // Configures the shopping settings. ShoppingSetting shoppingSetting = new ShoppingSetting() { // Sets the sales country of products to include in the campaign. SalesCountry = "US", MerchantId = merchantCenterAccountId, }; // [START AddShoppingSmartAd] // 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 }; // [END AddShoppingSmartAd] // 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> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to which ads are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService)user.GetService(AdWordsService.v201402.AdGroupAdService); // Create the third party redirect ad that violates a policy. ThirdPartyRedirectAd redirectAd = new ThirdPartyRedirectAd(); redirectAd.name = "Policy violation demo ad " + ExampleUtilities.GetRandomString(); redirectAd.url = "gopher://gopher.google.com"; redirectAd.dimensions = new Dimensions(); redirectAd.dimensions.width = 300; redirectAd.dimensions.height = 250; redirectAd.snippet = "<img src=\"https://sandbox.google.com/sandboximages/image.jpg\"/>"; redirectAd.impressionBeaconUrl = "http://www.examples.com/beacon1"; redirectAd.certifiedVendorFormatId = 119; redirectAd.isCookieTargeted = false; redirectAd.isUserInterestTargeted = false; redirectAd.isTagged = false; AdGroupAd redirectAdGroupAd = new AdGroupAd(); redirectAdGroupAd.adGroupId = adGroupId; redirectAdGroupAd.ad = redirectAd; // Create the operations. AdGroupAdOperation redirectAdOperation = new AdGroupAdOperation(); redirectAdOperation.@operator = Operator.ADD; redirectAdOperation.operand = redirectAdGroupAd; try { AdGroupAdReturnValue retVal = null; // Setup two arrays, one to hold the list of all operations to be // validated, and another to hold the list of operations that cannot be // fixed after validation. List <AdGroupAdOperation> allOperations = new List <AdGroupAdOperation>(); List <AdGroupAdOperation> operationsToBeRemoved = new List <AdGroupAdOperation>(); allOperations.Add(redirectAdOperation); try { // Validate the operations. service.RequestHeader.validateOnly = true; retVal = service.mutate(allOperations.ToArray()); } catch (AdWordsApiException ex) { ApiException innerException = ex.ApiException as ApiException; if (innerException == null) { throw new Exception("Failed to retrieve ApiError. See inner exception for more " + "details.", ex); } // Examine each ApiError received from the server. foreach (ApiError apiError in innerException.errors) { int index = ErrorUtilities.GetOperationIndex(apiError.fieldPath); if (index == -1) { // This API error is not associated with an operand, so we cannot // recover from this error by removing one or more operations. // Rethrow the exception for manual inspection. throw; } // Handle policy violation errors. if (apiError is PolicyViolationError) { PolicyViolationError policyError = (PolicyViolationError)apiError; if (policyError.isExemptable) { // If the policy violation error is exemptable, add an exemption // request. List <ExemptionRequest> exemptionRequests = new List <ExemptionRequest>(); if (allOperations[index].exemptionRequests != null) { exemptionRequests.AddRange(allOperations[index].exemptionRequests); } ExemptionRequest exemptionRequest = new ExemptionRequest(); exemptionRequest.key = policyError.key; exemptionRequests.Add(exemptionRequest); allOperations[index].exemptionRequests = exemptionRequests.ToArray(); } else { // Policy violation error is not exemptable, remove this // operation from the list of operations. operationsToBeRemoved.Add(allOperations[index]); } } else { // This is not a policy violation error, remove this operation // from the list of operations. operationsToBeRemoved.Add(allOperations[index]); } } // Remove all operations that aren't exemptable. foreach (AdGroupAdOperation operation in operationsToBeRemoved) { allOperations.Remove(operation); } } if (allOperations.Count > 0) { // Perform the operations exemptible of a policy violation. service.RequestHeader.validateOnly = false; retVal = service.mutate(allOperations.ToArray()); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { foreach (AdGroupAd newAdGroupAd in retVal.value) { Console.WriteLine("New ad with id = \"{0}\" and displayUrl = \"{1}\" was created.", newAdGroupAd.ad.id, newAdGroupAd.ad.displayUrl); } } else { Console.WriteLine("No ads were created."); } } else { Console.WriteLine("There are no ads to create after policy violation checks."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to create ads.", ex); } }
/// <summary> /// Create a feed that will sync to the Google My Business account /// specified by gmbEmailAddress. /// </summary> /// <param name="user">The user.</param> /// <param name="gmbEmailAddress">The GMB email address.</param> /// <param name="gmbAccessToken">The GMB access token.</param> /// <param name="businessAccountIdentifier">The GMB account identifier.</param> /// <returns>The newly created GMB feed.</returns> private static Feed CreateGmbFeed(AdWordsUser user, string gmbEmailAddress, string gmbAccessToken, string businessAccountIdentifier) { using (FeedService feedService = (FeedService)user.GetService( AdWordsService.v201802.FeedService)) { // Create a feed that will sync to the Google My Business account // specified by gmbEmailAddress. Do not add FeedAttributes to this object, // as AdWords will add them automatically because this will be a // system generated feed. Feed gmbFeed = new Feed { name = string.Format("Google My Business feed #{0}", ExampleUtilities.GetRandomString()) }; PlacesLocationFeedData feedData = new PlacesLocationFeedData { emailAddress = gmbEmailAddress, businessAccountIdentifier = businessAccountIdentifier, // Optional: specify labels to filter Google My Business listings. If // specified, only listings that have any of the labels set are // synchronized into FeedItems. labelFilters = new string[] { "Stores in New York City" } }; OAuthInfo oAuthInfo = new OAuthInfo { httpMethod = "GET", // Permissions for the AdWords API scope will also cover GMB. httpRequestUrl = user.Config.GetDefaultOAuth2Scope(), httpAuthorizationHeader = string.Format("Bearer {0}", gmbAccessToken) }; feedData.oAuthInfo = oAuthInfo; gmbFeed.systemFeedGenerationData = feedData; // Since this feed's feed items will be managed by AdWords, // you must set its origin to ADWORDS. gmbFeed.origin = FeedOrigin.ADWORDS; // Create an operation to add the feed. FeedOperation feedOperation = new FeedOperation { operand = gmbFeed, @operator = Operator.ADD }; try { // Add the feed. Since it is a system generated feed, AdWords will // automatically: // 1. Set up the FeedAttributes on the feed. // 2. Set up a FeedMapping that associates the FeedAttributes of the // feed with the placeholder fields of the LOCATION placeholder // type. FeedReturnValue addFeedResult = feedService.mutate( new FeedOperation[] { feedOperation }); Feed addedFeed = addFeedResult.value[0]; Console.WriteLine("Added GMB feed with ID {0}", addedFeed.id); return(addedFeed); } catch (Exception e) { throw new System.ApplicationException("Failed to create GMB feed.", e); } } }
/// <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 ads are added.</param> public void Run(GoogleAdsClient client, long customerId, long adGroupId) { // Get the AdGroupAdService. AdGroupAdServiceClient adGroupAdService = client.GetService(Services.V3.AdGroupAdService); // Create the ad. Ad ad = new Ad() { ResponsiveSearchAd = new ResponsiveSearchAdInfo() { Headlines = { // Sets a pinning to always choose this asset for HEADLINE_1. Pinning is // optional; if no pinning is set, then headlines and descriptions will be // rotated and the ones that perform best will be used more often. new AdTextAsset() { Text = "Cruise to Mars #" + ExampleUtilities.GetRandomString(), PinnedField = ServedAssetFieldType.Headline1 }, new AdTextAsset() { Text = "Best Space Cruise Line" }, new AdTextAsset() { Text = "Experience the Stars" }, new AdTextAsset() { Text = "Buy your tickets now" }, new AdTextAsset() { Text = "Visit the Red Planet" }, }, Path1 = "all-inclusive", Path2 = "deals" }, FinalUrls = { "http://www.example.com" } }; // Builds the final ad group ad representation. AdGroupAd adGroupAd = new AdGroupAd() { AdGroup = ResourceNames.AdGroup(customerId, adGroupId), Status = AdGroupAdStatusEnum.Types.AdGroupAdStatus.Paused, Ad = ad }; // Creates the operation. AdGroupAdOperation operation = new AdGroupAdOperation() { Create = adGroupAd }; try { MutateAdGroupAdsResponse response = adGroupAdService.MutateAdGroupAds(customerId.ToString(), new[] { operation }); foreach (MutateAdGroupAdResult result in response.Results) { Console.WriteLine($"Responsive search ad created with resource name:" + $" '{result.ResourceName}'."); } } 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="user">The AdWords user.</param> public void Run(AdWordsUser user) { // [START prepareUAC] MOE:strip_line // Get the CampaignService. CampaignService campaignService = (CampaignService)user.GetService(AdWordsService.v201705.CampaignService); // Create the campaign. Campaign campaign = new Campaign(); campaign.name = "Interplanetary Cruise App #" + ExampleUtilities.GetRandomString(); // 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 advertising channel and subchannel types for universal app campaigns. campaign.advertisingChannelType = AdvertisingChannelType.MULTI_CHANNEL; campaign.advertisingChannelSubType = AdvertisingChannelSubType.UNIVERSAL_APP_CAMPAIGN; // Set the campaign's bidding strategy. Universal app campaigns // only support TARGET_CPA bidding strategy. BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration(); biddingConfig.biddingStrategyType = BiddingStrategyType.TARGET_CPA; // Set the target CPA to $1 / app install. TargetCpaBiddingScheme biddingScheme = new TargetCpaBiddingScheme(); biddingScheme.targetCpa = new Money(); biddingScheme.targetCpa.microAmount = 1000000; biddingConfig.biddingScheme = biddingScheme; campaign.biddingStrategyConfiguration = biddingConfig; // Set the campaign's budget. campaign.budget = new Budget(); campaign.budget.budgetId = CreateBudget(user).budgetId; // 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"); // [END prepareUAC] MOE:strip_line // [START setUACAssets] MOE:strip_line // Set the campaign's assets and ad text ideas. These values will be used to // generate ads. UniversalAppCampaignSetting universalAppSetting = new UniversalAppCampaignSetting(); universalAppSetting.appId = "com.labpixies.colordrips"; universalAppSetting.description1 = "A cool puzzle game"; universalAppSetting.description2 = "Remove connected blocks"; universalAppSetting.description3 = "3 difficulty levels"; universalAppSetting.description4 = "4 colorful fun skins"; // Optional: You can set up to 10 image assets for your campaign. // See UploadImage.cs for an example on how to upload images. // // universalAppSetting.imageMediaIds = new long[] { INSERT_IMAGE_MEDIA_ID_HERE }; // [END setUACAssets] MOE:strip_line // [START optimizeUAC] MOE:strip_line // Optimize this campaign for getting new users for your app. universalAppSetting.universalAppBiddingStrategyGoalType = UniversalAppBiddingStrategyGoalType.OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME; // Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal // type, then also specify your in-app conversion types so AdWords can // focus your campaign on people who are most likely to complete the // corresponding in-app actions. // Conversion type IDs can be retrieved using ConversionTrackerService.get. // // campaign.selectiveOptimization = new SelectiveOptimization(); // campaign.selectiveOptimization.conversionTypeIds = // new long[] { INSERT_CONVERSION_TYPE_ID_1_HERE, INSERT_CONVERSION_TYPE_ID_2_HERE }; // Optional: Set the campaign settings for Advanced location options. GeoTargetTypeSetting geoSetting = new GeoTargetTypeSetting(); geoSetting.positiveGeoTargetType = GeoTargetTypeSettingPositiveGeoTargetType.LOCATION_OF_PRESENCE; geoSetting.negativeGeoTargetType = GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE; campaign.settings = new Setting[] { universalAppSetting, geoSetting }; // [END optimizeUAC] MOE:strip_line // [START createUAC] MOE:strip_line // Create the operation. CampaignOperation operation = new CampaignOperation(); operation.@operator = Operator.ADD; operation.operand = campaign; try { // Add the campaign. CampaignReturnValue retVal = campaignService.mutate(new CampaignOperation[] { operation }); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { foreach (Campaign newCampaign in retVal.value) { Console.WriteLine("Universal app campaign with name = '{0}' and id = '{1}' was added.", newCampaign.name, newCampaign.id); // Optional: Set the campaign's location and language targeting. No other targeting // criteria can be used for universal app campaigns. SetCampaignTargetingCriteria(user, newCampaign); } } else { Console.WriteLine("No universal app campaigns were added."); } } catch (Exception e) { throw new System.ApplicationException("Failed to add universal app campaigns.", e); } // [END createUAC] MOE:strip_line }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { using (CampaignService campaignService = (CampaignService)user.GetService(AdWordsService.v201806.CampaignService)) { Budget budget = CreateBudget(user); List <CampaignOperation> operations = new List <CampaignOperation>(); for (int i = 0; i < NUM_ITEMS; i++) { // Create the campaign. Campaign campaign = new Campaign { name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(), 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. status = CampaignStatus.PAUSED }; BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration { biddingStrategyType = BiddingStrategyType.MANUAL_CPC }; campaign.biddingStrategyConfiguration = biddingConfig; campaign.budget = new Budget { budgetId = budget.budgetId }; // Set the campaign network options. campaign.networkSetting = new NetworkSetting { targetGoogleSearch = true, targetSearchNetwork = true, targetContentNetwork = false, targetPartnerSearchNetwork = false }; // Set the campaign settings for Advanced location options. GeoTargetTypeSetting geoSetting = new GeoTargetTypeSetting { positiveGeoTargetType = GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE, negativeGeoTargetType = GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE }; campaign.settings = new Setting[] { geoSetting }; // 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"); // Optional: Set the frequency cap. FrequencyCap frequencyCap = new FrequencyCap { impressions = 5, level = Level.ADGROUP, timeUnit = TimeUnit.DAY }; campaign.frequencyCap = frequencyCap; // Create the operation. CampaignOperation operation = new CampaignOperation { @operator = Operator.ADD, operand = campaign }; operations.Add(operation); } try { // Add the campaign. CampaignReturnValue retVal = campaignService.mutate(operations.ToArray()); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { foreach (Campaign newCampaign in retVal.value) { Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was added.", newCampaign.name, newCampaign.id); } } else { Console.WriteLine("No campaigns were added."); } } catch (Exception e) { throw new System.ApplicationException("Failed to add campaigns.", e); } } }
/// <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.V4.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> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">Id of the campaign to which ad groups are /// added.</param> public void Run(AdWordsUser user, long campaignId) { using (AdGroupService adGroupService = (AdGroupService)user.GetService(AdWordsService.v201702.AdGroupService)) { List <AdGroupOperation> operations = new List <AdGroupOperation>(); for (int i = 0; i < NUM_ITEMS; i++) { // Create the ad group. AdGroup adGroup = new AdGroup(); adGroup.name = string.Format("Earth to Mars Cruises #{0}", ExampleUtilities.GetRandomString()); adGroup.status = AdGroupStatus.ENABLED; adGroup.campaignId = campaignId; // Set the ad group bids. BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration(); CpcBid cpcBid = new CpcBid(); cpcBid.bid = new Money(); cpcBid.bid.microAmount = 10000000; biddingConfig.bids = new Bids[] { cpcBid }; adGroup.biddingStrategyConfiguration = biddingConfig; // Optional: Set targeting restrictions. // Depending on the criterionTypeGroup value, most TargetingSettingDetail // only affect Display campaigns. However, the USER_INTEREST_AND_LIST value // works for RLSA campaigns - Search campaigns targeting using a // remarketing list. TargetingSetting targetingSetting = new TargetingSetting(); // Restricting to serve ads that match your ad group placements. // This is equivalent to choosing "Target and bid" in the UI. TargetingSettingDetail placementDetail = new TargetingSettingDetail(); placementDetail.criterionTypeGroup = CriterionTypeGroup.PLACEMENT; placementDetail.targetAll = false; // Using your ad group verticals only for bidding. This is equivalent // to choosing "Bid only" in the UI. TargetingSettingDetail verticalDetail = new TargetingSettingDetail(); verticalDetail.criterionTypeGroup = CriterionTypeGroup.VERTICAL; verticalDetail.targetAll = true; targetingSetting.details = new TargetingSettingDetail[] { placementDetail, verticalDetail }; adGroup.settings = new Setting[] { targetingSetting }; // Create the operation. AdGroupOperation operation = new AdGroupOperation(); operation.@operator = Operator.ADD; operation.operand = adGroup; operations.Add(operation); } try { // Create the ad group. AdGroupReturnValue retVal = adGroupService.mutate(operations.ToArray()); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { foreach (AdGroup newAdGroup in retVal.value) { Console.WriteLine("Ad group with id = '{0}' and name = '{1}' was created.", newAdGroup.id, newAdGroup.name); } } else { Console.WriteLine("No ad groups were created."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create ad groups.", e); } } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="baseCampaignId">Id of the campaign to use as base of the /// trial.</param> /// <param name="draftId">Id of the draft.</param> public void Run(AdWordsUser user, long draftId, long baseCampaignId) { // Get the TrialService. TrialService trialService = (TrialService)user.GetService( AdWordsService.v201605.TrialService); // [START createTrial] MOE:strip_line Trial trial = new Trial() { draftId = draftId, baseCampaignId = baseCampaignId, name = "Test Trial #" + ExampleUtilities.GetRandomString(), trafficSplitPercent = 50 }; TrialOperation trialOperation = new TrialOperation() { @operator = Operator.ADD, operand = trial }; // [END createTrial] MOE:strip_line try { long trialId = trialService.mutate(new TrialOperation[] { trialOperation }).value[0].id; // [START pollForTrialCompletion] MOE:strip_line // Since creating a trial is asynchronous, we have to poll it to wait // for it to finish. Selector trialSelector = new Selector() { fields = new string[] { Trial.Fields.Id, Trial.Fields.Status, Trial.Fields.BaseCampaignId, Trial.Fields.TrialCampaignId }, predicates = new Predicate[] { Predicate.Equals(Trial.Fields.Id, trialId) } }; trial = null; bool isPending = true; int pollAttempts = 0; do { int sleepMillis = (int)Math.Pow(2, pollAttempts) * POLL_INTERVAL_SECONDS_BASE * 1000; Console.WriteLine("Sleeping {0} millis...", sleepMillis); Thread.Sleep(sleepMillis); trial = trialService.get(trialSelector).entries[0]; Console.WriteLine("Trial ID {0} has status '{1}'.", trial.id, trial.status); pollAttempts++; isPending = (trial.status == TrialStatus.CREATING); } while (isPending && pollAttempts <= MAX_RETRIES); if (trial.status == TrialStatus.ACTIVE) { // The trial creation was successful. Console.WriteLine("Trial created with ID {0} and trial campaign ID {1}.", trial.id, trial.trialCampaignId); // [START retrieveTrialErrors] MOE:strip_line } else if (trial.status == TrialStatus.CREATION_FAILED) { // The trial creation failed, and errors can be fetched from the // TrialAsyncErrorService. Selector errorsSelector = new Selector() { fields = new string[] { TrialAsyncError.Fields.TrialId, TrialAsyncError.Fields.AsyncError }, predicates = new Predicate[] { Predicate.Equals(TrialAsyncError.Fields.TrialId, trial.id) } }; TrialAsyncErrorService trialAsyncErrorService = (TrialAsyncErrorService)user.GetService( AdWordsService.v201605.TrialAsyncErrorService); TrialAsyncErrorPage trialAsyncErrorPage = trialAsyncErrorService.get(errorsSelector); if (trialAsyncErrorPage.entries == null || trialAsyncErrorPage.entries.Length == 0) { Console.WriteLine("Could not retrieve errors for trial {0}.", trial.id); } else { Console.WriteLine("Could not create trial ID {0} for draft ID {1} due to the " + "following errors:", trial.id, draftId); int i = 0; foreach (TrialAsyncError error in trialAsyncErrorPage.entries) { ApiError asyncError = error.asyncError; Console.WriteLine("Error #{0}: errorType='{1}', errorString='{2}', trigger='{3}'," + " fieldPath='{4}'", i++, asyncError.ApiErrorType, asyncError.errorString, asyncError.trigger, asyncError.fieldPath); } } // [END retrieveTrialErrors] MOE:strip_line } else { // Most likely, the trial is still being created. You can continue // polling, but we have limited the number of attempts in the // example. Console.WriteLine("Timed out waiting to create trial from draft ID {0} with " + "base campaign ID {1}.", draftId, baseCampaignId); } // [END pollForTrialCompletion] MOE:strip_line } catch (Exception e) { throw new System.ApplicationException("Failed to create trial from draft.", e); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { // Get the UserListService. AdwordsUserListService userListService = (AdwordsUserListService)user.GetService( AdWordsService.v201705.AdwordsUserListService); // Create a user list. CrmBasedUserList userList = new CrmBasedUserList() { name = "Customer relationship management list #" + ExampleUtilities.GetRandomString(), description = "A list of customers that originated from email " + "addresses", // CRM Userlist has a maximum membership lifespan of 180 days. See // https://support.google.com/adwords/answer/6276125 for details. membershipLifeSpan = 180L, }; // Create operation. UserListOperation operation = new UserListOperation() { operand = userList, @operator = Operator.ADD }; try { // Add user list. UserListReturnValue result = userListService.mutate( new UserListOperation[] { operation }); Console.WriteLine("Created new user list with name = '{0}' and id = " + "'{1}'.", result.value[0].name, result.value[0].id); // Get user list ID. long userListId = result.value[0].id; // Prepare the emails for upload. List <Member> memberList = new List <Member>(); // Hash normalized email addresses based on SHA-256 hashing algorithm. String[] emailHashes = new String[EMAILS.Length]; for (int i = 0; i < EMAILS.Length; i++) { Member member = new Member(); member.hashedEmail = ToSha256String(digest, ToNormalizedEmail(EMAILS[i])); // Adding address info is currently available on a whitelist-only basis. This // code demonstrates how to do it, but if you are not on the whitelist, you // will need to remove this block for the example to run. AddressInfo addressInfo = new AddressInfo(); addressInfo.hashedFirstName = ToSha256String(digest, FIRST_NAME); addressInfo.hashedLastName = ToSha256String(digest, LAST_NAME); addressInfo.zipCode = ZIP_CODE; addressInfo.countryCode = COUNTRY_CODE; member.addressInfo = addressInfo; memberList.Add(member); } ; // Create operation to add members to the user list based on email // addresses. MutateMembersOperation mutateMembersOperation = new MutateMembersOperation() { operand = new MutateMembersOperand() { userListId = userListId, membersList = memberList.ToArray() }, @operator = Operator.ADD }; // Add members to the user list based on email addresses. MutateMembersReturnValue mutateMembersResult = userListService.mutateMembers( new MutateMembersOperation[] { mutateMembersOperation }); // Display results. // Reminder: it may take several hours for the list to be populated // with members. foreach (UserList userListResult in mutateMembersResult.userLists) { Console.WriteLine("Email addresses were added to user list with " + "name '{0}' and id '{1}'.", userListResult.name, userListResult.id); } userListService.Close(); } catch (Exception e) { throw new System.ApplicationException("Failed to add user lists " + "(a.k.a. audiences) and upload email addresses.", e); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads API client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <param name="feedId">The Feed ID for creating the feed item set.</param> public void Run(GoogleAdsClient client, long customerId, long feedId) { // Get the FeedItemSetService. FeedItemSetServiceClient feedItemService = client.GetService( Services.V10.FeedItemSetService); FeedItemSet feedItemSet = new FeedItemSet() { Feed = ResourceNames.Feed(customerId, feedId), DisplayName = "Feed Item Set #" + ExampleUtilities.GetRandomString(), }; // A feed item set can be created as a dynamic set by setting an optional filter // field below. If your feed is a location extension, uncomment the code that calls // DynamicLocationSetFilter. If instead your feed is an affiliate extension, // uncomment the code that sets the DynamicAffiliateLocationSetFilter instead. // 1) Location extension. //feedItemSet.DynamicLocationSetFilter = new DynamicLocationSetFilter() //{ // // Dynamic location sets support filtering locations based on business name // // and/or labels. If both are specified, the feed item set will only include // // locations that satisfy both types of filters. // BusinessNameFilter = new BusinessNameFilter() // { // BusinessName = "INSERT_YOUR_BUSINESS_NAME_HERE", // FilterType = FeedItemSetStringFilterType.Exact, // }, // // Adds a filter by feed item label resource name. If multiple labels are // // specified, the feed item set will only include feed items with all of the // // specified labels. // Labels = { "INSERT_BUSINESS_LABEL_HERE" } //}; // 2) Affiliate extension. //feedItemSet.DynamicAffiliateLocationSetFilter = new DynamicAffiliateLocationSetFilter() //{ // ChainIds = { long.Parse("INSERT_CHAIN_ID_HERE") } //}; // Constructs an operation that will create a new feed item set. FeedItemSetOperation operation = new FeedItemSetOperation() { Create = feedItemSet }; try { // Issues a mutate request to add the feed item set on the server. MutateFeedItemSetsResponse response = feedItemService.MutateFeedItemSets(customerId.ToString(), new[] { operation }); // Prints the resource names of the added feed item sets. foreach (MutateFeedItemSetResult addedFeedItemSet in response.Results) { Console.WriteLine("Created a feed item set with resource name " + $"'{addedFeedItemSet.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 a price asset. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> /// <returns>the resource name of the newly created price asset.</returns> private string CreatePriceAsset(GoogleAdsClient client, long customerId) { PriceAsset priceAsset = new PriceAsset { Type = PriceExtensionType.Services, // Price qualifier is optional. PriceQualifier = PriceExtensionPriceQualifier.From, LanguageCode = "en", PriceOfferings = { CreatePriceOffering( "Scrubs", "Body Scrub, Salt Scrub", "http://www.example.com/scrubs", "http://m.example.com/scrubs", 60000000, // 60 USD "USD", PriceExtensionPriceUnit.PerHour ), CreatePriceOffering( "Hair Cuts", "Once a month", "http://www.example.com/haircuts", "http://m.example.com/haircuts", 250000000, // 60 USD "USD", PriceExtensionPriceUnit.PerMonth ), CreatePriceOffering( "Skin Care Package", "Four times a month", "http://www.example.com/skincarepackage", null, 250000000, // 250 USD "USD", PriceExtensionPriceUnit.PerMonth ), }, }; Asset asset = new Asset { Name = "Price Asset #" + ExampleUtilities.GetRandomString(), TrackingUrlTemplate = "http://tracker.example.com/?u={lpurl}", PriceAsset = priceAsset, }; AssetOperation operation = new AssetOperation { Create = asset, }; AssetServiceClient assetClient = client.GetService(Services.V10.AssetService); MutateAssetsResponse response = assetClient.MutateAssets(customerId.ToString(), new[] { operation }); string resourceName = response.Results[0].ResourceName; Console.WriteLine($"Created price asset with resource name '{resourceName}'."); return(resourceName); }
/// <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="adGroupId">ID of the ad group to which ads are added.</param> public void Run(GoogleAdsClient client, long customerId, long adGroupId) { // Get the AdGroupAdServiceClient. AdGroupAdServiceClient adGroupAdService = client.GetService( Services.V5.AdGroupAdService); string adGroupResourceName = ResourceNames.AdGroup(customerId, adGroupId); // Creates an expanded text ad info object. ExpandedTextAdInfo expandedTextAdInfo = new ExpandedTextAdInfo() { HeadlinePart1 = $"Cruise to Mars #{ExampleUtilities.GetShortRandomString()}", HeadlinePart2 = "Best Space Cruise Line", // Intentionally use an ad text that violates policy -- having too many exclamation // marks. Description = "Buy your tickets now!!!!!!!" }; // Creates an ad group ad to hold the above ad. AdGroupAd adGroupAd = new AdGroupAd() { AdGroup = adGroupResourceName, // Set the ad group ad to PAUSED to prevent it from immediately serving. // Set to ENABLED once you've added targeting and the ad are ready to serve. Status = AdGroupAdStatus.Paused, // Sets the expanded text ad info on an Ad. Ad = new Ad() { ExpandedTextAd = expandedTextAdInfo, FinalUrls = { "http://www.example.com" } } }; // Creates an ad group ad operation. AdGroupAdOperation operation = new AdGroupAdOperation() { Create = adGroupAd }; try { try { // Try sending a mutate request to add the ad group ad. adGroupAdService.MutateAdGroupAds(customerId.ToString(), new [] { operation }); } catch (GoogleAdsException ex) { // The request will always fail because of the policy violation in the // description of the ad. var ignorablePolicyTopics = FetchIgnorablePolicyTopics(ex); // Try sending exemption requests for creating an expanded text ad. RequestExemption(customerId, adGroupAdService, operation, ignorablePolicyTopics); } } 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="user">The AdWords user.</param> public void Run(AdWordsUser user) { // Get the BudgetService. BudgetService budgetService = (BudgetService)user.GetService(AdWordsService.v201509.BudgetService); // Get the CampaignService. CampaignService campaignService = (CampaignService)user.GetService(AdWordsService.v201509.CampaignService); // Create the campaign budget. Budget budget = new Budget(); budget.name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString(); budget.period = BudgetBudgetPeriod.DAILY; budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD; budget.amount = new Money(); budget.amount.microAmount = 500000; BudgetOperation budgetOperation = new BudgetOperation(); budgetOperation.@operator = Operator.ADD; budgetOperation.operand = budget; try { BudgetReturnValue budgetRetval = budgetService.mutate( new BudgetOperation[] { budgetOperation }); budget = budgetRetval.value[0]; } catch (Exception e) { throw new System.ApplicationException("Failed to add shared budget.", e); } List <CampaignOperation> operations = new List <CampaignOperation>(); for (int i = 0; i < NUM_ITEMS; i++) { // Create the campaign. Campaign campaign = new Campaign(); campaign.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(); campaign.status = CampaignStatus.PAUSED; campaign.advertisingChannelType = AdvertisingChannelType.SEARCH; BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration(); biddingConfig.biddingStrategyType = BiddingStrategyType.MANUAL_CPC; campaign.biddingStrategyConfiguration = biddingConfig; campaign.budget = new Budget(); campaign.budget.budgetId = budget.budgetId; // Set the campaign network options. campaign.networkSetting = new NetworkSetting(); campaign.networkSetting.targetGoogleSearch = true; campaign.networkSetting.targetSearchNetwork = true; campaign.networkSetting.targetContentNetwork = false; campaign.networkSetting.targetPartnerSearchNetwork = false; // Set the campaign settings for Advanced location options. GeoTargetTypeSetting geoSetting = new GeoTargetTypeSetting(); geoSetting.positiveGeoTargetType = GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE; geoSetting.negativeGeoTargetType = GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE; campaign.settings = new Setting[] { geoSetting }; // 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"); // Optional: Set the campaign ad serving optimization status. campaign.adServingOptimizationStatus = AdServingOptimizationStatus.ROTATE; // Optional: Set the frequency cap. FrequencyCap frequencyCap = new FrequencyCap(); frequencyCap.impressions = 5; frequencyCap.level = Level.ADGROUP; frequencyCap.timeUnit = TimeUnit.DAY; campaign.frequencyCap = frequencyCap; // Create the operation. CampaignOperation operation = new CampaignOperation(); operation.@operator = Operator.ADD; operation.operand = campaign; operations.Add(operation); } try { // Add the campaign. CampaignReturnValue retVal = campaignService.mutate(operations.ToArray()); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { foreach (Campaign newCampaign in retVal.value) { Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was added.", newCampaign.name, newCampaign.id); } } else { Console.WriteLine("No campaigns were added."); } } catch (Exception e) { throw new System.ApplicationException("Failed to add campaigns.", e); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">Id of the campaign to which ad groups are /// added.</param> public void Run(AdWordsUser user, long campaignId) { // Get the AdGroupService. AdGroupService adGroupService = (AdGroupService)user.GetService(AdWordsService.v201402.AdGroupService); List <AdGroupOperation> operations = new List <AdGroupOperation>(); for (int i = 0; i < NUM_ITEMS; i++) { // Create the ad group. AdGroup adGroup = new AdGroup(); adGroup.name = string.Format("Earth to Mars Cruises #{0}", ExampleUtilities.GetRandomString()); adGroup.status = AdGroupStatus.ENABLED; adGroup.campaignId = campaignId; // Set the ad group bids. BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration(); CpmBid cpmBid = new CpmBid(); cpmBid.bid = new Money(); cpmBid.bid.microAmount = 10000000; biddingConfig.bids = new Bids[] { cpmBid }; adGroup.biddingStrategyConfiguration = biddingConfig; // Optional: Set targeting restrictions. // These setting only affect serving for the Display Network. TargetingSetting targetingSetting = new TargetingSetting(); TargetingSettingDetail placementDetail = new TargetingSettingDetail(); placementDetail.criterionTypeGroup = CriterionTypeGroup.PLACEMENT; placementDetail.targetAll = true; TargetingSettingDetail verticalDetail = new TargetingSettingDetail(); verticalDetail.criterionTypeGroup = CriterionTypeGroup.VERTICAL; verticalDetail.targetAll = false; targetingSetting.details = new TargetingSettingDetail[] { placementDetail, verticalDetail }; adGroup.settings = new Setting[] { targetingSetting }; // Create the operation. AdGroupOperation operation = new AdGroupOperation(); operation.@operator = Operator.ADD; operation.operand = adGroup; operations.Add(operation); } try { // Create the ad group. AdGroupReturnValue retVal = adGroupService.mutate(operations.ToArray()); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { foreach (AdGroup newAdGroup in retVal.value) { Console.WriteLine("Ad group with id = '{0}' and name = '{1}' was created.", newAdGroup.id, newAdGroup.name); } } else { Console.WriteLine("No ad groups were created."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to create ad groups.", ex); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="businessId">The AdWords Express business id.</param> public void Run(AdWordsUser user, long businessId) { // Get the ExpressBusinessService. ExpressBusinessService businessService = (ExpressBusinessService) user.GetService(AdWordsService.v201502.ExpressBusinessService); // Get the PromotionService PromotionService promotionService = (PromotionService) user.GetService(AdWordsService.v201502.PromotionService); // Get the business for the businessId. We will need its geo point to // create a Proximity criterion for the new Promotion. Selector businessSelector = new Selector(); Predicate predicate = new Predicate(); predicate.field = "Id"; predicate.@operator = PredicateOperator.EQUALS; predicate.values = new string[] { businessId.ToString() }; businessSelector.predicates = new Predicate[] { predicate }; businessSelector.fields = new string[] { "Id", "GeoPoint" }; ExpressBusinessPage businessPage = businessService.get(businessSelector); if (businessPage == null || businessPage.entries == null || businessPage.entries.Length == 0) { Console.WriteLine("No business was found."); return; } // Set the business ID to the service. promotionService.RequestHeader.expressBusinessId = businessId; // First promotion Promotion marsTourPromotion = new Promotion(); Money budget = new Money(); budget.microAmount = 1000000L; marsTourPromotion.name = "Mars Tour Promotion " + ExampleUtilities.GetShortRandomString(); marsTourPromotion.status = PromotionStatus.PAUSED; marsTourPromotion.destinationUrl = "http://www.example.com"; marsTourPromotion.budget = budget; marsTourPromotion.callTrackingEnabled = true; // Criteria // Criterion - Travel Agency product service ProductService productService = new ProductService(); productService.text = "Travel Agency"; // Criterion - English language // The ID can be found in the documentation: // https://developers.google.com/adwords/api/docs/appendix/languagecodes Language language = new Language(); language.id = 1000L; // Criterion - Within 15 miles Proximity proximity = new Proximity(); proximity.geoPoint = businessPage.entries[0].geoPoint; proximity.radiusDistanceUnits = ProximityDistanceUnits.MILES; proximity.radiusInUnits = 15; marsTourPromotion.criteria = new Criterion[] { productService, language, proximity }; // Creative Creative creative = new Creative(); creative.headline = "Standard Mars Trip"; creative.line1 = "Fly coach to Mars"; creative.line2 = "Free in-flight pretzels"; marsTourPromotion.creatives = new Creative[] { creative }; PromotionOperation operation = new PromotionOperation(); operation.@operator = Operator.ADD; operation.operand = marsTourPromotion; try { Promotion[] addedPromotions = promotionService.mutate( new PromotionOperation[] { operation }); Console.WriteLine("Added promotion ID {0} with name {1} to business ID {2}.", addedPromotions[0].id, addedPromotions[0].name, businessId); } catch (Exception ex) { throw new System.ApplicationException("Failed to add promotions.", ex); } }
/// <summary> /// Creates the campaign. /// </summary> /// <param name="user">The Google Ads user.</param> /// <param name="budgetId">The budget ID.</param> /// <returns>The newly created campaign instance.</returns> public aw::Campaign CreateCampaign(AdWordsUser user, long budgetId) { // Get the CampaignService. using (aw::CampaignService campaignService = (aw::CampaignService)user.GetService(AdWordsService.v201809.CampaignService)) { // Create the campaign. aw::Campaign campaign = new aw::Campaign { name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(), advertisingChannelType = aw::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. status = aw::CampaignStatus.PAUSED }; aw::BiddingStrategyConfiguration biddingConfig = new aw::BiddingStrategyConfiguration { biddingStrategyType = aw::BiddingStrategyType.MANUAL_CPC }; campaign.biddingStrategyConfiguration = biddingConfig; campaign.budget = new aw::Budget { budgetId = budgetId }; // Set the campaign network options. campaign.networkSetting = new aw::NetworkSetting { 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. aw::CampaignOperation operation = new aw::CampaignOperation { @operator = aw::Operator.ADD, operand = campaign }; // Add the campaign. aw::CampaignReturnValue retVal = campaignService.mutate( new aw::CampaignOperation[] { operation }); // Retrieve the newly created campaign. aw::Campaign newCampaign = retVal.value[0]; // Display the results. Console.WriteLine($"Campaign with ID={newCampaign.id} and name=" + $"'{newCampaign.name}' was created."); // return the newly created campaign. return(newCampaign); } }
/// <summary> /// Creates a Shopping dynamic remarketing campaign object (not including ad group level and /// below). This creates a Display campaign with the merchant center feed attached. /// Merchant Center is used for the product information in combination with a user list /// which contains hits with <code>ecomm_prodid</code> specified. See /// <a href="https://developers.google.com/adwords-remarketing-tag/parameters#retail"> /// the guide</a> for more detail. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="merchantId">The ID of the Merchant Center account.</param> /// <param name="budgetId">The ID of the budget to use for the campaign.</param> /// <returns>The campaign that was created.</returns> private static Campaign CreateCampaign(AdWordsUser user, long merchantId, long budgetId) { using (CampaignService campaignService = (CampaignService)user.GetService(AdWordsService.v201806.CampaignService)) { Campaign campaign = new Campaign { name = "Shopping campaign #" + ExampleUtilities.GetRandomString(), // Dynamic remarketing campaigns are only available on the Google Display // Network. advertisingChannelType = AdvertisingChannelType.DISPLAY, status = CampaignStatus.PAUSED }; Budget budget = new Budget { budgetId = budgetId }; campaign.budget = budget; // This example uses a Manual CPC bidding strategy, but you should select the // strategy that best aligns with your sales goals. More details here: // https://support.google.com/adwords/answer/2472725 BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration { biddingStrategyType = BiddingStrategyType.MANUAL_CPC }; campaign.biddingStrategyConfiguration = biddingStrategyConfiguration; ShoppingSetting setting = new ShoppingSetting { // Campaigns with numerically higher priorities take precedence over those with // lower priorities. campaignPriority = 0, // Set the Merchant Center account ID from which to source products. merchantId = merchantId, // Display Network campaigns do not support partition by country. The only // supported value is "ZZ". This signals that products from all countries are // available in the campaign. The actual products which serve are based on the // products tagged in the user list entry. salesCountry = "ZZ", // Optional: Enable local inventory ads (items for sale in physical stores.) enableLocal = true }; campaign.settings = new Setting[] { setting }; CampaignOperation op = new CampaignOperation { operand = campaign, @operator = Operator.ADD }; CampaignReturnValue result = campaignService.mutate(new CampaignOperation[] { op }); return(result.value[0]); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { // Get the UserListService. AdwordsUserListService userListService = (AdwordsUserListService)user.GetService( AdWordsService.v201702.AdwordsUserListService); // Create a user list. CrmBasedUserList userList = new CrmBasedUserList() { name = "Customer relationship management list #" + ExampleUtilities.GetRandomString(), description = "A list of customers that originated from email " + "addresses", // CRM Userlist has a maximum membership lifespan of 180 days. See // https://support.google.com/adwords/answer/6276125 for details. membershipLifeSpan = 180L, }; // Create operation. UserListOperation operation = new UserListOperation() { operand = userList, @operator = Operator.ADD }; try { // Add user list. UserListReturnValue result = userListService.mutate( new UserListOperation[] { operation }); Console.WriteLine("Created new user list with name = '{0}' and id = " + "'{1}'.", result.value[0].name, result.value[0].id); // Get user list ID. long userListId = result.value[0].id; // Create operation to add members to the user list based on email // addresses. MutateMembersOperation mutateMembersOperation = new MutateMembersOperation() { operand = new MutateMembersOperand() { userListId = userListId, dataType = MutateMembersOperandDataType.EMAIL_SHA256 }, @operator = Operator.ADD }; // Hash normalized email addresses based on SHA-256 hashing algorithm. String[] emailHashes = new String[EMAILS.Length]; for (int i = 0; i < EMAILS.Length; i++) { String normalizedEmail = ToNormalizedEmail(EMAILS[i]); emailHashes[i] = ToSha256String(digest, normalizedEmail); } // Add email address hashes. mutateMembersOperation.operand.members = emailHashes; // Add members to the user list based on email addresses. MutateMembersReturnValue mutateMembersResult = userListService.mutateMembers( new MutateMembersOperation[] { mutateMembersOperation }); // Display results. // Reminder: it may take several hours for the list to be populated // with members. foreach (UserList userListResult in mutateMembersResult.userLists) { Console.WriteLine("Email addresses were added to user list with " + "name '{0}' and id '{1}'.", userListResult.name, userListResult.id); } } catch (Exception e) { throw new System.ApplicationException("Failed to add user lists " + "(a.k.a. audiences) and upload email addresses.", e); } }
/// <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.V4.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() { Name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(), 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 Status = CampaignStatus.Paused, // Set the bidding strategy and budget. ManualCpc = new ManualCpc(), CampaignBudget = budget, // Set the campaign network options. NetworkSettings = new NetworkSettings { TargetGoogleSearch = true, TargetSearchNetwork = true, TargetContentNetwork = false, TargetPartnerSearchNetwork = false }, // Optional: Set the start date. StartDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd"), // Optional: Set the end date. EndDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd"), }; // Create the operation. operations.Add(new CampaignOperation() { Create = campaign }); } try { // Add the campaigns. MutateCampaignsResponse retVal = campaignService.MutateCampaigns( customerId.ToString(), operations); // 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}"); throw; } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="businessId">The AdWords Express business id.</param> public void Run(AdWordsUser user, long businessId) { // Get the PromotionService PromotionService promotionService = (PromotionService) user.GetService(AdWordsService.v201607.PromotionService); // Set the business ID to the service. promotionService.RequestHeader.expressBusinessId = businessId; // First promotion Promotion marsTourPromotion = new Promotion(); Money budget = new Money(); budget.microAmount = 1000000L; marsTourPromotion.name = "Mars Tour Promotion " + ExampleUtilities.GetShortRandomString(); marsTourPromotion.status = PromotionStatus.PAUSED; marsTourPromotion.destinationUrl = "http://www.example.com"; marsTourPromotion.budget = budget; marsTourPromotion.callTrackingEnabled = true; // Criteria // Criterion - Travel Agency product service ProductService productService = new ProductService(); productService.text = "Travel Agency"; // Criterion - English language // The ID can be found in the documentation: // https://developers.google.com/adwords/api/docs/appendix/languagecodes Language language = new Language(); language.id = 1000L; // Criterion - State of California Location location = new Location(); location.id = 21137L; marsTourPromotion.criteria = new Criterion[] { productService, language, location }; // Creative Creative creative = new Creative(); creative.headline = "Standard Mars Trip"; creative.line1 = "Fly coach to Mars"; creative.line2 = "Free in-flight pretzels"; marsTourPromotion.creatives = new Creative[] { creative }; PromotionOperation operation = new PromotionOperation(); operation.@operator = Operator.ADD; operation.operand = marsTourPromotion; try { Promotion[] addedPromotions = promotionService.mutate( new PromotionOperation[] { operation }); Console.WriteLine("Added promotion ID {0} with name {1} to business ID {2}.", addedPromotions[0].id, addedPromotions[0].name, businessId); } catch (Exception e) { throw new System.ApplicationException("Failed to add promotions.", e); } }
/// <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> // [START add_shopping_product_ad_2] private string AddStandardShoppingCampaign(GoogleAdsClient client, long customerId, string budgetResourceName, long merchantCenterAccountId) { // Get the CampaignService. CampaignServiceClient campaignService = client.GetService(Services.V10.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 the conversion action is /// added.</param> // [START AddRemarketingAction_1] public void Run(GoogleAdsClient client, long customerId) { // Get the RemarketingActionService. RemarketingActionServiceClient remarketingActionService = client.GetService(Services.V6.RemarketingActionService); // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService(Services.V6.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. // [START AddRemarketingAction] var query = $"SELECT remarketing_action.id, remarketing_action.name, " + $"remarketing_action.tag_snippets FROM remarketing_action " + $"WHERE remarketing_action.resource_name = '{remarketingActionResourceName}'"; // [END AddRemarketingAction] // 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="user">The AdWords user.</param> public void Run(AdWordsUser user) { // Get the UserListService. AdwordsUserListService userListService = (AdwordsUserListService)user.GetService(AdWordsService.v201502.AdwordsUserListService); // Get the ConversionTrackerService. ConversionTrackerService conversionTrackerService = (ConversionTrackerService)user.GetService(AdWordsService.v201502. ConversionTrackerService); BasicUserList userList = new BasicUserList(); userList.name = "Mars cruise customers #" + ExampleUtilities.GetRandomString(); userList.description = "A list of mars cruise customers in the last year."; userList.status = UserListMembershipStatus.OPEN; userList.membershipLifeSpan = 365; UserListConversionType conversionType = new UserListConversionType(); conversionType.name = userList.name; userList.conversionTypes = new UserListConversionType[] { conversionType }; // Optional: Set the user list status. userList.status = UserListMembershipStatus.OPEN; // Create the operation. UserListOperation operation = new UserListOperation(); operation.operand = userList; operation.@operator = Operator.ADD; try { // Add the user list. UserListReturnValue retval = userListService.mutate(new UserListOperation[] { operation }); UserList[] userLists = null; if (retval != null && retval.value != null) { userLists = retval.value; // Get all conversion snippets List <string> conversionIds = new List <string>(); foreach (BasicUserList newUserList in userLists) { if (newUserList.conversionTypes != null) { foreach (UserListConversionType newConversionType in newUserList.conversionTypes) { conversionIds.Add(newConversionType.id.ToString()); } } } Dictionary <long, ConversionTracker> conversionsMap = new Dictionary <long, ConversionTracker>(); if (conversionIds.Count > 0) { // Create the selector. Selector selector = new Selector() { fields = new string[] { ConversionTracker.Fields.Id }, predicates = new Predicate[] { Predicate.In(ConversionTracker.Fields.Id, conversionIds) } }; // Get all conversion trackers. ConversionTrackerPage page = conversionTrackerService.get(selector); if (page != null && page.entries != null) { foreach (ConversionTracker tracker in page.entries) { conversionsMap[tracker.id] = tracker; } } } // Display the results. foreach (BasicUserList newUserList in userLists) { Console.WriteLine("User list with name '{0}' and id '{1}' was added.", newUserList.name, newUserList.id); // Display user list associated conversion code snippets. if (newUserList.conversionTypes != null) { foreach (UserListConversionType userListConversionType in newUserList.conversionTypes) { if (conversionsMap.ContainsKey(userListConversionType.id)) { AdWordsConversionTracker conversionTracker = (AdWordsConversionTracker)conversionsMap[userListConversionType.id]; Console.WriteLine("Conversion type code snippet associated to the list:\n{0}\n", conversionTracker.snippet); } else { throw new Exception("Failed to associate conversion type code snippet."); } } } } } else { Console.WriteLine("No user lists (a.k.a. audiences) were added."); } } catch (Exception e) { throw new System.ApplicationException("Failed to add user lists (a.k.a. audiences).", e); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="gmbEmailAddress">The email address for Google My Business /// account.</param> /// <param name="gmbAccessToken">The OAuth2 access token for Google /// My Business account.</param> /// <param name="businessAccountIdentifier">The account identifier for /// Google My Business account.</param> public void Run(AdWordsUser user, string gmbEmailAddress, string gmbAccessToken, string businessAccountIdentifier) { FeedService feedService = (FeedService)user.GetService(AdWordsService.v201502.FeedService); CustomerFeedService customerFeedService = (CustomerFeedService)user.GetService( AdWordsService.v201502.CustomerFeedService); // Create a feed that will sync to the Google My Business account // specified by gmbEmailAddress. Do not add FeedAttributes to this object, // as AdWords will add them automatically because this will be a // system generated feed. Feed gmbFeed = new Feed(); gmbFeed.name = String.Format("Google My Business feed #{0}", ExampleUtilities.GetRandomString()); PlacesLocationFeedData feedData = new PlacesLocationFeedData(); feedData.emailAddress = gmbEmailAddress; feedData.businessAccountIdentifier = businessAccountIdentifier; OAuthInfo oAuthInfo = new OAuthInfo(); oAuthInfo.httpMethod = "GET"; // Permissions for the AdWords API scope will also cover GMB. oAuthInfo.httpRequestUrl = user.Config.GetDefaultOAuth2Scope(); oAuthInfo.httpAuthorizationHeader = string.Format("Bearer {0}", gmbAccessToken); feedData.oAuthInfo = oAuthInfo; gmbFeed.systemFeedGenerationData = feedData; // Since this feed's feed items will be managed by AdWords, // you must set its origin to ADWORDS. gmbFeed.origin = FeedOrigin.ADWORDS; // Create an operation to add the feed. FeedOperation feedOperation = new FeedOperation(); feedOperation.operand = gmbFeed; feedOperation.@operator = Operator.ADD; try { // Add the feed. Since it is a system generated feed, AdWords will // automatically: // 1. Set up the FeedAttributes on the feed. // 2. Set up a FeedMapping that associates the FeedAttributes of the // feed with the placeholder fields of the LOCATION placeholder // type. FeedReturnValue addFeedResult = feedService.mutate(new FeedOperation[] { feedOperation }); Feed addedFeed = addFeedResult.value[0]; Console.WriteLine("Added GMB feed with ID {0}", addedFeed.id); // Add a CustomerFeed that associates the feed with this customer for // the LOCATION placeholder type. CustomerFeed customerFeed = new CustomerFeed(); customerFeed.feedId = addedFeed.id; customerFeed.placeholderTypes = new int[] { PLACEHOLDER_LOCATION }; // Create a matching function that will always evaluate to true. Function customerMatchingFunction = new Function(); ConstantOperand constOperand = new ConstantOperand(); constOperand.type = ConstantOperandConstantType.BOOLEAN; constOperand.booleanValue = true; customerMatchingFunction.lhsOperand = new FunctionArgumentOperand[] { constOperand }; customerMatchingFunction.@operator = FunctionOperator.IDENTITY; customerFeed.matchingFunction = customerMatchingFunction; // Create an operation to add the customer feed. CustomerFeedOperation customerFeedOperation = new CustomerFeedOperation(); customerFeedOperation.operand = customerFeed; customerFeedOperation.@operator = Operator.ADD; // After the completion of the Feed ADD operation above the added feed // will not be available for usage in a CustomerFeed until the sync // between the AdWords and GMB accounts completes. The loop below // will retry adding the CustomerFeed up to ten times with an // exponential back-off policy. CustomerFeed addedCustomerFeed = null; AdWordsAppConfig config = new AdWordsAppConfig(); config.RetryCount = 10; ErrorHandler errorHandler = new ErrorHandler(config); do { try { CustomerFeedReturnValue customerFeedResult = customerFeedService.mutate(new CustomerFeedOperation[] { customerFeedOperation }); addedCustomerFeed = customerFeedResult.value[0]; Console.WriteLine("Added CustomerFeed for feed ID {0} and placeholder type {1}", addedCustomerFeed.feedId, addedCustomerFeed.placeholderTypes[0]); break; } catch (AdWordsApiException e) { ApiException apiException = (ApiException)e.ApiException; foreach (ApiError error in apiException.errors) { if (error is CustomerFeedError) { if ((error as CustomerFeedError).reason == CustomerFeedErrorReason.MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE) { errorHandler.DoExponentialBackoff(); errorHandler.IncrementRetriedAttempts(); } else { throw; } } } } } while (errorHandler.HaveMoreRetryAttemptsLeft()); // OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at // the Campaign level. This will be similar to the CampaignFeed in the // AddSiteLinks example, except you can also filter based on the // business name and category of each FeedItem by using a // FeedAttributeOperand in your matching function. // OPTIONAL: Create an AdGroupFeed for even more fine grained control // over which feed items are used at the AdGroup level. } catch (Exception e) { throw new System.ApplicationException("Failed to create customer feed.", e); } }