/// <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) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201802.AdGroupAdService)) { // Create the template ad. TemplateAd clickToDownloadAppAd = new TemplateAd(); clickToDownloadAppAd.name = "Ad for demo game"; clickToDownloadAppAd.templateId = 353; clickToDownloadAppAd.finalUrls = new string[] { "http://play.google.com/store/apps/details?id=com.example.demogame" }; clickToDownloadAppAd.displayUrl = "play.google.com"; // Create the template elements for the ad. You can refer to // https://developers.google.com/adwords/api/docs/appendix/templateads // for the list of avaliable template fields. TemplateElementField headline = new TemplateElementField(); headline.name = "headline"; headline.fieldText = "Enjoy your drive in Mars"; headline.type = TemplateElementFieldType.TEXT; TemplateElementField description1 = new TemplateElementField(); description1.name = "description1"; description1.fieldText = "Realistic physics simulation"; description1.type = TemplateElementFieldType.TEXT; TemplateElementField description2 = new TemplateElementField(); description2.name = "description2"; description2.fieldText = "Race against players online"; description2.type = TemplateElementFieldType.TEXT; TemplateElementField appId = new TemplateElementField(); appId.name = "appId"; appId.fieldText = "com.example.demogame"; appId.type = TemplateElementFieldType.TEXT; TemplateElementField appStore = new TemplateElementField(); appStore.name = "appStore"; appStore.fieldText = "2"; appStore.type = TemplateElementFieldType.ENUM; // Optionally specify a landscape image. The image needs to be in a BASE64 // encoded form. Here we download a demo image and encode it for this ad. byte[] imageData = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/9JmyKk"); Image image = new Image(); image.data = imageData; TemplateElementField landscapeImage = new TemplateElementField(); landscapeImage.name = "landscapeImage"; landscapeImage.fieldMedia = image; landscapeImage.type = TemplateElementFieldType.IMAGE; TemplateElement adData = new TemplateElement(); adData.uniqueName = "adData"; adData.fields = new TemplateElementField[] { headline, description1, description2, appId, appStore, landscapeImage }; clickToDownloadAppAd.templateElements = new TemplateElement[] { adData }; // Create the adgroupad. AdGroupAd clickToDownloadAppAdGroupAd = new AdGroupAd(); clickToDownloadAppAdGroupAd.adGroupId = adGroupId; clickToDownloadAppAdGroupAd.ad = clickToDownloadAppAd; // Optional: Set the status. clickToDownloadAppAdGroupAd.status = AdGroupAdStatus.PAUSED; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.@operator = Operator.ADD; operation.operand = clickToDownloadAppAdGroupAd; try { // Create the ads. AdGroupAdReturnValue retval = adGroupAdService.mutate( new AdGroupAdOperation[] { operation }); // Display the results. if (retval != null && retval.value != null) { foreach (AdGroupAd adGroupAd in retval.value) { Console.WriteLine("New click-to-download ad with id = \"{0}\" and url = \"{1}\" " + "was created.", adGroupAd.ad.id, adGroupAd.ad.finalUrls[0]); } } else { Console.WriteLine("No click-to-download ads were created."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create click-to-download ad.", 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) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201806.AdGroupAdService)) { // Create a responsive search ad. ResponsiveSearchAd responsiveSearchAd = new ResponsiveSearchAd() { finalUrls = new string[] { "http://www.example.com/cruise" }, path1 = "all-inclusive", path2 = "deals", headlines = new AssetLink[] { new AssetLink() { asset = new TextAsset() { assetText = "Cruise to Mars #" + ExampleUtilities.GetShortRandomString(), }, // Set 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. pinnedField = ServedAssetFieldType.HEADLINE_1 }, new AssetLink() { asset = new TextAsset() { assetText = "Best Space Cruise Line", } }, new AssetLink() { asset = new TextAsset() { assetText = "Experience the Stars", } }, }, descriptions = new AssetLink[] { new AssetLink() { asset = new TextAsset() { assetText = "Buy your tickets now", } }, new AssetLink() { asset = new TextAsset() { assetText = "Visit the Red Planet", } }, } }; // Create ad group ad. AdGroupAd adGroupAd = new AdGroupAd() { adGroupId = adGroupId, ad = responsiveSearchAd, // Optional: Set additional settings. status = AdGroupAdStatus.PAUSED }; // Create ad group ad operation and add it to the list. AdGroupAdOperation operation = new AdGroupAdOperation() { operand = adGroupAd, @operator = Operator.ADD }; try { // Add the responsive search ad on the server. AdGroupAdReturnValue retval = adGroupAdService.mutate( new AdGroupAdOperation[] { operation }); // Print out some information for the created ad. foreach (AdGroupAd newAdGroupAd in retval.value) { ResponsiveSearchAd newAd = (ResponsiveSearchAd)newAdGroupAd.ad; Console.WriteLine($"New responsive search ad with ID {newAd.id} was added."); Console.WriteLine("Headlines:"); foreach (AssetLink headline in newAd.headlines) { TextAsset textAsset = headline.asset as TextAsset; Console.WriteLine($" {textAsset.assetText}"); if (headline.pinnedFieldSpecified) { Console.WriteLine($" (pinned to {headline.pinnedField})"); } } Console.WriteLine("Descriptions:"); foreach (AssetLink description in newAd.descriptions) { TextAsset textAsset = description.asset as TextAsset; Console.WriteLine($" {textAsset.assetText}"); if (description.pinnedFieldSpecified) { Console.WriteLine($" (pinned to {description.pinnedField})"); } } } } catch (Exception e) { throw new System.ApplicationException("Failed to create responsive search ad.", e); } } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the adgroup to which ads are added.</param> public void Run(AdWordsUser user, long adGroupId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService( AdWordsService.v201806.AdGroupAdService)) { // This ad format does not allow the creation of an image using the // Image.data field. An image must first be created using the // MediaService, and Image.mediaId must be populated when creating the // ad. Image logoImage = new Image { mediaId = UploadImage(user, "https://goo.gl/mtt54n").mediaId }; Image marketingImage = new Image { mediaId = UploadImage(user, "https://goo.gl/3b9Wfh").mediaId }; GmailTeaser teaser = new GmailTeaser { headline = "Dream", description = "Create your own adventure", businessName = "Interplanetary Ships", logoImage = logoImage }; // Creates a Gmail ad. GmailAd gmailAd = new GmailAd { teaser = teaser, marketingImage = marketingImage, marketingImageHeadline = "Travel", marketingImageDescription = "Take to the skies!", finalUrls = new string[] { "http://www.example.com/" } }; // Creates ad group ad for the Gmail ad. AdGroupAd adGroupAd = new AdGroupAd { adGroupId = adGroupId, ad = gmailAd, // Optional: Set additional settings. status = AdGroupAdStatus.PAUSED }; // Creates ad group ad operation and add it to the list. AdGroupAdOperation operation = new AdGroupAdOperation { operand = adGroupAd, @operator = Operator.ADD }; try { // Adds a responsive display ad on the server. AdGroupAdReturnValue result = adGroupAdService.mutate( new AdGroupAdOperation[] { operation }); if (result == null || result.value == null || result.value.Length == 0) { Console.WriteLine("No Gmail ads were added."); return; } // Prints out some information for each created Gmail ad. foreach (AdGroupAd newAdGroupAd in result.value) { Console.WriteLine("A Gmail ad with ID {0} and headline '{1}' was added.", newAdGroupAd.ad.id, (newAdGroupAd.ad as GmailAd).teaser.headline); } } catch (Exception e) { throw new System.ApplicationException("Failed to add Gmail ads.", e); } } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the first adgroup to which ad is added.</param> public void Run(AdWordsUser user, long adGroupId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201809.AdGroupAdService)) { // Create the HTML5 template ad. See // https://developers.google.com/adwords/api/docs/guides/template-ads#html5_ads // for more details. TemplateAd html5Ad = new TemplateAd() { name = "Ad for HTML5", templateId = 419, finalUrls = new string[] { "http://example.com/html5" }, displayUrl = "www.example.com/html5", dimensions = new Dimensions() { width = 300, height = 250 } }; // The HTML5 zip file contains all the HTML, CSS, and images needed for the // HTML5 ad. For help on creating an HTML5 zip file, check out Google Web // Designer (https://www.google.com/webdesigner/). byte[] html5Zip = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/9Y7qI2", user.Config); // Create a media bundle containing the zip file with all the HTML5 components. MediaBundle mediaBundle = new MediaBundle() { // You may also upload an HTML5 zip using MediaService.upload() method // set the mediaId field. See UploadMediaBundle.cs for an example on // how to upload HTML5 zip files. data = html5Zip, entryPoint = "carousel/index.html", type = MediaMediaType.MEDIA_BUNDLE }; // Create the template elements for the ad. You can refer to // https://developers.google.com/adwords/api/docs/appendix/templateads // for the list of available template fields. html5Ad.templateElements = new TemplateElement[] { new TemplateElement() { uniqueName = "adData", fields = new TemplateElementField[] { new TemplateElementField() { name = "Custom_layout", fieldMedia = mediaBundle, type = TemplateElementFieldType.MEDIA_BUNDLE }, new TemplateElementField() { name = "layout", fieldText = "Custom", type = TemplateElementFieldType.ENUM }, }, } }; // Create the AdGroupAd. AdGroupAd html5AdGroupAd = new AdGroupAd() { adGroupId = adGroupId, ad = html5Ad, // Additional properties (non-required). status = AdGroupAdStatus.PAUSED }; AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation() { @operator = Operator.ADD, operand = html5AdGroupAd }; try { // Add HTML5 ad. AdGroupAdReturnValue result = adGroupAdService.mutate(new AdGroupAdOperation[] { adGroupAdOperation }); // Display results. if (result != null && result.value != null && result.value.Length > 0) { foreach (AdGroupAd adGroupAd in result.value) { Console.WriteLine( "New HTML5 ad with id \"{0}\" and display url \"{1}\" was added.", adGroupAd.ad.id, adGroupAd.ad.displayUrl); } } else { Console.WriteLine("No HTML5 ads were added."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create HTML5 ad.", 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) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201710.AdGroupAdService)) { try { // Create a responsive display ad. ResponsiveDisplayAd responsiveDisplayAd = new ResponsiveDisplayAd(); // This ad format does not allow the creation of an image using the // Image.data field. An image must first be created using the MediaService, // and Image.mediaId must be populated when creating the ad. responsiveDisplayAd.marketingImage = new Image() { mediaId = UploadImage(user, "https://goo.gl/3b9Wfh") }; responsiveDisplayAd.shortHeadline = "Travel"; responsiveDisplayAd.longHeadline = "Travel the World"; responsiveDisplayAd.description = "Take to the air!"; responsiveDisplayAd.businessName = "Google"; responsiveDisplayAd.finalUrls = new string[] { "http://www.example.com" }; // Optional: Create a square marketing image using MediaService, and set it // to the ad. responsiveDisplayAd.squareMarketingImage = new Image() { mediaId = UploadImage(user, "https://goo.gl/mtt54n"), }; // Optional: set call to action text. responsiveDisplayAd.callToActionText = "Shop Now"; // Optional: Set dynamic display ad settings, composed of landscape logo // image, promotion text, and price prefix. responsiveDisplayAd.dynamicDisplayAdSettings = CreateDynamicDisplayAdSettings(user); // Whitelisted accounts only: Set color settings using hexadecimal values. // Set allowFlexibleColor to false if you want your ads to render by always // using your colors strictly. // responsiveDisplayAd.mainColor = "#0000ff"; // responsiveDisplayAd.accentColor = "#ffff00"; // responsiveDisplayAd.allowFlexibleColor = false; // Whitelisted accounts only: Set the format setting that the ad will be // served in. // responsiveDisplayAd.formatSetting = DisplayAdFormatSetting.NON_NATIVE; // Create ad group ad. AdGroupAd adGroupAd = new AdGroupAd() { adGroupId = adGroupId, ad = responsiveDisplayAd, status = AdGroupAdStatus.PAUSED }; // Create operation. AdGroupAdOperation operation = new AdGroupAdOperation() { operand = adGroupAd, @operator = Operator.ADD }; // Make the mutate request. AdGroupAdReturnValue result = adGroupAdService.mutate( new AdGroupAdOperation[] { operation }); // Display results. if (result != null && result.value != null) { foreach (AdGroupAd newAdGroupAd in result.value) { ResponsiveDisplayAd newAd = newAdGroupAd.ad as ResponsiveDisplayAd; Console.WriteLine("Responsive display ad with ID '{0}' and short headline '{1}'" + " was added.", newAd.id, newAd.shortHeadline); } } else { Console.WriteLine("No responsive display ads were created."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create responsive display ad.", 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.v201502.AdGroupAdService); // Create standard third party redirect ad. ThirdPartyRedirectAd standardAd = new ThirdPartyRedirectAd(); standardAd.name = String.Format("Example third party ad #{0}", ExampleUtilities.GetRandomString()); standardAd.finalUrls = new string[] { "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.finalUrls = new string[] { "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).finalUrls[0], 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> /// 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) { // [START addResponsiveDisplayAd] MOE:strip_line // Get the AdGroupAdService. AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201605.AdGroupAdService); // Get the MediaService. MediaService mediaService = (MediaService)user.GetService(AdWordsService.v201605.MediaService); try { // Create the image. Image image = new Image() { data = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/3b9Wfh", user.Config), type = MediaMediaType.IMAGE }; // Upload the image. Image newImage = (Image)mediaService.upload(new Media[] { image })[0]; // Create a responsive display ad. ResponsiveDisplayAd responsiveDisplayAd = new ResponsiveDisplayAd(); // This ad format does not allow the creation of an image using the // Image.data field. An image must first be created using the MediaService, // and Image.mediaId must be populated when creating the ad. responsiveDisplayAd.marketingImage = new Image() { mediaId = newImage.mediaId }; responsiveDisplayAd.shortHeadline = "Travel"; responsiveDisplayAd.longHeadline = "Travel the World"; responsiveDisplayAd.description = "Take to the air!"; responsiveDisplayAd.businessName = "Google"; responsiveDisplayAd.finalUrls = new string[] { "http://www.example.com" }; // Create ad group ad. AdGroupAd adGroupAd = new AdGroupAd() { adGroupId = adGroupId, ad = responsiveDisplayAd, status = AdGroupAdStatus.PAUSED }; // Create operation. AdGroupAdOperation operation = new AdGroupAdOperation() { operand = adGroupAd, @operator = Operator.ADD }; // Make the mutate request. AdGroupAdReturnValue result = adGroupAdService.mutate( new AdGroupAdOperation[] { operation }); // Display results. if (result != null && result.value != null) { foreach (AdGroupAd newAdGroupAd in result.value) { ResponsiveDisplayAd newAd = newAdGroupAd.ad as ResponsiveDisplayAd; Console.WriteLine("Responsive display ad with ID '{0}' and short headline '{1}'" + " was added.", newAd.id, newAd.shortHeadline); } } else { Console.WriteLine("No responsive display ads were created."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create responsive display ad.", e); } // [END addResponsiveDisplayAd] MOE:strip_line }
/// <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> /// 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) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201802.AdGroupAdService)) { List <AdGroupAdOperation> operations = new List <AdGroupAdOperation>(); for (int i = 0; i < NUMBER_OF_ADS; i++) { // Create the expanded text ad. ExpandedTextAd expandedTextAd = new ExpandedTextAd { headlinePart1 = "Cruise #" + i.ToString() + " to Mars", headlinePart2 = "Best Space Cruise Line", description = "Buy your tickets now!", finalUrls = new string[] { "http://www.example.com/" + i } }; AdGroupAd expandedTextAdGroupAd = new AdGroupAd { adGroupId = adGroupId, ad = expandedTextAd, // Optional: Set the status. status = AdGroupAdStatus.PAUSED }; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation { @operator = Operator.ADD, operand = expandedTextAdGroupAd }; operations.Add(operation); } AdGroupAdReturnValue retVal = null; try { // Create the ads. retVal = adGroupAdService.mutate(operations.ToArray()); // Display the results. if (retVal != null && retVal.value != null) { foreach (AdGroupAd adGroupAd in retVal.value) { ExpandedTextAd newAd = adGroupAd.ad as ExpandedTextAd; Console.WriteLine( "Expanded text ad with ID '{0}' and headline '{1} - {2}' " + "was added.", newAd.id, newAd.headlinePart1, newAd.headlinePart2); } } else { Console.WriteLine("No expanded text ads were created."); } adGroupAdService.Close(); } catch (Exception e) { throw new System.ApplicationException("Failed to create expanded text ad.", 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.v201502.AdGroupAdService); List <AdGroupAdOperation> operations = new List <AdGroupAdOperation>(); for (int i = 0; i < NUM_ITEMS; i++) { // Create the text ad. TextAd textAd = new TextAd(); textAd.headline = "Luxury Cruise to Mars"; textAd.description1 = "Visit the Red Planet in style."; textAd.description2 = "Low-gravity fun for everyone!"; textAd.displayUrl = "www.example.com"; textAd.finalUrls = new string[] { "http://www.example.com/" + i }; AdGroupAd textAdGroupAd = new AdGroupAd(); textAdGroupAd.adGroupId = adGroupId; textAdGroupAd.ad = textAd; // Optional: Set the status. textAdGroupAd.status = AdGroupAdStatus.PAUSED; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.@operator = Operator.ADD; operation.operand = textAdGroupAd; operations.Add(operation); } AdGroupAdReturnValue retVal = null; try { // Create the ads. retVal = service.mutate(operations.ToArray()); // Display the results. 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 TextAd) { ... } // // to identify the ad type. foreach (AdGroupAd adGroupAd in retVal.value) { Console.WriteLine("New text ad with id = \"{0}\" and displayUrl = \"{1}\" was created.", adGroupAd.ad.id, adGroupAd.ad.displayUrl); } } else { Console.WriteLine("No text ads were created."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to create text ad.", ex); } }
/// <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) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201809.AdGroupAdService)) { try { // Create the ad. MultiAssetResponsiveDisplayAd ad = new MultiAssetResponsiveDisplayAd() { headlines = new AssetLink[] { new AssetLink() { // Text assets can be specified directly in the asset field when // creating the ad. asset = new TextAsset() { assetText = "Travel to Mars", }, }, new AssetLink() { asset = new TextAsset() { assetText = "Travel to Jupiter", }, }, new AssetLink() { asset = new TextAsset() { assetText = "Travel to Pluto", }, }, }, descriptions = new AssetLink[] { new AssetLink() { asset = new TextAsset() { assetText = "Visit the planet in a luxury spaceship.", }, }, new AssetLink() { asset = new TextAsset() { assetText = "See the planet in style.", }, }, }, businessName = "Galactic Luxury Cruises", longHeadline = new AssetLink() { asset = new TextAsset() { assetText = "Visit the planet in a luxury spaceship.", }, }, // This ad format does not allow the creation of an image asset by setting // the asset.imageData field. An image asset must first be created using the // AssetService, and asset.assetId must be populated when creating the ad. marketingImages = new AssetLink[] { new AssetLink() { asset = new ImageAsset() { assetId = UploadImageAsset(user, "https://goo.gl/3b9Wfh") }, } }, squareMarketingImages = new AssetLink[] { new AssetLink() { asset = new ImageAsset() { assetId = UploadImageAsset(user, "https://goo.gl/mtt54n") }, } }, finalUrls = new string[] { "http://www.example.com" }, // Optional: set call to action text. callToActionText = "Shop Now", // Set color settings using hexadecimal values. Set allowFlexibleColor to // false if you want your ads to render by always using your colors // strictly. mainColor = "#0000ff", accentColor = "#ffff00", allowFlexibleColor = false, // Set the format setting that the ad will be served in. formatSetting = DisplayAdFormatSetting.NON_NATIVE, // Optional: Set dynamic display ad settings, composed of landscape logo // image, promotion text, and price prefix. dynamicSettingsPricePrefix = "as low as", dynamicSettingsPromoText = "Free shipping!", logoImages = new AssetLink[] { new AssetLink() { asset = new ImageAsset() { assetId = UploadImageAsset(user, "https://goo.gl/mtt54n") }, } } }; // Create the ad group ad. AdGroupAd adGroupAd = new AdGroupAd() { ad = ad, adGroupId = adGroupId }; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation() { operand = adGroupAd, @operator = Operator.ADD }; // Make the mutate request. AdGroupAdReturnValue result = adGroupAdService.mutate(new AdGroupAdOperation[] { operation }); // Display results. if (result != null && result.value != null) { foreach (AdGroupAd newAdGroupAd in result.value) { MultiAssetResponsiveDisplayAd newAd = newAdGroupAd.ad as MultiAssetResponsiveDisplayAd; Console.WriteLine( "Responsive display ad with ID '{0}' and long headline '{1}'" + " was added.", newAd.id, (newAd.longHeadline.asset as TextAsset).assetText); } } else { Console.WriteLine("No responsive display ads were created."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create responsive display ad.", e); } } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to which text ads are /// added.</param> public void Run(AdWordsUser user, long adGroupId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201802.AdGroupAdService)) { // Set the validateOnly headers. adGroupAdService.RequestHeader.validateOnly = true; // Create your expanded text ad. ExpandedTextAd expandedTextAd = new ExpandedTextAd() { headlinePart1 = "Luxury Cruise to Mars", headlinePart2 = "Visit the Red Planet in style.", description = "Low-gravity fun for everyone!!", finalUrls = new string[] { "http://www.example.com" } }; AdGroupAd adGroupAd = new AdGroupAd() { adGroupId = adGroupId, ad = expandedTextAd }; AdGroupAdOperation operation = new AdGroupAdOperation() { @operator = Operator.ADD, operand = adGroupAd }; try { adGroupAdService.mutate(new AdGroupAdOperation[] { operation }); // Since validation is ON, result will be null. Console.WriteLine("Expanded text ad validated successfully."); } catch (AdWordsApiException e) { // This block will be hit if there is a validation error from the server. Console.WriteLine( "There were validation error(s) while adding expanded text ad."); if (e.ApiException != null) { foreach (ApiError error in ((ApiException)e.ApiException).errors) { Console.WriteLine(" Error type is '{0}' and fieldPath is '{1}'.", error.ApiErrorType, error.fieldPath); } } } catch (Exception e) { throw new System.ApplicationException("Failed to validate expanded text ad.", e); } } }
/// <summary> /// Creates the Product Ad. /// </summary> /// <param name="adGroupAdService">The AdGroupAdService instance.</param> /// <param name="adGroup">The ad group.</param> /// <returns>The Product Ad.</returns> private static AdGroupAd CreateProductAd(AdGroupAdService adGroupAdService, AdGroup adGroup) { // Create product ad. ProductAd productAd = new ProductAd(); // Create ad group ad. AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.adGroupId = adGroup.id; adGroupAd.ad = productAd; // Create operation. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.operand = adGroupAd; operation.@operator = Operator.ADD; // Make the mutate request. AdGroupAdReturnValue retval = adGroupAdService.mutate( new AdGroupAdOperation[] { operation }); return retval.value[0]; }
/// <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 adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201402.AdGroupAdService); // Create the template ad. TemplateAd clickToDownloadAppAd = new TemplateAd(); clickToDownloadAppAd.name = "Ad for demo game"; clickToDownloadAppAd.templateId = 353; clickToDownloadAppAd.url = "http://play.google.com/store/apps/details?id=com.example.demogame"; clickToDownloadAppAd.displayUrl = "play.google.com"; // Create the template elements for the ad. You can refer to // https://developers.google.com/adwords/api/docs/appendix/templateads // for the list of avaliable template fields. TemplateElementField headline = new TemplateElementField(); headline.name = "headline"; headline.fieldText = "Enjoy your drive in Mars"; headline.type = TemplateElementFieldType.TEXT; TemplateElementField description1 = new TemplateElementField(); description1.name = "description1"; description1.fieldText = "Realistic physics simulation"; description1.type = TemplateElementFieldType.TEXT; TemplateElementField description2 = new TemplateElementField(); description2.name = "description2"; description2.fieldText = "Race against players online"; description2.type = TemplateElementFieldType.TEXT; TemplateElementField appId = new TemplateElementField(); appId.name = "appId"; appId.fieldText = "com.example.demogame"; appId.type = TemplateElementFieldType.TEXT; TemplateElementField appStore = new TemplateElementField(); appStore.name = "appStore"; appStore.fieldText = "2"; appStore.type = TemplateElementFieldType.ENUM; TemplateElement adData = new TemplateElement(); adData.uniqueName = "adData"; adData.fields = new TemplateElementField[] { headline, description1, description2, appId, appStore }; clickToDownloadAppAd.templateElements = new TemplateElement[] { adData }; // Create the adgroupad. AdGroupAd clickToDownloadAppAdGroupAd = new AdGroupAd(); clickToDownloadAppAdGroupAd.adGroupId = adGroupId; clickToDownloadAppAdGroupAd.ad = clickToDownloadAppAd; // Optional: Set the status. clickToDownloadAppAdGroupAd.status = AdGroupAdStatus.PAUSED; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.@operator = Operator.ADD; operation.operand = clickToDownloadAppAdGroupAd; try { // Create the ads. AdGroupAdReturnValue retval = adGroupAdService.mutate(new AdGroupAdOperation[] { operation }); // Display the results. if (retval != null && retval.value != null) { foreach (AdGroupAd adGroupAd in retval.value) { Console.WriteLine("New click-to-download ad with id = \"{0}\" and url = \"{1}\" " + "was created.", adGroupAd.ad.id, adGroupAd.ad.url); } } else { Console.WriteLine("No click-to-download ads were created."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to create click-to-download ad.", ex); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group that contains the criterion. /// </param> /// <param name="criterionId">Id of the keyword for which the ad /// parameters are set.</param> public void Run(AdWordsUser user, long adGroupId, long criterionId) { // Get the AdGroupAdService. AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService( AdWordsService.v201601.AdGroupAdService); // Get the AdParamService. AdParamService adParamService = (AdParamService)user.GetService( AdWordsService.v201601.AdParamService); // Create the text ad. TextAd textAd = new TextAd(); textAd.finalUrls = new string[] { "http://www.example.com" }; textAd.displayUrl = "example.com"; textAd.headline = " Mars Cruises"; textAd.description1 = "Low-gravity fun for {param1:cheap}."; textAd.description2 = "Only {param2:a few} seats left!"; AdGroupAd adOperand = new AdGroupAd(); adOperand.adGroupId = adGroupId; adOperand.status = AdGroupAdStatus.ENABLED; adOperand.ad = textAd; // Create the operation. AdGroupAdOperation adOperation = new AdGroupAdOperation(); adOperation.operand = adOperand; adOperation.@operator = Operator.ADD; try { // Create the text ad. AdGroupAdReturnValue retVal = adGroupAdService.mutate( new AdGroupAdOperation[] { adOperation }); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { Console.WriteLine("Text ad with id ='{0}' was successfully added.", retVal.value[0].ad.id); } else { Console.WriteLine("No text ads were created."); return; } } catch (Exception e) { Console.WriteLine("Failed to create text ads. Exception says \"{0}\"", e.Message); return; } // Create the ad param for price. AdParam priceParam = new AdParam(); priceParam.adGroupId = adGroupId; priceParam.criterionId = criterionId; priceParam.paramIndex = 1; priceParam.insertionText = "$100"; // Create the ad param for seats. AdParam seatParam = new AdParam(); seatParam.adGroupId = adGroupId; seatParam.criterionId = criterionId; seatParam.paramIndex = 2; seatParam.insertionText = "50"; // Create the operations. AdParamOperation priceOperation = new AdParamOperation(); priceOperation.@operator = Operator.SET; priceOperation.operand = priceParam; AdParamOperation seatOperation = new AdParamOperation(); seatOperation.@operator = Operator.SET; seatOperation.operand = seatParam; try { // Set the ad parameters. AdParam [] newAdParams = adParamService.mutate(new AdParamOperation[] { priceOperation, seatOperation }); // Display the results. if (newAdParams != null) { Console.WriteLine("Ad parameters were successfully updated."); } else { Console.WriteLine("No ad parameters were set."); } } catch (Exception e) { throw new System.ApplicationException("Failed to set ad parameters.", e); } }
/// <summary> /// Creates an ad for serving dynamic content in a remarketing campaign. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroup">The ad group under which to create the ad.</param> /// <returns>The ad that was created.</returns> private static AdGroupAd CreateAd(AdWordsUser user, AdGroup adGroup) { using (AdGroupAdService adService = (AdGroupAdService)user.GetService(AdWordsService.v201806.AdGroupAdService)) { ResponsiveDisplayAd ad = new ResponsiveDisplayAd { // This ad format does not allow the creation of an image using the // Image.data field. An image must first be created using the MediaService, // and Image.mediaId must be populated when creating the ad. marketingImage = UploadImage(user, "https://goo.gl/3b9Wfh"), shortHeadline = "Travel", longHeadline = "Travel the World", description = "Take to the air!", businessName = "Interplanetary Cruises", finalUrls = new string[] { "http://www.example.com/" }, // Optional: Call to action text. // Valid texts: https://support.google.com/adwords/answer/7005917 callToActionText = "Apply Now", // Optional: Set dynamic display ad settings, composed of landscape logo // image, promotion text, and price prefix. dynamicDisplayAdSettings = CreateDynamicDisplayAdSettings(user), // Optional: Create a logo image and set it to the ad. logoImage = UploadImage(user, "https://goo.gl/mtt54n"), // Optional: Create a square marketing image and set it to the ad. squareMarketingImage = UploadImage(user, "https://goo.gl/mtt54n") }; // Whitelisted accounts only: Set color settings using hexadecimal values. // Set allowFlexibleColor to false if you want your ads to render by always // using your colors strictly. // ad.mainColor = "#0000ff"; // ad.accentColor = "#ffff00"; // ad.allowFlexibleColor = false; // Whitelisted accounts only: Set the format setting that the ad will be // served in. // ad.formatSetting = DisplayAdFormatSetting.NON_NATIVE; AdGroupAd adGroupAd = new AdGroupAd { ad = ad, adGroupId = adGroup.id }; AdGroupAdOperation op = new AdGroupAdOperation { operand = adGroupAd, @operator = Operator.ADD }; AdGroupAdReturnValue result = adService.mutate(new AdGroupAdOperation[] { op }); return(result.value[0]); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">ID of the ad group to which ad is added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService)user.GetService(AdWordsService.v201702.AdGroupAdService); // Create the expanded text ad. ExpandedTextAd expandedTextAd = new ExpandedTextAd() { headlinePart1 = "Luxury Cruise to Mars", headlinePart2 = "Visit the Red Planet in style.", description = "Low-gravity fun for everyone!", }; // Specify a tracking URL for 3rd party tracking provider. You may // specify one at customer, campaign, ad group, ad, criterion or // feed item levels. expandedTextAd.trackingUrlTemplate = "http://tracker.example.com/?season={_season}&promocode={_promocode}&u={lpurl}"; // Since your tracking URL has two custom parameters, provide their // values too. This can be provided at campaign, ad group, ad, criterion // or feed item levels. CustomParameter seasonParameter = new CustomParameter(); seasonParameter.key = "season"; seasonParameter.value = "christmas"; CustomParameter promoCodeParameter = new CustomParameter(); promoCodeParameter.key = "promocode"; promoCodeParameter.value = "NYC123"; expandedTextAd.urlCustomParameters = new CustomParameters(); expandedTextAd.urlCustomParameters.parameters = new CustomParameter[] { seasonParameter, promoCodeParameter }; // Specify a list of final URLs. This field cannot be set if URL field is // set. This may be specified at ad, criterion and feed item levels. expandedTextAd.finalUrls = new string[] { "http://www.example.com/cruise/space/", "http://www.example.com/locations/mars/" }; // Specify a list of final mobile URLs. This field cannot be set if URL // field is set, or finalUrls is unset. This may be specified at ad, // criterion and feed item levels. expandedTextAd.finalMobileUrls = new string[] { "http://mobile.example.com/cruise/space/", "http://mobile.example.com/locations/mars/" }; AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.adGroupId = adGroupId; adGroupAd.ad = expandedTextAd; // Optional: Set the status. adGroupAd.status = AdGroupAdStatus.PAUSED; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.@operator = Operator.ADD; operation.operand = adGroupAd; AdGroupAdReturnValue retVal = null; try { // Create the ads. retVal = service.mutate(new AdGroupAdOperation[] { operation }); // Display the results. if (retVal != null && retVal.value != null) { ExpandedTextAd newExpandedTextAd = retVal.value[0].ad as ExpandedTextAd; Console.WriteLine("Expanded text ad with ID '{0}' and headline '{1} - {2}' was added.", newExpandedTextAd.id, newExpandedTextAd.headlinePart1, newExpandedTextAd.headlinePart2); Console.WriteLine("Upgraded URL properties:"); Console.WriteLine(" Final URLs: {0}", string.Join(", ", newExpandedTextAd.finalUrls)); Console.WriteLine(" Final Mobile URLs: {0}", string.Join(", ", newExpandedTextAd.finalMobileUrls)); Console.WriteLine(" Tracking URL template: {0}", newExpandedTextAd.trackingUrlTemplate); List <string> parameters = new List <string>(); foreach (CustomParameter customParam in newExpandedTextAd.urlCustomParameters.parameters) { parameters.Add(string.Format("{0}={1}", customParam.key, customParam.value)); } Console.WriteLine(" Custom parameters: {0}", string.Join(", ", parameters.ToArray())); } else { Console.WriteLine("No expanded text ads were created."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create expanded text ad.", e); } }
public static AdGroupAdReturnValue CreateTextAds(AdWordsUser user, AdWordsContentLo adWordsContent) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201710.AdGroupAdService)) { List <AdGroupAdOperation> operations = new List <AdGroupAdOperation>(); for (int i = 0; i < adWordsContent.ContentProducts.Count; i++) { // Create the expanded text ad. ExpandedTextAd expandedTextAd = new ExpandedTextAd(); expandedTextAd.headlinePart1 = adWordsContent.ContentProducts[i].AdContent.HeadLinePart1; expandedTextAd.headlinePart2 = adWordsContent.ContentProducts[i].AdContent.HeadLinePart2; expandedTextAd.path1 = adWordsContent.ContentProducts[i].AdContent.Path1 != "" ? adWordsContent.ContentProducts[i].AdContent.Path1 : ""; expandedTextAd.path2 = adWordsContent.ContentProducts[i].AdContent.Path2 != "" ? adWordsContent.ContentProducts[i].AdContent.Path2 : ""; expandedTextAd.description = adWordsContent.ContentProducts[i].AdContent.Description; expandedTextAd.finalUrls = adWordsContent.ContentProducts[i].FinalUrl; AdGroupAd expandedTextAdGroupAd = new AdGroupAd(); expandedTextAdGroupAd.adGroupId = adWordsContent.AdGroupLo.AdGroupId; expandedTextAdGroupAd.ad = expandedTextAd; // Optional: Set the status. expandedTextAdGroupAd.status = AdGroupAdStatus.ENABLED; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.@operator = Operator.ADD; operation.operand = expandedTextAdGroupAd; operations.Add(operation); } AdGroupAdReturnValue retVal = null; try { // Create the ads. retVal = adGroupAdService.mutate(operations.ToArray()); adGroupAdService.Close(); } catch (AdWordsApiException e) { ApiException innerException = e.ApiException as ApiException; if (innerException == null) { throw new Exception("Failed to retrieve ApiError. See inner exception for more " + "details.", e); } // Examine each ApiError received from the server. foreach (ApiError apiError in innerException.errors) { int index = apiError.GetOperationIndex(); 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>(); } else { // Policy violation error is not exemptable, remove this // operation from the list of operations. } } else { // This is not a policy violation error, remove this operation // from the list of operations. } } } catch (Exception ex) { throw new System.ApplicationException("Failed to create expanded text ad.", ex); } return(retVal); } }
/// <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.v201605.AdGroupAdService); // Create the text ad. TextAd textAd = new TextAd(); textAd.headline = "Luxury Cruise to Mars"; textAd.description1 = "Visit the Red Planet in style."; textAd.description2 = "Low-gravity fun for everyone!!"; textAd.displayUrl = "www.example.com"; textAd.finalUrls = new string[] { "http://www.example.com" }; AdGroupAd textadGroupAd = new AdGroupAd(); textadGroupAd.adGroupId = adGroupId; textadGroupAd.ad = textAd; // Create the operations. AdGroupAdOperation textAdOperation = new AdGroupAdOperation(); textAdOperation.@operator = Operator.ADD; textAdOperation.operand = textadGroupAd; 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(textAdOperation); try { // Validate the operations. service.RequestHeader.validateOnly = true; retVal = service.mutate(allOperations.ToArray()); } catch (AdWordsApiException e) { ApiException innerException = e.ApiException as ApiException; if (innerException == null) { throw new Exception("Failed to retrieve ApiError. See inner exception for more " + "details.", e); } // 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 e) { throw new System.ApplicationException("Failed to create ads.", e); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group that contains the criterion. /// </param> /// <param name="criterionId">Id of the keyword for which the ad /// parameters are set.</param> public void Run(AdWordsUser user, long adGroupId, long criterionId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService( AdWordsService.v201802.AdGroupAdService)) using (AdParamService adParamService = (AdParamService)user.GetService( AdWordsService.v201802.AdParamService)) { // Create the expanded text ad. ExpandedTextAd expandedTextAd = new ExpandedTextAd { headlinePart1 = "Mars Cruises", headlinePart2 = "Low-gravity fun for {param1:cheap}.", description = "Only {param2:a few} seats left!", finalUrls = new string[] { "http://www.example.com" } }; AdGroupAd adOperand = new AdGroupAd { adGroupId = adGroupId, status = AdGroupAdStatus.ENABLED, ad = expandedTextAd }; // Create the operation. AdGroupAdOperation adOperation = new AdGroupAdOperation { operand = adOperand, @operator = Operator.ADD }; // Create the text ad. AdGroupAdReturnValue retVal = adGroupAdService.mutate( new AdGroupAdOperation[] { adOperation }); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { Console.WriteLine("Expanded text ad with id ='{0}' was successfully added.", retVal.value[0].ad.id); } else { throw new System.ApplicationException("Failed to create expanded text ads."); } // Create the ad param for price. AdParam priceParam = new AdParam { adGroupId = adGroupId, criterionId = criterionId, paramIndex = 1, insertionText = "$100" }; // Create the ad param for seats. AdParam seatParam = new AdParam { adGroupId = adGroupId, criterionId = criterionId, paramIndex = 2, insertionText = "50" }; // Create the operations. AdParamOperation priceOperation = new AdParamOperation { @operator = Operator.SET, operand = priceParam }; AdParamOperation seatOperation = new AdParamOperation { @operator = Operator.SET, operand = seatParam }; try { // Set the ad parameters. AdParam[] newAdParams = adParamService.mutate(new AdParamOperation[] { priceOperation, seatOperation }); // Display the results. if (newAdParams != null) { Console.WriteLine("Ad parameters were successfully updated."); } else { Console.WriteLine("No ad parameters were set."); } } catch (Exception e) { throw new System.ApplicationException("Failed to set ad parameters.", e); } } }