/// <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) { // Get the AdGroupAdService. AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService(AdWordsService.v201509.AdGroupAdService); // Set the validateOnly headers. adGroupAdService.RequestHeader.validateOnly = true; // Create your 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; AdGroupAdOperation textAdOperation = new AdGroupAdOperation(); textAdOperation.@operator = Operator.ADD; textAdOperation.operand = textAdGroupAd; try { AdGroupAdReturnValue retVal = adGroupAdService.mutate( (new AdGroupAdOperation[] {textAdOperation})); // Since validation is ON, result will be null. Console.WriteLine("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 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 text ad.", 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 ad.</param> /// <param name="adId">Id of the ad being removed.</param> public void Run(AdWordsUser user, long adGroupId, long adId) { // Get the AdGroupAdService. AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService( AdWordsService.v201509.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> /// 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.v201509.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 e) { throw new System.ApplicationException("Failed to pause 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 ad is added. /// </param> public void Run(AdWordsUser user, long adGroupId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201809.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 { key = "season", value = "christmas" }; CustomParameter promoCodeParameter = new CustomParameter { key = "promocode", value = "NYC123" }; expandedTextAd.urlCustomParameters = new CustomParameters { 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 { adGroupId = adGroupId, ad = expandedTextAd, // Optional: Set the status. status = AdGroupAdStatus.PAUSED }; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation { @operator = Operator.ADD, operand = adGroupAd }; AdGroupAdReturnValue retVal = null; try { // Create the ads. retVal = adGroupAdService.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) { // Get the AdGroupAdService. AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService(AdWordsService.v201509.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> /// Builds the operation for creating an ad within an ad group. /// </summary> /// <param name="adGroupId">ID of the ad group for which ads are created.</param> /// <returns>A list of operations for creating ads.</returns> private static List<AdGroupAdOperation> BuildAdGroupAdOperations(long adGroupId) { List<AdGroupAdOperation> operations = new List<AdGroupAdOperation>(); AdGroupAd adGroupAd = new AdGroupAd() { adGroupId = adGroupId, ad = new TextAd() { headline = "Luxury Cruise to Mars", description1 = "Visit the Red Planet in style.", description2 = "Low-gravity fun for everyone!", displayUrl = "www.example.com", finalUrls = new String[] { "http://www.example.com/1" } } }; AdGroupAdOperation operation = new AdGroupAdOperation() { operand = adGroupAd, @operator = Operator.ADD }; operations.Add(operation); return operations; }
/// <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.v201509.AdGroupAdService); // Get the AdParamService. AdParamService adParamService = (AdParamService) user.GetService( AdWordsService.v201509.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 ad is added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService) user.GetService(AdWordsService.v201601.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"; // Specify a tracking URL for 3rd party tracking provider. You may // specify one at customer, campaign, ad group, ad, criterion or // feed item levels. textAd.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"; textAd.urlCustomParameters = new CustomParameters(); textAd.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. textAd.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. textAd.finalMobileUrls = new string[] { "http://mobile.example.com/cruise/space/", "http://mobile.example.com/locations/mars/" }; 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; AdGroupAdReturnValue retVal = null; try { // Create the ads. retVal = service.mutate(new AdGroupAdOperation[] { operation }); // Display the results. if (retVal != null && retVal.value != null) { AdGroupAd newAdGroupAd = retVal.value[0]; Console.WriteLine("New text ad with ID = {0} and display URL = \"{1}\" was " + "created.", newAdGroupAd.ad.id, newAdGroupAd.ad.displayUrl); Console.WriteLine("Upgraded URL properties:"); TextAd newTextAd = (TextAd) newAdGroupAd.ad; Console.WriteLine(" Final URLs: {0}", string.Join(", ", newTextAd.finalUrls)); Console.WriteLine(" Final Mobile URLs: {0}", string.Join(", ", newTextAd.finalMobileUrls)); Console.WriteLine(" Tracking URL template: {0}", newTextAd.trackingUrlTemplate); Console.WriteLine(" Final App URLs: {0}", string.Join(", ", newTextAd.finalAppUrls.Select(finalAppUrl => finalAppUrl.url).ToArray())); List<string> parameters = new List<string>(); foreach (CustomParameter customParam in newTextAd.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 text ads were created."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create text ad.", e); } }
/// <summary> /// /// </summary> /// <param name="UseSandbox"></param> /// <param name="Name"></param> /// <param name="Countries"></param> /// <param name="Languages"></param> /// <param name="BudgetPeriod"></param> /// <param name="BudgetAmount"></param> /// <param name="MaxAdGroups"></param> /// <param name="DisplayUrl"></param> /// <param name="destinationUrlPrefix"></param> public void CreateCampaignByKeywordDensityContentMatch(bool UseSandbox, Guid AffiliateSiteRefId, int BudgetPeriod, Moneyv200906 BudgetAmount, AdGroupCriterionMoneyv200906 KeywordMaxCpc, string DisplayUrl, int MaxAdGroups, int AdKeywordType, int MinKeywordDensity, int MaxKeywordDensity, int MinContentMatch, decimal maxApiUsageDollars) { // Create a user (reads headers from App.config file). AdWordsUser user = new AdWordsUser(); if (UseSandbox) user.UseSandbox(); // use sandbox AccountService accountService = (AccountService)user.GetService(ApiServices.v13.AccountService); string[] accounts = accountService.getClientAccounts(); try { #region Create Campaign PpcNetwork ppcNetwork = DataRepository.PpcNetworkProvider.GetByName("AdWords"); TList<PpcCampaign> Campaigns = DataRepository.PpcCampaignProvider.GetByPpcNetworkRefId(ppcNetwork.PpcNetworkRefId); foreach (PpcCampaign campaign in Campaigns) { // Target the campaign at CampaignServicev200906 campaignService = (com.google.api.adwords.v200906.CampaignService.CampaignService) user.GetService(ApiServices.v200906.CampaignService); // Create a new campaign with an ad group. First create a // campaign, so we can get its id. Campaignv200906 newCampaign = new Campaignv200906(); // The campaign name is optional. An error results if a campaign // of the same name already exists. newCampaign.name = campaign.CampaignName + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(); // Set the campaign status to paused, we don't want to start // paying for this test. // Required: Set the campaign status. newCampaign.status = CampaignStatusv200906.ACTIVE; newCampaign.statusSpecified = true; // Required: Specify the currency and budget amount. Budget budget = new Budget(); BudgetAmount.microAmountSpecified = true; budget.amount = BudgetAmount; // Required: Specify the bidding strategy. newCampaign.biddingStrategy = new ManualCPC(); // Optional: Specify the budget period and delivery method. budget.periodSpecified = true; budget.period = BudgetBudgetPeriod.DAILY; budget.deliveryMethodSpecified = true; budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD; newCampaign.budget = budget; // Optional: Specify an endDate for the campaign. newCampaign.endDate = DateTime.Now.AddDays(campaign.DurationInDays).ToString("yyyyMMdd"); // Define an Add operation to add the campaign. CampaignOperation campaignOperation = new CampaignOperation(); campaignOperation.operatorSpecified = true; campaignOperation.@operator = CampaignOperatorv200906.ADD; campaignOperation.operand = newCampaign; try { CampaignReturnValue results = campaignService.mutate(new CampaignOperation[] { campaignOperation }); if (results != null && results.value != null && results.value.Length > 0) { newCampaign.id = results.value[0].id; newCampaign.idSpecified = true; Trace.TraceInformation( "New campaign with name = \"{0}\" and id = " + "\"{1}\" was created.", results.value[0].name, results.value[0].id); } } catch (Exception ex) { Trace.TraceError("Error:" + ex.Message); throw new Exception("Failed to create campaign. " + ex.Message); } #endregion #region Targeting CampaignTargetService service = (CampaignTargetService)user.GetService(ApiServices.v200906.CampaignTargetService); // Create a language target - for English language. LanguageTargetv200906 languageTarget = new LanguageTargetv200906(); languageTarget.languageCode = "en"; //TODO: Add as property LanguageTargetList languageTargetList = new LanguageTargetList(); languageTargetList.targets = new LanguageTargetv200906[] { languageTarget }; languageTargetList.campaignId = newCampaign.id; languageTargetList.campaignIdSpecified = true; // Create a country target - include US, exclude metrocode 743. CountryTargetv200906 countryTarget = new CountryTargetv200906(); countryTarget.countryCode = campaign.TargetCountry; countryTarget.excludedSpecified = true; countryTarget.excluded = false; MetroTargetv200906 metroTarget = new MetroTargetv200906(); metroTarget.excludedSpecified = true; metroTarget.excluded = true; metroTarget.metroCode = campaign.ExcludeMetroTarget; GeoTargetList geoTargetList = new GeoTargetList(); geoTargetList.targets = new GeoTargetv200906[] { countryTarget, metroTarget }; geoTargetList.campaignId = newCampaign.id; geoTargetList.campaignIdSpecified = true; // Create a network target - Google Search. NetworkTargetv200906 networkTarget1 = new NetworkTargetv200906(); networkTarget1.networkCoverageTypeSpecified = true; networkTarget1.networkCoverageType = NetworkCoverageTypev200906.GOOGLE_SEARCH; NetworkTargetv200906 networkTarget2 = new NetworkTargetv200906(); networkTarget2.networkCoverageTypeSpecified = true; networkTarget2.networkCoverageType = NetworkCoverageTypev200906.SEARCH_NETWORK; NetworkTargetList networkTargetList = new NetworkTargetList(); networkTargetList.targets = new NetworkTargetv200906[] { networkTarget1, networkTarget2 }; networkTargetList.campaignId = newCampaign.id; networkTargetList.campaignIdSpecified = true; TargetList[] targets = new TargetList[] { languageTargetList, geoTargetList, networkTargetList }; ArrayList campaignTargetOperations = new ArrayList(); foreach (TargetList target in targets) { CampaignTargetOperation ops = new CampaignTargetOperation(); ops.operatorSpecified = true; ops.@operator = CampaignTargetOperatorv200906.SET; ops.operand = target; campaignTargetOperations.Add(ops); } try { service.mutate((CampaignTargetOperation[]) campaignTargetOperations.ToArray(typeof(CampaignTargetOperation))); Trace.TraceInformation("Geo, language, and network targeting were " + "successfully added to campaign id = \"{0}\".", newCampaign.id); } catch (Exception ex) { Trace.TraceError("Failed to create campaign targeting. " + "Exception says \"{0}\"", ex.Message); } #endregion #region Create your Services //create your services List<SeedKeyword> keywords = new List<SeedKeyword>(); AdGroupAdServicev200906 adService = (AdGroupAdServicev200906)user.GetService(ApiServices.v200906.AdGroupAdService); KeywordToolService keywordToolService = (KeywordToolService)user.GetService(ApiServices.v13.KeywordToolService); AdGroupServicev200906 adgroupService = (AdGroupServicev200906)user.GetService(ApiServices.v200906.AdGroupService); TrafficEstimatorService trafficEstimatorService = (TrafficEstimatorService)user.GetService(ApiServices.v13.TrafficEstimatorService); #endregion #region Enumerate thru all the keywords by category AdGroupv200906 newAdGroup = null; foreach ( SiteCategory siteCategory in DataRepository.SiteCategoryProvider.GetByAffiliateSiteRefId(AffiliateSiteRefId)) { int adGroupCnt = 1; //enumerate thru all the keywords foreach ( KeywordUrLsDistinct keywordUrLsDistinct in DataRepository.KeywordUrLsDistinctProvider.GetBySiteCategoryRefId( siteCategory.SiteCategoryRefId)) { VList<KeywordDensity> keywordDensityList = DataRepository.KeywordDensityProvider.GetURLKeywordDensity(keywordUrLsDistinct.Url, MinKeywordDensity, MaxKeywordDensity). FindAllDistinct("SiteContent"); int GroupAdCount = 0; //check the avg keyword density if (keywordDensityList.Count >= MinContentMatch) { if (adGroupCnt == 1) { #region Ad AdGroup if (GroupAdCount >= MaxAdGroups) break; //Create an ad group by site category newAdGroup = new AdGroupv200906(); newAdGroup.name = siteCategory.Name; newAdGroup.campaignId = newCampaign.id; newAdGroup.campaignIdSpecified = true; //newAdGroup.campaignName = newCampaign.name; // Optional: set the status of adgroup. newAdGroup.statusSpecified = true; newAdGroup.status = AdGroupStatus.ENABLED; // Optional: Create a Manual CPC Bid. ManualCPCAdGroupBids bids = new ManualCPCAdGroupBids(); // Set the keyword content max cpc. bids.keywordContentMaxCpc = new Bid(); Money kwdContentMaxCpc = new Money(); kwdContentMaxCpc.microAmountSpecified = true; kwdContentMaxCpc.microAmount = KeywordMaxCpc.microAmount; bids.keywordContentMaxCpc.amount = kwdContentMaxCpc; // Set the keyword max cpc. bids.keywordMaxCpc = new Bid(); Money kwdMaxCpc = new Money(); kwdMaxCpc.microAmountSpecified = true; kwdMaxCpc.microAmount = KeywordMaxCpc.microAmount; bids.keywordMaxCpc.amount = kwdMaxCpc; // Set the manual bid to the adgroup. newAdGroup.bids = bids; AdGroupOperation adGroupOperation = new AdGroupOperation(); adGroupOperation.operatorSpecified = true; adGroupOperation.@operator = AddGroupOperatorv200906.ADD; adGroupOperation.operand = newAdGroup; try { AdGroupReturnValue results = adgroupService.mutate(new AdGroupOperation[] { adGroupOperation }); if (results != null && results.value != null && results.value.Length > 0) { newAdGroup.id = results.value[0].id; newAdGroup.idSpecified = true; Trace.TraceInformation( "New ad group with name = \"{0}\" and id = \"{1}\" was created.", results.value[0].name, results.value[0].id); } } catch (Exception ex) { Trace.TraceError("Failed to create ad group. Exception says \"{0}\"", ex.Message); } adGroupCnt++; #endregion } Trace.TraceInformation(keywordUrLsDistinct.Url); //Create an add for each product // // IMPORTANT: create an ad before adding keywords! Else the // minCpc will have a higher value. TList<PpcAdTemplate> ppcAdTemplateList = DataRepository.PpcAdTemplateProvider.GetByPpcCampaignRefId(campaign.PpcCampaignRefId); foreach (var ppcAdTemplate in ppcAdTemplateList) { TextAdv200906 newTextAd = new TextAdv200906(); Product prod = DataRepository.ProductProvider.GetByProductRefId( (Guid)keywordUrLsDistinct.ProductRefId); newTextAd.headline = StringUtils.ScrubProdName(prod.Name); while (newTextAd.headline.Length > 25) { // if one word longer than 25 chars if (newTextAd.headline.LastIndexOf(" ") < 0) continue; newTextAd.headline = newTextAd.headline.Substring(0, newTextAd.headline.LastIndexOf(" ")). Substring( 0, newTextAd.headline.Substring(0, newTextAd.headline.LastIndexOf(" ")) . LastIndexOf(" ")); } newTextAd.description1 = ppcAdTemplate.AdLine1.Replace(KeywordToken, keywordDensityList[0].Keywords).Replace(ProductNameToken, newTextAd.headline); newTextAd.description2 = ppcAdTemplate.AdLine2; //} newTextAd.displayUrl = DisplayUrl; newTextAd.url = keywordUrLsDistinct.Url; //don't add it yet, there is a check below to see if it meets criteria //SeedKeyword[] keywordsArray = new SeedKeyword[] { new SeedKeyword() }; //keywordsArray = keywords.ToArray(); // Associate this ad group with the newly created campaign. Send // the request to add the new ad group. try { //we found a keyword that meets criteria so ad the new Ad. AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.adGroupId = newAdGroup.id; adGroupAd.adGroupIdSpecified = true; adGroupAd.ad = newTextAd; AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation(); adGroupAdOperation.operatorSpecified = true; adGroupAdOperation.@operator = AddGroupAdOperatorv200906.ADD; adGroupAdOperation.operand = adGroupAd; AdGroupAdReturnValue result = null; try { result = adService.mutate(new AdGroupAdOperation[] { adGroupAdOperation }); if (result.value != null && result.value.Length > 0) { foreach (AdGroupAd tempAdGroupAd in result.value) { Trace.TraceInformation( String.Format( "New text ad with headline = \"{0}\" and id = \"{1}\" was created.", ((TextAdv200906)tempAdGroupAd.ad).headline, tempAdGroupAd.ad.id)); } } } catch (Exception ex) { Trace.TraceError("Failed to create Ad(s). Exception says \"{0}\"", ex.Message); } GroupAdCount++; Trace.TraceInformation("Text ad" + GroupAdCount + ": " + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2); //Trace.TraceInformation("Text ad: " + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2); } catch { //do nothing Trace.TraceError("***Text ad Failed:" + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2); } } //Add the Product name as a whole phrase AdGroupCriterionServicev200906 criterionService = (AdGroupCriterionServicev200906) user.GetService(ApiServices.v200906.AdGroupCriterionService); foreach (KeywordDensity kd in keywordDensityList) { try { Keywordv200906 newKeyword = new Keywordv200906(); newKeyword.matchTypeSpecified = true; newKeyword.matchType = com.google.api.adwords.v200906.AdGroupCriterionService.KeywordMatchType. BROAD; newKeyword.text = kd.Keywords; BiddableAdGroupCriterion criterion = new BiddableAdGroupCriterion(); criterion.adGroupId = newAdGroup.id; criterion.adGroupIdSpecified = true; criterion.criterion = newKeyword; criterion.destinationUrl = kd.Url; //TODO: Use the Traffic Estimator to determine the // the maxCpc to use //newKeyword.maxCpc = KeywordMaxCpc; //newKeyword.maxCpcSpecified = true; var adGroupCriterionBids = new com.google.api.adwords.v200906.AdGroupCriterionService. ManualCPCAdGroupCriterionBids(); adGroupCriterionBids.maxCpc = new com.google.api.adwords.v200906.AdGroupCriterionService.Bid(); adGroupCriterionBids.maxCpc.amount = KeywordMaxCpc; criterion.bids = adGroupCriterionBids; AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation(); adGroupCriterionOperation.@operator = com.google.api.adwords.v200906.AdGroupCriterionService.Operator.ADD; adGroupCriterionOperation.operatorSpecified = true; adGroupCriterionOperation.operand = criterion; try { AdGroupCriterionReturnValue results = criterionService.mutate(new AdGroupCriterionOperation[] { adGroupCriterionOperation }); if (results != null && results.value != null && results.value.Length > 0) { Keywordv200906 result = results.value[0].criterion as Keywordv200906; Trace.TraceInformation( String.Format( "New keyword with text = \"{0}\" and id = \"{1}\" was created.", result.text, result.id)); } } catch (Exception ex) { Trace.TraceError( String.Format( "Failed to create keyword at Ad group level. Exception says \"{0}\"", ex.Message)); } } catch { //do nothing Trace.TraceError("***Add Criteria Failed: Keyword" + kd.Keywords); } } if (GroupAdCount >= MaxAdGroups) break; } } } #endregion } #region Check api usage // check api usage ApiUsage apiUsage = new ApiUsage(); APIQuotaValues aPIQuotaValues = apiUsage.GetApiUsage(UseSandbox); Trace.TraceInformation("FreeQuotaUsed:" + aPIQuotaValues.FreeQuotaUsed.ToString() + " FreeUnitsRemaining:" + aPIQuotaValues.FreeUnitsRemaining.ToString() + " SysDefinesQuotaCap:" + aPIQuotaValues.SysDefinesQuotaCap.ToString() + " TotalUsed:" + aPIQuotaValues.TotalUsed.ToString()); #endregion #region Log everything created //AdGroup[] adGroups = adgroupService.getAllAdGroups(campaignId); //foreach (AdGroup adGroup in adGroups) //{ // Trace.TraceInformation("Ad group: " + adGroup.name); // Ad[] ads = adService.getAllAds(new long[] { adGroup.id }); // foreach (Ad ad in ads) // { // if (ad is TextAd) // { // TextAd textAd = (TextAd)ad; // Trace.TraceInformation("Text ad: " + textAd.headline + " Text Line1:" + textAd.description1 + " Text Line2:" + textAd.description2); // } // } //} #endregion } catch (Exception ex) { Trace.TraceError("Error:" + ex.Message); throw ex; } }
/// <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> /// <param name="hasAdParam">True, if an ad param placeholder should be /// added.</param> /// <returns>The text ad id.</returns> public long CreateThirdPartyRedirectAd(AdWordsUser user, long adGroupId) { AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService(AdWordsService.v201601.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> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <param name="adGroupId">ID of the ad group to which ads are added.</param> public void Run(GoogleAdsClient client, long customerId, long adGroupId) { // Get the AdGroupAdService. AdGroupAdServiceClient adGroupAdService = client.GetService(Services.V5.AdGroupAdService); // Create the ad. Ad ad = new Ad() { ResponsiveSearchAd = new ResponsiveSearchAdInfo() { Headlines = { // Sets a pinning to always choose this asset for HEADLINE_1. Pinning is // optional; if no pinning is set, then headlines and descriptions will be // rotated and the ones that perform best will be used more often. new AdTextAsset() { Text = "Cruise to Mars #" + ExampleUtilities.GetShortRandomString(), PinnedField = ServedAssetFieldType.Headline1 }, new AdTextAsset() { Text = "Best Space Cruise Line" }, new AdTextAsset() { Text = "Experience the Stars" } }, Descriptions = { new AdTextAsset() { Text = "Buy your tickets now" }, new AdTextAsset() { Text = "Visit the Red Planet" }, }, Path1 = "all-inclusive", Path2 = "deals" }, FinalUrls = { "http://www.example.com" } }; // Builds the final ad group ad representation. AdGroupAd adGroupAd = new AdGroupAd() { AdGroup = ResourceNames.AdGroup(customerId, adGroupId), Status = AdGroupAdStatusEnum.Types.AdGroupAdStatus.Paused, Ad = ad }; // Creates the operation. AdGroupAdOperation operation = new AdGroupAdOperation() { Create = adGroupAd }; try { MutateAdGroupAdsResponse response = adGroupAdService.MutateAdGroupAds(customerId.ToString(), new[] { operation }); foreach (MutateAdGroupAdResult result in response.Results) { Console.WriteLine($"Responsive search ad created with resource name:" + $" '{result.ResourceName}'."); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
/// <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.v201708.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) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201809.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", headlinePart3 = "For Your Loved Ones", description = "Buy your tickets now!", description2 = "Discount ends soon", 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 adgroup to which ads are added.</param> public void Run(AdWordsUser user, long adGroupId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService( AdWordsService.v201802.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(); logoImage.mediaId = UploadImage(user, "https://goo.gl/mtt54n").mediaId; Image marketingImage = new Image(); marketingImage.mediaId = UploadImage(user, "https://goo.gl/3b9Wfh").mediaId; GmailTeaser teaser = new GmailTeaser(); teaser.headline = "Dream"; teaser.description = "Create your own adventure"; teaser.businessName = "Interplanetary Ships"; teaser.logoImage = logoImage; // Creates a Gmail ad. GmailAd gmailAd = new GmailAd(); gmailAd.teaser = teaser; gmailAd.marketingImage = marketingImage; gmailAd.marketingImageHeadline = "Travel"; gmailAd.marketingImageDescription = "Take to the skies!"; gmailAd.finalUrls = new string[] { "http://www.example.com/" }; // Creates ad group ad for the Gmail ad. AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.adGroupId = adGroupId; adGroupAd.ad = gmailAd; // Optional: Set additional settings. adGroupAd.status = AdGroupAdStatus.PAUSED; // Creates ad group ad operation and add it to the list. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.operand = adGroupAd; operation.@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="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> /// <param name="adGroupId">The ad group ID to which ads are added.</param> public void Run(GoogleAdsClient client, long customerId, long adGroupId) { // Get the AdGroupAdService. AdGroupAdServiceClient service = client.GetService(Services.V10.AdGroupAdService); // Create the expanded text ad. AdGroupAd ad = new AdGroupAd { AdGroup = ResourceNames.AdGroup(customerId, adGroupId), Ad = new Ad { ExpandedTextAd = new ExpandedTextAdInfo { Description = "Low-gravity fun for everyone!", HeadlinePart1 = "Luxury Cruise to Mars", HeadlinePart2 = "Visit the Red Planet in style.", }, // Specify a tracking URL for 3rd party tracking provider. You may // specify one at customer, campaign, ad group, ad, criterion or // feed item levels. 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. UrlCustomParameters = { new CustomParameter { Key = "season", Value = "christmas" }, new CustomParameter { Key = "promocode", Value = "NY123" } }, // 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. FinalUrls = { "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. FinalMobileUrls = { "http://mobile.example.com/cruise/space/", "http://mobile.example.com/locations/mars/" } }, // Optional: Set the status. Status = AdGroupAdStatus.Paused }; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation { Create = ad }; try { // Create the ad. MutateAdGroupAdsResponse response = service.MutateAdGroupAds(customerId.ToString(), new AdGroupAdOperation[] { operation }); // Display the results. foreach (MutateAdGroupAdResult result in response.Results) { Console.WriteLine($"Expanded text ad created with resource name: " + $"{result.ResourceName}."); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
/// <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.v201609.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) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService)user.GetService(AdWordsService.v201409.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 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.v201502.AdGroupAdService); // Get the AdParamService. AdParamService adParamService = (AdParamService)user.GetService( AdWordsService.v201502.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="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <param name="adGroupId">ID of the ad group to which ads are added.</param> public void Run(GoogleAdsClient client, long customerId, long adGroupId) { // Get the AdGroupAdService. AdGroupAdServiceClient adGroupAdService = client.GetService( Services.V3.AdGroupAdService); // Create the ad group ad object. AdGroupAd adGroupAd = new AdGroupAd { AdGroup = ResourceNames.AdGroup(customerId, adGroupId), // Optional: Set the status. Status = AdGroupAdStatus.Paused, Ad = new Ad { ExpandedTextAd = new ExpandedTextAdInfo { Description = "Luxury Cruise to Mars", HeadlinePart1 = "Visit the Red Planet in style.", HeadlinePart2 = "Low-gravity fun for everyone!!", }, FinalUrls = { "http://www.example.com/" }, } }; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation { Create = adGroupAd }; try { // Create the ads, while setting validateOnly = true. MutateAdGroupAdsResponse response = adGroupAdService.MutateAdGroupAds( customerId.ToString(), new[] { operation }, false, true); // Since validation is ON, result will be null. Console.WriteLine("Expanded text ad validated successfully."); } catch (GoogleAdsException 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.Failure != null) { // Note: Depending on the ad type, you may get back policy violation errors as // either PolicyFindingError or PolicyViolationError. ExpandedTextAds return // errors as PolicyFindingError, so only this case is illustrated here. See // https://developers.google.com/google-ads/api/docs/policy-exemption/overview // for additional details. e.Failure.Errors .Where(err => err.ErrorCode.PolicyFindingError == PolicyFindingError.PolicyFinding) .ToList() .ForEach(delegate(GoogleAdsError err) { int count = 1; if (err.Details.PolicyFindingDetails != null) { foreach (PolicyTopicEntry entry in err.Details.PolicyFindingDetails.PolicyTopicEntries) { Console.WriteLine($"{count}) Policy topic entry with topic = " + $"\"{entry.Topic}\" and type = \"{entry.Type}\" " + $"was found."); } } count++; }); } } catch (Exception e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); } }
/// <summary> /// Creates an App ad for a given ad group. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <param name="adGroupResourceName">The resource name of the ad group to add the App /// ad to.</param> private void CreateAppAd(GoogleAdsClient client, long customerId, string adGroupResourceName) { // Get the AdGroupAdService. AdGroupAdServiceClient adGroupAdService = client.GetService( Services.V3.AdGroupAdService); // Creates an ad group ad. AdGroupAd adGroupAd = new AdGroupAd { AdGroup = adGroupResourceName, Status = AdGroupAdStatus.Enabled, Ad = new Ad { AppAd = new AppAdInfo { Headlines = { new AdTextAsset() { Text = "A cool puzzle game" }, new AdTextAsset() { Text = "Remove connected blocks" }, }, Descriptions = { new AdTextAsset() { Text = "3 difficulty levels" }, new AdTextAsset() { Text = "4 colorful fun skins" } }, // Optional: You can set up to 20 image assets for your campaign. //Images = //{ // new AdImageAsset() // { // Asset = ResourceNames.Asset(customerId, assetId) // } //} } } }; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation { Create = adGroupAd }; // Submits the ad group ad operation to add the ad group ad and prints the results. MutateAdGroupAdsResponse response = adGroupAdService.MutateAdGroupAds(customerId.ToString(), new[] { operation }); Console.WriteLine($"Created an ad group ad with ad with resource name " + $"'{response.Results[0].ResourceName}'."); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to which ads are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService)user.GetService(AdWordsService.v201506.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 e) { throw new System.ApplicationException("Failed to create text ad.", e); } }
/// <summary> /// Creates a test textad 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 text ad id.</returns> public long CreateTextAd(AdWordsUser user, long adGroupId, bool hasAdParam) { AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService(AdWordsService.v201601.AdGroupAdService); AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation(); adGroupAdOperation.@operator = Operator.ADD; adGroupAdOperation.operand = new AdGroupAd(); adGroupAdOperation.operand.adGroupId = adGroupId; TextAd ad = new TextAd(); ad.headline = "Luxury Cruise to Mars"; ad.description1 = "Visit the Red Planet in style."; if (hasAdParam) { ad.description2 = "Low-gravity fun for {param1:cheap}!"; } else { ad.description2 = "Low-gravity fun for everyone!"; } ad.displayUrl = "example.com"; ad.finalUrls = new string[] { "http://www.example.com" }; adGroupAdOperation.operand.ad = ad; AdGroupAdReturnValue retVal = adGroupAdService.mutate(new AdGroupAdOperation[] { adGroupAdOperation }); return retVal.value[0].ad.id; }
/// <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) { // Get the AdGroupAdService. AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService( AdWordsService.v201601.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"); // 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 text ads are /// added.</param> public void Run(AdWordsUser user, long adGroupId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(AdWordsService.v201809.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 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.v201601.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.finalUrls = new string[] { "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 to which ads are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService) user.GetService(AdWordsService.v201509.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 ads are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService) user.GetService(AdWordsService.v201509.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 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 ads are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService)user.GetService(AdWordsService.v201402.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.url = "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 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); } }
public async Task TestAdGroupAd_CRUD_Passed() { var service = CreateService(); var testConfig = TestConfig.GetFromConfigFile(); long adGroupId = testConfig.AdWords.AdGroupId; // Create var createOp = new AdGroupAdOperation(); var textAd = new ExpandedTextAd { HeadlinePart1 = "Test Headline Part One", HeadlinePart2 = "Test Headline Part Two", Description = "Test Expanded Text Ad Description", FinalUrls = StringUtility.List("https://github.com/manychois/googleapis-dotnetcore") }; createOp.Operand = new AdGroupAd { AdGroupId = adGroupId, Ad = textAd, Status = AdGroupAdStatus.Enabled }; createOp.Operator = Operator.Add; var returnValue = await service.MutateAsync(new AdGroupAdOperation[] { createOp }); Assert.Equal(1, returnValue.Value.Count); var returnAdGroupAd = returnValue.Value[0]; Assert.Equal(adGroupId, returnAdGroupAd.AdGroupId.Value); Assert.Equal(AdGroupAdStatus.Enabled, returnAdGroupAd.Status.Value); Assert.IsType <ExpandedTextAd>(returnAdGroupAd.Ad); var returnTextAd = returnAdGroupAd.Ad as ExpandedTextAd; Assert.Equal(textAd.HeadlinePart1, returnTextAd.HeadlinePart1); Assert.Equal(textAd.HeadlinePart2, returnTextAd.HeadlinePart2); Assert.Equal(textAd.Description, returnTextAd.Description); Assert.Equal(textAd.FinalUrls, returnTextAd.FinalUrls); long adId = returnTextAd.Id.Value; // Read var selector = new Selector <AdGroupAdServiceField>() .AddFields( AdGroupAdServiceField.AdGroupId, AdGroupAdServiceField.BaseCampaignId, AdGroupAdServiceField.Status, AdGroupAdServiceField.AdGroupCreativeApprovalStatus, AdGroupAdServiceField.HeadlinePart1, AdGroupAdServiceField.HeadlinePart2, AdGroupAdServiceField.Description, AdGroupAdServiceField.CreativeFinalUrls) .AddPredicate(AdGroupAdServiceField.Id, PredicateOperator.Equals, adId); var page = await service.GetAsync(selector); Assert.Equal(1, page.TotalNumEntries.Value); returnAdGroupAd = page.Entries[0]; Assert.Equal(adGroupId, returnAdGroupAd.AdGroupId.Value); Assert.Equal(AdGroupAdStatus.Enabled, returnAdGroupAd.Status.Value); Assert.Equal(testConfig.AdWords.CampaignId, returnAdGroupAd.BaseCampaignId.Value); Assert.Equal(AdGroupAdApprovalStatus.Unchecked, returnAdGroupAd.ApprovalStatus.Value); Assert.IsType <ExpandedTextAd>(returnAdGroupAd.Ad); returnTextAd = returnAdGroupAd.Ad as ExpandedTextAd; Assert.Equal(textAd.HeadlinePart1, returnTextAd.HeadlinePart1); Assert.Equal(textAd.HeadlinePart2, returnTextAd.HeadlinePart2); Assert.Equal(textAd.Description, returnTextAd.Description); Assert.Equal(textAd.FinalUrls, returnTextAd.FinalUrls); // Update (Status only) var setOp = new AdGroupAdOperation(); setOp.Operand = new AdGroupAd { AdGroupId = adGroupId, Ad = new Ad { Id = adId }, Status = AdGroupAdStatus.Paused }; setOp.Operator = Operator.Set; returnValue = await service.MutateAsync(new AdGroupAdOperation[] { setOp }); Assert.Equal(1, returnValue.Value.Count); returnAdGroupAd = returnValue.Value[0]; Assert.Equal(adGroupId, returnAdGroupAd.AdGroupId.Value); Assert.Equal(AdGroupAdStatus.Paused, returnAdGroupAd.Status.Value); Assert.IsType <ExpandedTextAd>(returnAdGroupAd.Ad); returnTextAd = returnAdGroupAd.Ad as ExpandedTextAd; Assert.Equal(textAd.HeadlinePart1, returnTextAd.HeadlinePart1); Assert.Equal(textAd.HeadlinePart2, returnTextAd.HeadlinePart2); Assert.Equal(textAd.Description, returnTextAd.Description); Assert.Equal(textAd.FinalUrls, returnTextAd.FinalUrls); // Delete var removeOp = new AdGroupAdOperation(); removeOp.Operand = new AdGroupAd { AdGroupId = adGroupId, Ad = new Ad { Id = adId } }; removeOp.Operator = Operator.Remove; returnValue = await service.MutateAsync(new AdGroupAdOperation[] { removeOp }); Assert.Equal(1, returnValue.Value.Count); returnAdGroupAd = returnValue.Value[0]; Assert.Equal(adId, returnAdGroupAd.Ad.Id); }
/// <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.v201406.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 first adgroup to which ad is added.</param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupAdService. AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService( AdWordsService.v201603.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"); // 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 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.v201809.AdGroupAdService)) using (AdParamService adParamService = (AdParamService)user.GetService(AdWordsService.v201809.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); } } }
/// <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.v201601.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 e) { throw new System.ApplicationException("Failed to create 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 ad is added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService)user.GetService(AdWordsService.v201406.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"; // Specify a tracking URL for 3rd party tracking provider. You may // specify one at customer, campaign, ad group, ad, criterion or // feed item levels. textAd.trackingUrlTemplate = "http://tracker.example.com/?cid={_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"; textAd.urlCustomParameters = new CustomParameters(); textAd.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. textAd.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. textAd.finalMobileUrls = new string[] { "http://mobile.example.com/cruise/space/", "http://mobile.example.com/locations/mars/" }; 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; AdGroupAdReturnValue retVal = null; try { // Create the ads. retVal = service.mutate(new AdGroupAdOperation[] { operation }); // Display the results. if (retVal != null && retVal.value != null) { AdGroupAd newAdGroupAd = retVal.value[0]; Console.WriteLine("New text ad with ID = {0} and display URL = \"{1}\" was " + "created.", newAdGroupAd.ad.id, newAdGroupAd.ad.displayUrl); Console.WriteLine("Upgraded URL properties:"); TextAd newTextAd = (TextAd)newAdGroupAd.ad; Console.WriteLine(" Final URLs: {0}", string.Join(", ", newTextAd.finalUrls)); Console.WriteLine(" Final Mobile URLs: {0}", string.Join(", ", newTextAd.finalMobileUrls)); Console.WriteLine(" Tracking URL template: {0}", newTextAd.trackingUrlTemplate); List <string> parameters = new List <string>(); foreach (CustomParameter customParam in newTextAd.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 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) { // Get the AdGroupAdService. AdGroupAdService service = (AdGroupAdService) user.GetService(AdWordsService.v201509.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 e) { throw new System.ApplicationException("Failed to create third party redirect 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 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 e) { throw new System.ApplicationException("Failed to create third party redirect ads.", e); } }