/// <summary> /// Creates text ads that use ad customizations for the specified ad group /// IDs. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupIds">IDs of the ad groups to which customized ads /// are added.</param> /// <param name="feedName">Name of the feed to be used.</param> private static void CreateAdsWithCustomizations(AdWordsUser user, long[] adGroupIds, string feedName) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService( AdWordsService.v201708.AdGroupAdService)) { ExpandedTextAd expandedTextAd = new ExpandedTextAd() { headlinePart1 = string.Format("Luxury Cruise to {{={0}.Name}}", feedName), headlinePart2 = string.Format("Only {{={0}.Price}}", feedName), description = string.Format("Offer ends in {{=countdown({0}.Date)}}!", feedName), finalUrls = new string[] { "http://www.example.com" } }; // We add the same ad to both ad groups. When they serve, they will show // different values, since they match different feed items. List <AdGroupAdOperation> adGroupAdOperations = new List <AdGroupAdOperation>(); foreach (long adGroupId in adGroupIds) { AdGroupAd adGroupAd = new AdGroupAd() { adGroupId = adGroupId, ad = expandedTextAd }; AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation() { operand = adGroupAd, @operator = Operator.ADD }; adGroupAdOperations.Add(adGroupAdOperation); } AdGroupAdReturnValue adGroupAdReturnValue = adGroupAdService.mutate( adGroupAdOperations.ToArray()); foreach (AdGroupAd addedAd in adGroupAdReturnValue.value) { Console.WriteLine("Created an ad with ID {0}, type '{1}' and status '{2}'.", addedAd.ad.id, addedAd.ad.AdType, addedAd.status); } } }
/// <summary> /// Creates an expanded Dynamic Search Ad. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">ID of the ad group in which ad is created.</param> /// <returns>The newly created ad.</returns> private static ExpandedDynamicSearchAd CreateExpandedDSA(AdWordsUser user, long adGroupId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201806.AdGroupAdService)) { // Create an Expanded Dynamic Search Ad. This ad will have its headline, display URL and // final URL auto-generated at serving time according to domain name specific information // provided by DynamicSearchAdsSetting at the campaign level. ExpandedDynamicSearchAd expandedDSA = new ExpandedDynamicSearchAd { // Set the ad description. description = "Buy your tickets now!" }; // Create the ad group ad. AdGroupAd adGroupAd = new AdGroupAd { adGroupId = adGroupId, ad = expandedDSA, // Optional: Set the status. status = AdGroupAdStatus.PAUSED }; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation { @operator = Operator.ADD, operand = adGroupAd }; try { // Create the ad. AdGroupAdReturnValue retval = adGroupAdService.mutate( new AdGroupAdOperation[] { operation }); // Display the results. AdGroupAd newAdGroupAd = retval.value[0]; ExpandedDynamicSearchAd newAd = newAdGroupAd.ad as ExpandedDynamicSearchAd; Console.WriteLine("Expanded Dynamic Search Ad with ID '{0}' and description '{1}' " + "was added.", newAd.id, newAd.description); return(newAd); } catch (Exception e) { throw new System.ApplicationException("Failed to create Expanded Dynamic Search Ad.", e); } } }
/// <summary> /// Creates the Showcase ad. /// </summary> /// <param name="user">The AdWords user for which the ad is created.</param> /// <param name="adGroup">The ad group in which the ad is created.</param> /// <returns>The newly created Showcase ad.</returns> private static AdGroupAd CreateShowcaseAd(AdWordsUser user, AdGroup adGroup) { AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService( AdWordsService.v201710.AdGroupAdService); // Create the Showcase ad. ShowcaseAd showcaseAd = new ShowcaseAd(); // Required: set the ad's name, final URLs and display URL. showcaseAd.name = "Showcase ad " + ExampleUtilities.GetShortRandomString(); showcaseAd.finalUrls = new string[] { "http://example.com/showcase" }; showcaseAd.displayUrl = "example.com"; // Required: Set the ad's expanded image. Image expandedImage = new Image(); expandedImage.mediaId = UploadImage(user, "https://goo.gl/IfVlpF"); showcaseAd.expandedImage = expandedImage; // Optional: Set the collapsed image. Image collapsedImage = new Image(); collapsedImage.mediaId = UploadImage(user, "https://goo.gl/NqTxAE"); showcaseAd.collapsedImage = collapsedImage; // Create ad group ad. AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.adGroupId = adGroup.id; adGroupAd.ad = showcaseAd; // Create operation. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.operand = adGroupAd; operation.@operator = Operator.ADD; // Make the mutate request. AdGroupAdReturnValue retval = adGroupAdService.mutate( new AdGroupAdOperation[] { operation }); adGroupAdService.Close(); 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 that contains the ad. /// </param> /// <param name="adId">Id of the ad to be paused.</param> public void Run(AdWordsUser user, long adGroupId, long adId) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService)user.GetService(AdWordsService.v201402.AdGroupAdService); AdGroupAdStatus status = AdGroupAdStatus.PAUSED; // Create the ad group ad. AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.status = status; adGroupAd.adGroupId = adGroupId; adGroupAd.ad = new Ad(); adGroupAd.ad.id = adId; // Create the operation. AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation(); adGroupAdOperation.@operator = Operator.SET; adGroupAdOperation.operand = adGroupAd; try { // Update the ad. AdGroupAdReturnValue retVal = service.mutate(new AdGroupAdOperation[] { adGroupAdOperation }); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { AdGroupAd pausedAdGroupAd = retVal.value[0]; Console.WriteLine("Ad with id \"{0}\" and ad group id \"{1}\"was paused.", pausedAdGroupAd.ad.id, pausedAdGroupAd.adGroupId); } else { Console.WriteLine("No ads were paused."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to pause ad.", ex); } }
/// <summary> /// Gets the ad group ad by ID. /// </summary> /// <param name="adGroupAdService">The AdGroupAdService instance.</param> /// <param name="adGroupId">ID of the ad group.</param> /// <param name="adId">ID of the ad to be retrieved.</param> /// <returns>The AdGroupAd if the item could be retrieved, null otherwise. /// </returns> private AdGroupAd GetAdGroupAd(AdGroupAdService adGroupAdService, long adGroupId, long adId) { // Create a selector. Selector selector = new Selector() { fields = new string[] { Ad.Fields.Id, Ad.Fields.Url }, predicates = new Predicate[] { // Restrict the fetch to only the selected ad group ID and ad ID. Predicate.Equals(AdGroupAd.Fields.AdGroupId, adGroupId), Predicate.Equals(Ad.Fields.Id, adId) } }; // Get the ad. AdGroupAdPage page = adGroupAdService.get(selector); if (page != null && page.entries != null && page.entries.Length > 0) { return page.entries[0]; } else { return null; } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">ID of the ad group that contains the ad.</param> /// <param name="adId">ID of the ad to be upgraded.</param> public void Run(AdWordsUser user, long adGroupId, long adId) { // Get the AdGroupAdService. AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService(AdWordsService.v201603.AdGroupAdService); try { // Retrieve the Ad. AdGroupAd adGroupAd = GetAdGroupAd(adGroupAdService, adGroupId, adId); if (adGroupAd == null) { Console.WriteLine("Ad not found."); return; } // Copy the destination url to the final url. AdUrlUpgrade upgradeUrl = new AdUrlUpgrade(); upgradeUrl.adId = adGroupAd.ad.id; upgradeUrl.finalUrl = adGroupAd.ad.url; // Upgrade the ad. Ad[] upgradedAds = adGroupAdService.upgradeUrl(new AdUrlUpgrade[] { upgradeUrl }); // Display the results. if (upgradedAds != null && upgradedAds.Length > 0) { foreach (Ad upgradedAd in upgradedAds) { Console.WriteLine("Ad with id = {0} and destination url = {1} was upgraded.", upgradedAd.id, upgradedAd.finalUrls[0]); } } else { Console.WriteLine("No ads were upgraded."); } } catch (Exception e) { throw new System.ApplicationException("Failed to upgrade ads.", e); } }
/// <summary> /// Creates text ads that use ad customizations for the specified ad group /// IDs. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupIds">IDs of the ad groups to which customized ads /// are added.</param> /// <param name="feedName">Name of the feed to be used.</param> private static void CreateAdsWithCustomizations(AdWordsUser user, long[] adGroupIds, string feedName) { // Get the AdGroupAdService. AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService( AdWordsService.v201406.AdGroupAdService); TextAd textAd = new TextAd(); textAd.headline = string.Format("Luxury Cruise to {{={0}.Name}}", feedName); textAd.description1 = string.Format("Only {{={0}.Price}}", feedName); textAd.description2 = string.Format("Offer ends in {{=countdown({0}.Date)}}!", feedName); textAd.url = "http://www.example.com"; textAd.displayUrl = "www.example.com"; // We add the same ad to both ad groups. When they serve, they will show // different values, since they match different feed items. List <AdGroupAdOperation> adGroupAdOperations = new List <AdGroupAdOperation>(); foreach (long adGroupId in adGroupIds) { AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.adGroupId = adGroupId; adGroupAd.ad = textAd; AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation(); adGroupAdOperation.operand = adGroupAd; adGroupAdOperation.@operator = Operator.ADD; adGroupAdOperations.Add(adGroupAdOperation); } AdGroupAdReturnValue adGroupAdReturnValue = adGroupAdService.mutate( adGroupAdOperations.ToArray()); foreach (AdGroupAd addedAd in adGroupAdReturnValue.value) { Console.WriteLine("Created an ad with ID {0}, type '{1}' and status '{2}'.", addedAd.ad.id, addedAd.ad.AdType, addedAd.status); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group that contains the ad.</param> /// <param name="adId">Id of the ad being removed.</param> public void Run(AdWordsUser user, long adGroupId, long adId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService( AdWordsService.v201708.AdGroupAdService)) { // Since we do not need to update any ad-specific fields, it is enough to // create the base type. Ad ad = new Ad(); ad.id = adId; // Create the ad group ad. AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.adGroupId = adGroupId; adGroupAd.ad = ad; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.operand = adGroupAd; operation.@operator = Operator.REMOVE; try { // Remove the ad. AdGroupAdReturnValue retVal = adGroupAdService.mutate( new AdGroupAdOperation[] { operation }); if (retVal != null && retVal.value != null && retVal.value.Length > 0) { AdGroupAd removedAdGroupAd = retVal.value[0]; Console.WriteLine("Ad with id = \"{0}\" and type = \"{1}\" was removed.", removedAdGroupAd.ad.id, removedAdGroupAd.ad.AdType); } else { Console.WriteLine("No ads were removed."); } } catch (Exception e) { throw new System.ApplicationException("Failed to remove ad.", e); } } }
/// <summary> /// Creates a test ThirdPartyRedirectAd for running further tests. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">The adgroup id for which the ad is created. /// </param> /// <returns>The text ad id.</returns> public long CreateThirdPartyRedirectAd(AdWordsUser user, long adGroupId) { AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201806.AdGroupAdService); AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation(); adGroupAdOperation.@operator = Operator.ADD; adGroupAdOperation.operand = new AdGroupAd(); adGroupAdOperation.operand.adGroupId = adGroupId; // Create the third party redirect ad. ThirdPartyRedirectAd redirectAd = new ThirdPartyRedirectAd(); redirectAd.name = string.Format("Example third party ad #{0}", this.GetTimeStamp()); redirectAd.url = "http://www.example.com"; redirectAd.dimensions = new Dimensions(); redirectAd.dimensions.height = 250; redirectAd.dimensions.width = 300; // This field normally contains the javascript ad tag. redirectAd.snippet = "<img src=\"http://www.google.com/intl/en/adwords/select/images/samples/inline.jpg\"/>"; redirectAd.impressionBeaconUrl = "http://www.examples.com/beacon"; redirectAd.certifiedVendorFormatId = 119; redirectAd.isCookieTargeted = false; redirectAd.isUserInterestTargeted = false; redirectAd.isTagged = false; adGroupAdOperation.operand.ad = redirectAd; AdGroupAdReturnValue retVal = adGroupAdService.mutate(new AdGroupAdOperation[] { adGroupAdOperation }); return(retVal.value[0].ad.id); }
/// <summary> /// Creates a test expanded text ad for running further tests. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">The adgroup id for which the ad is created. /// </param> /// <param name="hasAdParam">True, if an ad param placeholder should be /// added.</param> /// <returns>The expanded text ad id.</returns> public long CreateExpandedTextAd(AdWordsUser user, long adGroupId, bool hasAdParam) { AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201806.AdGroupAdService); AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation(); adGroupAdOperation.@operator = Operator.ADD; adGroupAdOperation.operand = new AdGroupAd(); adGroupAdOperation.operand.adGroupId = adGroupId; ExpandedTextAd expandedTextAd = new ExpandedTextAd(); expandedTextAd.headlinePart1 = "Luxury Cruise to Mars"; expandedTextAd.headlinePart2 = "Best Space Cruise Line"; expandedTextAd.description = "Buy your tickets now!"; if (hasAdParam) { expandedTextAd.description = "Low-gravity fun for {param1:cheap}!"; } else { expandedTextAd.description = "Low-gravity fun for everyone!"; } expandedTextAd.finalUrls = new string[] { "http://www.example.com/" }; adGroupAdOperation.operand.ad = expandedTextAd; AdGroupAdReturnValue retVal = adGroupAdService.mutate(new AdGroupAdOperation[] { adGroupAdOperation }); return(retVal.value[0].ad.id); }
/// <summary> /// Creates the Product Ad. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">The ad group ID.</param> /// <returns>The Product Ad.</returns> private static AdGroupAd CreateProductAd(AdWordsUser user, long adGroupId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService( AdWordsService.v201802.AdGroupAdService)) { // Create product ad. ProductAd productAd = new ProductAd(); // Create ad group ad. AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.adGroupId = adGroupId; 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> /// 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 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> /// 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 from which text ads are /// retrieved.</param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService)user.GetService(AdWordsService.v201609.AdGroupAdService); // Create a selector. Selector selector = new Selector() { fields = new string[] { TextAd.Fields.Id, AdGroupAd.Fields.Status, TextAd.Fields.Headline, TextAd.Fields.Description1, TextAd.Fields.Description2, TextAd.Fields.DisplayUrl }, ordering = new OrderBy[] { OrderBy.Asc(TextAd.Fields.Id) }, predicates = new Predicate[] { // Restrict the fetch to only the selected ad group id. Predicate.Equals(AdGroupAd.Fields.AdGroupId, adGroupId), // Retrieve only text ads. Predicate.Equals("AdType", "TEXT_AD"), // By default disabled ads aren't returned by the selector. To return // them include the DISABLED status in the statuses field. Predicate.In(AdGroupAd.Fields.Status, new string[] { AdGroupAdStatus.ENABLED.ToString(), AdGroupAdStatus.PAUSED.ToString(), AdGroupAdStatus.DISABLED.ToString() }) }, paging = Paging.Default }; AdGroupAdPage page = new AdGroupAdPage(); try { do { // Get the text ads. page = service.get(selector); // Display the results. if (page != null && page.entries != null) { int i = selector.paging.startIndex; foreach (AdGroupAd adGroupAd in page.entries) { TextAd textAd = (TextAd)adGroupAd.ad; Console.WriteLine("{0}) Ad id is {1} and status is {2}", i + 1, textAd.id, adGroupAd.status); Console.WriteLine(" {0}\n {1}\n {2}\n {3}", textAd.headline, textAd.description1, textAd.description2, textAd.displayUrl); i++; } } selector.paging.IncreaseOffset(); } while (selector.paging.startIndex < page.totalNumEntries); Console.WriteLine("Number of text ads found: {0}", page.totalNumEntries); } catch (Exception e) { throw new System.ApplicationException("Failed to get text ads", e); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">Id of the campaign for which disapproved ads /// are retrieved.</param> public void Run(AdWordsUser user, long campaignId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201802.AdGroupAdService)) { // Create the selector. Selector selector = new Selector() { fields = new string[] { Ad.Fields.Id, AdGroupAd.Fields.PolicySummary }, predicates = new Predicate[] { Predicate.Equals(AdGroup.Fields.CampaignId, campaignId), Predicate.Equals(AdGroupAdPolicySummary.Fields.CombinedApprovalStatus, PolicyApprovalStatus.DISAPPROVED.ToString()) }, paging = Paging.Default }; AdGroupAdPage page = new AdGroupAdPage(); int disapprovedAdsCount = 0; try { do { // Get the disapproved ads. page = adGroupAdService.get(selector); // Display the results. if (page != null && page.entries != null) { foreach (AdGroupAd adGroupAd in page.entries) { AdGroupAdPolicySummary policySummary = adGroupAd.policySummary; disapprovedAdsCount++; Console.WriteLine("Ad with ID {0} and type '{1}' was disapproved with the " + "following policy topic entries: ", adGroupAd.ad.id, adGroupAd.ad.AdType); // Display the policy topic entries related to the ad disapproval. foreach (PolicyTopicEntry policyTopicEntry in policySummary.policyTopicEntries) { Console.WriteLine(" topic id: {0}, topic name: '{1}'", policyTopicEntry.policyTopicId, policyTopicEntry.policyTopicName); // Display the attributes and values that triggered the policy topic. if (policyTopicEntry.policyTopicEvidences != null) { foreach (PolicyTopicEvidence evidence in policyTopicEntry.policyTopicEvidences) { Console.WriteLine(" evidence type: {0}", evidence.policyTopicEvidenceType); if (evidence.evidenceTextList != null) { for (int i = 0; i < evidence.evidenceTextList.Length; i++) { Console.WriteLine(" evidence text[{0}]: {1}", i, evidence.evidenceTextList[i]); } } } } } } } selector.paging.IncreaseOffset(); } while (selector.paging.startIndex < page.totalNumEntries); Console.WriteLine("Number of disapproved ads found: {0}", disapprovedAdsCount); } catch (Exception e) { throw new System.ApplicationException("Failed to get disapproved ads.", 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.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.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 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); } }
/// <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 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.v201806.AdGroupAdService)) { // Create the template ad. TemplateAd clickToDownloadAppAd = new TemplateAd { name = "Ad for demo game", templateId = 353, finalUrls = new string[] { "http://play.google.com/store/apps/details?id=com.example.demogame" }, 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 { name = "headline", fieldText = "Enjoy your drive in Mars", type = TemplateElementFieldType.TEXT }; TemplateElementField description1 = new TemplateElementField { name = "description1", fieldText = "Realistic physics simulation", type = TemplateElementFieldType.TEXT }; TemplateElementField description2 = new TemplateElementField { name = "description2", fieldText = "Race against players online", type = TemplateElementFieldType.TEXT }; TemplateElementField appId = new TemplateElementField { name = "appId", fieldText = "com.example.demogame", type = TemplateElementFieldType.TEXT }; TemplateElementField appStore = new TemplateElementField { name = "appStore", fieldText = "2", 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", user.Config); Image image = new Image { data = imageData }; TemplateElementField landscapeImage = new TemplateElementField { name = "landscapeImage", fieldMedia = image, type = TemplateElementFieldType.IMAGE }; TemplateElement adData = new TemplateElement { uniqueName = "adData", fields = new TemplateElementField[] { headline, description1, description2, appId, appStore, landscapeImage } }; clickToDownloadAppAd.templateElements = new TemplateElement[] { adData }; // Create the adgroupad. AdGroupAd clickToDownloadAppAdGroupAd = new AdGroupAd { adGroupId = adGroupId, ad = clickToDownloadAppAd, // Optional: Set the status. status = AdGroupAdStatus.PAUSED }; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation { @operator = Operator.ADD, 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); } } }
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> /// 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 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> /// 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 ad group from which text ads are /// retrieved.</param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService)user.GetService(AdWordsService.v201402.AdGroupAdService); // Create a selector. Selector selector = new Selector(); selector.fields = new string[] { "Id", "Status", "Headline", "Description1", "Description2", "DisplayUrl" }; // Set the sort order. OrderBy orderBy = new OrderBy(); orderBy.field = "Id"; orderBy.sortOrder = SortOrder.ASCENDING; selector.ordering = new OrderBy[] { orderBy }; // Restrict the fetch to only the selected ad group id. Predicate adGroupPredicate = new Predicate(); adGroupPredicate.field = "AdGroupId"; adGroupPredicate.@operator = PredicateOperator.EQUALS; adGroupPredicate.values = new string[] { adGroupId.ToString() }; // Retrieve only text ads. Predicate typePredicate = new Predicate(); typePredicate.field = "AdType"; typePredicate.@operator = PredicateOperator.EQUALS; typePredicate.values = new string[] { "TEXT_AD" }; // By default disabled ads aren't returned by the selector. To return // them include the DISABLED status in the statuses field. Predicate statusPredicate = new Predicate(); statusPredicate.field = "Status"; statusPredicate.@operator = PredicateOperator.IN; statusPredicate.values = new string[] { AdGroupAdStatus.ENABLED.ToString(), AdGroupAdStatus.PAUSED.ToString(), AdGroupAdStatus.DISABLED.ToString() }; selector.predicates = new Predicate[] { adGroupPredicate, statusPredicate, typePredicate }; // Select the selector paging. selector.paging = new Paging(); int offset = 0; int pageSize = 500; AdGroupAdPage page = new AdGroupAdPage(); try { do { selector.paging.startIndex = offset; selector.paging.numberResults = pageSize; // Get the text ads. page = service.get(selector); // Display the results. if (page != null && page.entries != null) { int i = offset; foreach (AdGroupAd adGroupAd in page.entries) { TextAd textAd = (TextAd)adGroupAd.ad; Console.WriteLine("{0}) Ad id is {1} and status is {2}", i + 1, textAd.id, adGroupAd.status); Console.WriteLine(" {0}\n {1}\n {2}\n {3}", textAd.headline, textAd.description1, textAd.description2, textAd.displayUrl); i++; } } offset += pageSize; } while (offset < page.totalNumEntries); Console.WriteLine("Number of text ads found: {0}", page.totalNumEntries); } catch (Exception ex) { throw new System.ApplicationException("Failed to get text 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) { // 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="campaignId">Id of the campaign for which disapproved ads /// are retrieved.</param> public void Run(AdWordsUser user, long campaignId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201802.AdGroupAdService)) { // Get all the disapproved ads for this campaign. string query = string.Format("SELECT Id, PolicySummary WHERE CampaignId = {0} and " + "CombinedApprovalStatus = DISAPPROVED ORDER BY Id", campaignId); int offset = 0; int pageSize = 500; AdGroupAdPage page = new AdGroupAdPage(); int disapprovedAdsCount = 0; try { do { string queryWithPaging = string.Format("{0} LIMIT {1}, {2}", query, offset, pageSize); // Get the disapproved ads. page = adGroupAdService.query(queryWithPaging); // Display the results. if (page != null && page.entries != null) { foreach (AdGroupAd adGroupAd in page.entries) { AdGroupAdPolicySummary policySummary = adGroupAd.policySummary; disapprovedAdsCount++; Console.WriteLine("Ad with ID {0} and type '{1}' was disapproved with the " + "following policy topic entries: ", adGroupAd.ad.id, adGroupAd.ad.AdType); // Display the policy topic entries related to the ad disapproval. foreach (PolicyTopicEntry policyTopicEntry in policySummary.policyTopicEntries) { Console.WriteLine(" topic id: {0}, topic name: '{1}'", policyTopicEntry.policyTopicId, policyTopicEntry.policyTopicName); // Display the attributes and values that triggered the policy topic. if (policyTopicEntry.policyTopicEvidences != null) { foreach (PolicyTopicEvidence evidence in policyTopicEntry.policyTopicEvidences) { Console.WriteLine(" evidence type: {0}", evidence.policyTopicEvidenceType); if (evidence.evidenceTextList != null) { for (int i = 0; i < evidence.evidenceTextList.Length; i++) { Console.WriteLine(" evidence text[{0}]: {1}", i, evidence.evidenceTextList[i]); } } } } } } } offset += pageSize; } while (offset < page.totalNumEntries); Console.WriteLine("Number of disapproved ads found: {0}", disapprovedAdsCount); } catch (Exception e) { throw new System.ApplicationException("Failed to get disapproved ads.", 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 adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201506.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; 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.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) { // 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); } }