/// <summary> /// Run the code examples. /// </summary> public void Run(AdManagerUser user) { using (LineItemService lineItemService = user.GetService <LineItemService>()) { // Set the order that all created line items will belong to and the // placement ID to target. long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE")); long[] targetPlacementIds = new long[] { long.Parse(_T("INSERT_PLACEMENT_ID_HERE")) }; // Create inventory targeting. InventoryTargeting inventoryTargeting = new InventoryTargeting(); inventoryTargeting.targetedPlacementIds = targetPlacementIds; // Create geographical targeting. GeoTargeting geoTargeting = new GeoTargeting(); // Include the US and Quebec, Canada. Location countryLocation = new Location(); countryLocation.id = 2840L; Location regionLocation = new Location(); regionLocation.id = 20123L; geoTargeting.targetedLocations = new Location[] { countryLocation, regionLocation }; Location postalCodeLocation = new Location(); postalCodeLocation.id = 9000093; // Exclude Chicago and the New York metro area. Location cityLocation = new Location(); cityLocation.id = 1016367L; Location metroLocation = new Location(); metroLocation.id = 200501L; geoTargeting.excludedLocations = new Location[] { cityLocation, metroLocation }; // Exclude domains that are not under the network's control. UserDomainTargeting userDomainTargeting = new UserDomainTargeting(); userDomainTargeting.domains = new String[] { "usa.gov" }; userDomainTargeting.targeted = false; // Create day-part targeting. DayPartTargeting dayPartTargeting = new DayPartTargeting(); dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER; // Target only the weekend in the browser's timezone. DayPart saturdayDayPart = new DayPart(); saturdayDayPart.dayOfWeek = Google.Api.Ads.AdManager.v201808.DayOfWeek.SATURDAY; saturdayDayPart.startTime = new TimeOfDay(); saturdayDayPart.startTime.hour = 0; saturdayDayPart.startTime.minute = MinuteOfHour.ZERO; saturdayDayPart.endTime = new TimeOfDay(); saturdayDayPart.endTime.hour = 24; saturdayDayPart.endTime.minute = MinuteOfHour.ZERO; DayPart sundayDayPart = new DayPart(); sundayDayPart.dayOfWeek = Google.Api.Ads.AdManager.v201808.DayOfWeek.SUNDAY; sundayDayPart.startTime = new TimeOfDay(); sundayDayPart.startTime.hour = 0; sundayDayPart.startTime.minute = MinuteOfHour.ZERO; sundayDayPart.endTime = new TimeOfDay(); sundayDayPart.endTime.hour = 24; sundayDayPart.endTime.minute = MinuteOfHour.ZERO; dayPartTargeting.dayParts = new DayPart[] { saturdayDayPart, sundayDayPart }; // Create technology targeting. TechnologyTargeting technologyTargeting = new TechnologyTargeting(); // Create browser targeting. BrowserTargeting browserTargeting = new BrowserTargeting(); browserTargeting.isTargeted = true; // Target just the Chrome browser. Technology browserTechnology = new Technology(); browserTechnology.id = 500072L; browserTargeting.browsers = new Technology[] { browserTechnology }; technologyTargeting.browserTargeting = browserTargeting; // Create an array to store local line item objects. LineItem[] lineItems = new LineItem[5]; for (int i = 0; i < 5; i++) { LineItem lineItem = new LineItem(); lineItem.name = "Line item #" + i; lineItem.orderId = orderId; lineItem.targeting = new Targeting(); lineItem.targeting.inventoryTargeting = inventoryTargeting; lineItem.targeting.geoTargeting = geoTargeting; lineItem.targeting.userDomainTargeting = userDomainTargeting; lineItem.targeting.dayPartTargeting = dayPartTargeting; lineItem.targeting.technologyTargeting = technologyTargeting; lineItem.lineItemType = LineItemType.STANDARD; lineItem.allowOverbook = true; // Set the creative rotation type to even. lineItem.creativeRotationType = CreativeRotationType.EVEN; // Set the size of creatives that can be associated with this line item. Size size = new Size(); size.width = 300; size.height = 250; size.isAspectRatio = false; // Create the creative placeholder. CreativePlaceholder creativePlaceholder = new CreativePlaceholder(); creativePlaceholder.size = size; lineItem.creativePlaceholders = new CreativePlaceholder[] { creativePlaceholder }; // Set the line item to run for one month. lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY; lineItem.endDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1), "America/New_York"); // Set the cost per unit to $2. lineItem.costType = CostType.CPM; lineItem.costPerUnit = new Money(); lineItem.costPerUnit.currencyCode = "USD"; lineItem.costPerUnit.microAmount = 2000000L; // Set the number of units bought to 500,000 so that the budget is // $1,000. Goal goal = new Goal(); goal.goalType = GoalType.LIFETIME; goal.unitType = UnitType.IMPRESSIONS; goal.units = 500000L; lineItem.primaryGoal = goal; lineItems[i] = lineItem; } try { // Create the line items on the server. lineItems = lineItemService.createLineItems(lineItems); if (lineItems != null) { foreach (LineItem lineItem in lineItems) { Console.WriteLine( "A line item with ID \"{0}\", belonging to order ID \"{1}\", and" + " named \"{2}\" was created.", lineItem.id, lineItem.orderId, lineItem.name); } } else { Console.WriteLine("No line items created."); } } catch (Exception e) { Console.WriteLine("Failed to create line items. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (ForecastService forecastService = user.GetService <ForecastService>()) using (NetworkService networkService = user.GetService <NetworkService>()) { // Set the ID of the advertiser (company) to forecast for. Setting an advertiser // will cause the forecast to apply the appropriate unified blocking rules. long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId; System.DateTime tomorrow = System.DateTime.Now.AddDays(1); // Create prospective line item. LineItem lineItem = new LineItem() { targeting = new Targeting() { inventoryTargeting = new InventoryTargeting() { targetedAdUnits = new AdUnitTargeting[] { new AdUnitTargeting() { adUnitId = rootAdUnitId, includeDescendants = true } } } }, creativePlaceholders = new CreativePlaceholder[] { new CreativePlaceholder() { size = new Size() { width = 300, height = 250 } } }, lineItemType = LineItemType.SPONSORSHIP, // Set the line item to run for 5 days. startDateTime = DateTimeUtilities.FromDateTime( tomorrow, "America/New_York"), endDateTime = DateTimeUtilities.FromDateTime( tomorrow.AddDays(5), "America/New_York"), // Set the cost type to match the unit type. costType = CostType.CPM, primaryGoal = new Goal() { goalType = GoalType.DAILY, unitType = UnitType.IMPRESSIONS, units = 50L } }; try { // Get availability forecast. AvailabilityForecastOptions options = new AvailabilityForecastOptions() { includeContendingLineItems = true, // Targeting criteria breakdown can only be included if breakdowns // are not speficied. includeTargetingCriteriaBreakdown = false, breakdown = new ForecastBreakdownOptions { timeWindows = new DateTime[] { lineItem.startDateTime, DateTimeUtilities.FromDateTime(tomorrow.AddDays(1), "America/New_York"), DateTimeUtilities.FromDateTime(tomorrow.AddDays(2), "America/New_York"), DateTimeUtilities.FromDateTime(tomorrow.AddDays(3), "America/New_York"), DateTimeUtilities.FromDateTime(tomorrow.AddDays(4), "America/New_York"), lineItem.endDateTime }, targets = new ForecastBreakdownTarget[] { new ForecastBreakdownTarget() { // Optional name field to identify this breakdown // in the response. name = "United States", targeting = new Targeting() { inventoryTargeting = new InventoryTargeting() { targetedAdUnits = new AdUnitTargeting[] { new AdUnitTargeting() { adUnitId = rootAdUnitId, includeDescendants = true } } }, geoTargeting = new GeoTargeting() { targetedLocations = new Location[] { new Location() { id = 2840L } } } } }, new ForecastBreakdownTarget() { // Optional name field to identify this breakdown // in the response. name = "Geneva", targeting = new Targeting() { inventoryTargeting = new InventoryTargeting() { targetedAdUnits = new AdUnitTargeting[] { new AdUnitTargeting() { adUnitId = rootAdUnitId, includeDescendants = true } } }, geoTargeting = new GeoTargeting() { targetedLocations = new Location[] { new Location() { id = 20133L } } } } } } } }; ProspectiveLineItem prospectiveLineItem = new ProspectiveLineItem() { advertiserId = advertiserId, lineItem = lineItem }; AvailabilityForecast forecast = forecastService.getAvailabilityForecast(prospectiveLineItem, options); // Display results. long matched = forecast.matchedUnits; double availablePercent = (double)(forecast.availableUnits / (matched * 1.0)) * 100; String unitType = forecast.unitType.ToString().ToLower(); Console.WriteLine($"{matched} {unitType} matched."); Console.WriteLine($"{availablePercent}% {unitType} available."); if (forecast.possibleUnitsSpecified) { double possiblePercent = (double)(forecast.possibleUnits / (matched * 1.0)) * 100; Console.WriteLine($"{possiblePercent}% {unitType} possible."); } var contendingLineItems = forecast.contendingLineItems ?? new ContendingLineItem[] { }; Console.WriteLine($"{contendingLineItems.Length} contending line items."); if (forecast.breakdowns != null) { foreach (ForecastBreakdown breakdown in forecast.breakdowns) { Console.WriteLine("Forecast breakdown for {0} to {1}", DateTimeUtilities.ToString(breakdown.startTime, "yyyy-MM-dd"), DateTimeUtilities.ToString(breakdown.endTime, "yyyy-MM-dd")); foreach (ForecastBreakdownEntry entry in breakdown.breakdownEntries) { Console.WriteLine($"\t{entry.name}"); long breakdownMatched = entry.forecast.matched; Console.WriteLine($"\t\t{breakdownMatched} {unitType} matched."); if (breakdownMatched > 0) { long breakdownAvailable = entry.forecast.available; double breakdownAvailablePercent = (double)(breakdownAvailable / (breakdownMatched * 1.0)) * 100; Console.WriteLine( $"\t\t{breakdownAvailablePercent}% {unitType} available"); } } } } } catch (Exception e) { Console.WriteLine("Failed to get forecast. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code examples. /// </summary> public void Run(AdManagerUser user, long proposalId) { using (ProposalLineItemService proposalLineItemService = user.GetService <ProposalLineItemService>()) using (NetworkService networkService = user.GetService <NetworkService>()) { ProposalLineItem proposalLineItem = new ProposalLineItem(); proposalLineItem.name = "Proposal line item #" + new Random().Next(int.MaxValue); proposalLineItem.proposalId = proposalId; proposalLineItem.lineItemType = LineItemType.STANDARD; // Set required Marketplace information. proposalLineItem.marketplaceInfo = new ProposalLineItemMarketplaceInfo() { adExchangeEnvironment = AdExchangeEnvironment.DISPLAY }; // Get the root ad unit ID used to target the whole site. String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId; // Create inventory targeting. InventoryTargeting inventoryTargeting = new InventoryTargeting(); // Create ad unit targeting for the root ad unit (i.e. the whole network). AdUnitTargeting adUnitTargeting = new AdUnitTargeting(); adUnitTargeting.adUnitId = rootAdUnitId; adUnitTargeting.includeDescendants = true; inventoryTargeting.targetedAdUnits = new AdUnitTargeting[] { adUnitTargeting }; // Create targeting. Targeting targeting = new Targeting(); targeting.inventoryTargeting = inventoryTargeting; proposalLineItem.targeting = targeting; // Create creative placeholder. Size size = new Size() { width = 300, height = 250, isAspectRatio = false }; CreativePlaceholder creativePlaceholder = new CreativePlaceholder(); creativePlaceholder.size = size; proposalLineItem.creativePlaceholders = new CreativePlaceholder[] { creativePlaceholder }; // Set the length of the proposal line item to run. proposalLineItem.startDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(7), "America/New_York"); proposalLineItem.endDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(30), "America/New_York"); // Set delivery specifications for the proposal line item. proposalLineItem.deliveryRateType = DeliveryRateType.EVENLY; // Set pricing for the proposal line item for 1000 impressions at a CPM of $2 // for a total value of $2. proposalLineItem.goal = new Goal() { unitType = UnitType.IMPRESSIONS, units = 1000L }; proposalLineItem.netCost = new Money() { currencyCode = "USD", microAmount = 2000000L }; proposalLineItem.netRate = new Money() { currencyCode = "USD", microAmount = 2000000L }; proposalLineItem.rateType = RateType.CPM; try { // Create the proposal line item on the server. ProposalLineItem[] proposalLineItems = proposalLineItemService.createProposalLineItems(new ProposalLineItem[] { proposalLineItem }); foreach (ProposalLineItem createdProposalLineItem in proposalLineItems) { Console.WriteLine("A proposal line item with ID \"{0}\" " + "and name \"{1}\" was created.", createdProposalLineItem.id, createdProposalLineItem.name); } } catch (Exception e) { Console.WriteLine( "Failed to create proposal line items. " + "Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (ActivityGroupService activityGroupService = user.GetService <ActivityGroupService>()) { // Set the ID of the advertiser company this activity group is associated // with. long advertiserCompanyId = long.Parse(_T("INSERT_ADVERTISER_COMPANY_ID_HERE")); // Create a short-term activity group. ActivityGroup shortTermActivityGroup = new ActivityGroup(); shortTermActivityGroup.name = "Short-term activity group #" + GetTimeStamp(); shortTermActivityGroup.companyIds = new long[] { advertiserCompanyId }; shortTermActivityGroup.clicksLookback = 1; shortTermActivityGroup.impressionsLookback = 1; // Create a long-term activity group. ActivityGroup longTermActivityGroup = new ActivityGroup(); longTermActivityGroup.name = "Long-term activity group #" + GetTimeStamp(); longTermActivityGroup.companyIds = new long[] { advertiserCompanyId }; longTermActivityGroup.clicksLookback = 30; longTermActivityGroup.impressionsLookback = 30; try { // Create the activity groups on the server. ActivityGroup[] activityGroups = activityGroupService.createActivityGroups( new ActivityGroup[] { shortTermActivityGroup, longTermActivityGroup }); // Display results. if (activityGroups != null) { foreach (ActivityGroup activityGroup in activityGroups) { Console.WriteLine( "An activity group with ID \"{0}\" and name \"{1}\" was created.", activityGroup.id, activityGroup.name); } } else { Console.WriteLine("No activity groups were created."); } } catch (Exception e) { Console.WriteLine("Failed to create activity groups. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (LineItemService lineItemService = user.GetService <LineItemService>()) { // Set the order that all created line items will belong to and the // video ad unit ID to target. long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE")); string targetedVideoAdUnitId = _T("INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE"); // Set the custom targeting value ID representing the metadata // on the content to target. This would typically be from a key representing // a "genre" and a value representing something like "comedy". The value must // be from a key in a content metadata key hierarchy. long contentCustomTargetingValueId = long.Parse(_T("INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE")); // Create content targeting. ContentMetadataKeyHierarchyTargeting contentMetadataTargeting = new ContentMetadataKeyHierarchyTargeting(); contentMetadataTargeting.customTargetingValueIds = new long[] { contentCustomTargetingValueId }; ContentTargeting contentTargeting = new ContentTargeting(); contentTargeting.targetedContentMetadata = new ContentMetadataKeyHierarchyTargeting[] { contentMetadataTargeting }; // Create inventory targeting. InventoryTargeting inventoryTargeting = new InventoryTargeting(); AdUnitTargeting adUnitTargeting = new AdUnitTargeting(); adUnitTargeting.adUnitId = targetedVideoAdUnitId; adUnitTargeting.includeDescendants = true; inventoryTargeting.targetedAdUnits = new AdUnitTargeting[] { adUnitTargeting }; // Create video position targeting. VideoPosition videoPosition = new VideoPosition(); videoPosition.positionType = VideoPositionType.PREROLL; VideoPositionTarget videoPositionTarget = new VideoPositionTarget(); videoPositionTarget.videoPosition = videoPosition; VideoPositionTargeting videoPositionTargeting = new VideoPositionTargeting(); videoPositionTargeting.targetedPositions = new VideoPositionTarget[] { videoPositionTarget }; // Create targeting. Targeting targeting = new Targeting(); targeting.contentTargeting = contentTargeting; targeting.inventoryTargeting = inventoryTargeting; targeting.videoPositionTargeting = videoPositionTargeting; // Create local line item object. LineItem lineItem = new LineItem(); lineItem.name = "Video line item - " + this.GetTimeStamp(); lineItem.orderId = orderId; lineItem.targeting = targeting; lineItem.lineItemType = LineItemType.SPONSORSHIP; lineItem.allowOverbook = true; // Set the environment type to video. lineItem.environmentType = EnvironmentType.VIDEO_PLAYER; // Set the creative rotation type to optimized. lineItem.creativeRotationType = CreativeRotationType.OPTIMIZED; // Create the master creative placeholder. CreativePlaceholder creativeMasterPlaceholder = new CreativePlaceholder(); Size size1 = new Size(); size1.width = 400; size1.height = 300; size1.isAspectRatio = false; creativeMasterPlaceholder.size = size1; // Create companion creative placeholders. CreativePlaceholder companionCreativePlaceholder1 = new CreativePlaceholder(); Size size2 = new Size(); size2.width = 300; size2.height = 250; size2.isAspectRatio = false; companionCreativePlaceholder1.size = size2; CreativePlaceholder companionCreativePlaceholder2 = new CreativePlaceholder(); Size size3 = new Size(); size3.width = 728; size3.height = 90; size3.isAspectRatio = false; companionCreativePlaceholder2.size = size3; // Set companion creative placeholders. creativeMasterPlaceholder.companions = new CreativePlaceholder[] { companionCreativePlaceholder1, companionCreativePlaceholder2 }; // Set the size of creatives that can be associated with this line item. lineItem.creativePlaceholders = new CreativePlaceholder[] { creativeMasterPlaceholder }; // Set delivery of video companions to optional. lineItem.companionDeliveryOption = CompanionDeliveryOption.OPTIONAL; // Set the line item to run for one month. lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY; lineItem.endDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Now.AddMonths(1), "America/New_York"); // Set the cost per day to $1. lineItem.costType = CostType.CPD; Money money = new Money(); money.currencyCode = "USD"; money.microAmount = 1000000L; lineItem.costPerUnit = money; // Set the percentage to be 100%. Goal goal = new Goal(); goal.goalType = GoalType.DAILY; goal.unitType = UnitType.IMPRESSIONS; goal.units = 100; lineItem.primaryGoal = goal; try { // Create the line item on the server. LineItem[] createdLineItems = lineItemService.createLineItems(new LineItem[] { lineItem }); foreach (LineItem createdLineItem in createdLineItems) { Console.WriteLine( "A line item with ID \"{0}\", belonging to order ID \"{1}\", and " + "named \"{2}\" was created.", createdLineItem.id, createdLineItem.orderId, createdLineItem.name); } } catch (Exception e) { Console.WriteLine("Failed to create line items. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (ProductTemplateService productTemplateService = user.GetService <ProductTemplateService>()) { // Set the ID of the product template. long productTemplateId = long.Parse(_T("INSERT_PRODUCT_TEMPLATE_ID_HERE")); // Create a statement to get the product template. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", productTemplateId); try { // Get product templates by statement. ProductTemplatePage page = productTemplateService.getProductTemplatesByStatement( statementBuilder.ToStatement()); ProductTemplate productTemplate = page.results[0]; // Add geo targeting for Canada to the product template. Location countryLocation = new Location(); countryLocation.id = 2124L; Targeting productTemplateTargeting = productTemplate.builtInTargeting; GeoTargeting geoTargeting = productTemplateTargeting.geoTargeting; List <Location> existingTargetedLocations = new List <Location>(); if (geoTargeting == null) { geoTargeting = new GeoTargeting(); } else if (geoTargeting.targetedLocations != null) { existingTargetedLocations = new List <Location>(geoTargeting.targetedLocations); } existingTargetedLocations.Add(countryLocation); Location[] newTargetedLocations = new Location[existingTargetedLocations.Count]; existingTargetedLocations.CopyTo(newTargetedLocations); geoTargeting.targetedLocations = newTargetedLocations; productTemplateTargeting.geoTargeting = geoTargeting; productTemplate.builtInTargeting = productTemplateTargeting; // Update the product template on the server. ProductTemplate[] productTemplates = productTemplateService.updateProductTemplates(new ProductTemplate[] { productTemplate }); if (productTemplates != null) { foreach (ProductTemplate updatedProductTemplate in productTemplates) { Console.WriteLine( "A product template with ID = '{0}' and name '{1}' was updated.", updatedProductTemplate.id, updatedProductTemplate.name); } } else { Console.WriteLine("No product templates updated."); } } catch (Exception e) { Console.WriteLine("Failed to update product templates. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (CreativeService creativeService = user.GetService <CreativeService>()) { // Set the ID of the advertiser (company) that all creatives will be // assigned to. long advertiserId = long.Parse(_T("INSERT_ADVERTISER_COMPANY_ID_HERE")); // Create an array to store local image creative objects. Creative[] imageCreatives = new ImageCreative[5]; for (int i = 0; i < 5; i++) { // Create creative size. Size size = new Size(); size.width = 300; size.height = 250; // Create an image creative. ImageCreative imageCreative = new ImageCreative(); imageCreative.name = string.Format("Image creative #{0}", i); imageCreative.advertiserId = advertiserId; imageCreative.destinationUrl = "http://www.google.com"; imageCreative.size = size; // Create image asset. CreativeAsset creativeAsset = new CreativeAsset(); creativeAsset.fileName = "image.jpg"; creativeAsset.assetByteArray = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/3b9Wfh", user.Config); creativeAsset.size = size; imageCreative.primaryImageAsset = creativeAsset; imageCreatives[i] = imageCreative; } try { // Create the image creatives on the server. imageCreatives = creativeService.createCreatives(imageCreatives); if (imageCreatives != null) { foreach (Creative creative in imageCreatives) { // Use "is" operator to determine what type of creative was // returned. if (creative is ImageCreative) { ImageCreative imageCreative = (ImageCreative)creative; Console.WriteLine( "An image creative with ID ='{0}', name ='{1}' and size = " + "({2},{3}) was created and can be previewed at: {4}", imageCreative.id, imageCreative.name, imageCreative.size.width, imageCreative.size.height, imageCreative.previewUrl); } else { Console.WriteLine( "A creative with ID ='{0}', name='{1}' and type='{2}' " + "was created.", creative.id, creative.name, creative.GetType().Name); } } } else { Console.WriteLine("No creatives created."); } } catch (Exception e) { Console.WriteLine("Failed to create creatives. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (LineItemService lineItemService = user.GetService <LineItemService>()) using (ReportService reportService = user.GetService <ReportService>()) { try { // Set the ID of the order to get line items from. long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE")); // Set the file path where the report will be saved. String filePath = _T("INSERT_FILE_PATH_HERE"); // Sets default for page. LineItemPage page = new LineItemPage(); // Create a statement to only select line items from a given order. StatementBuilder statementBuilder = new StatementBuilder() .Where("orderId = :orderId") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .AddValue("orderId", orderId); // Collect all line item custom field IDs for an order. List <long> customFieldIds = new List <long>(); do { // Get line items by statement. page = lineItemService.getLineItemsByStatement(statementBuilder .ToStatement()); // Get custom field IDs from the line items of an order. if (page.results != null) { foreach (LineItem lineItem in page.results) { if (lineItem.customFieldValues != null) { foreach (BaseCustomFieldValue customFieldValue in lineItem .customFieldValues) { if (!customFieldIds.Contains(customFieldValue .customFieldId)) { customFieldIds.Add(customFieldValue.customFieldId); } } } } } statementBuilder.IncreaseOffsetBy(StatementBuilder .SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); // Create statement to filter for an order. statementBuilder.RemoveLimitAndOffset(); // Create report job. ReportJob reportJob = new ReportJob(); // Create report query. ReportQuery reportQuery = new ReportQuery(); reportQuery.dateRangeType = DateRangeType.LAST_MONTH; reportQuery.dimensions = new Dimension[] { Dimension.LINE_ITEM_ID, Dimension.LINE_ITEM_NAME }; reportQuery.statement = statementBuilder.ToStatement(); reportQuery.customFieldIds = customFieldIds.ToArray(); reportQuery.columns = new Column[] { Column.AD_SERVER_IMPRESSIONS }; reportJob.reportQuery = reportQuery; // Run report job. reportJob = reportService.runReportJob(reportJob); ReportUtilities reportUtilities = new ReportUtilities(reportService, reportJob.id); // Set download options. ReportDownloadOptions options = new ReportDownloadOptions(); options.exportFormat = ExportFormat.CSV_DUMP; options.useGzipCompression = true; reportUtilities.reportDownloadOptions = options; // Download the report. using (ReportResponse reportResponse = reportUtilities.GetResponse()) { reportResponse.Save(filePath); } Console.WriteLine("Report saved to \"{0}\".", filePath); } catch (Exception e) { Console.WriteLine( "Failed to run cusom fields report. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (AudienceSegmentService audienceSegmentService = user.GetService<AudienceSegmentService>()) { // Get the NetworkService. NetworkService networkService = user.GetService<NetworkService>(); long customTargetingKeyId = long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE")); long customTargetingValueId = long.Parse(_T("INSERT_CUSTOM_TARGETING_VALUE_ID_HERE")); try { // Get the root ad unit ID used to target the whole site. String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId; // Create inventory targeting. InventoryTargeting inventoryTargeting = new InventoryTargeting(); // Create ad unit targeting for the root ad unit (i.e. the whole network). AdUnitTargeting adUnitTargeting = new AdUnitTargeting(); adUnitTargeting.adUnitId = rootAdUnitId; adUnitTargeting.includeDescendants = true; inventoryTargeting.targetedAdUnits = new AdUnitTargeting[] { adUnitTargeting }; // Create the custom criteria to be used in the segment rule. // CUSTOM_TARGETING_KEY_ID == CUSTOM_TARGETING_VALUE_ID CustomCriteria customCriteria = new CustomCriteria(); customCriteria.keyId = customTargetingKeyId; customCriteria.@operator = CustomCriteriaComparisonOperator.IS; customCriteria.valueIds = new long[] { customTargetingValueId }; // Create the custom criteria expression. CustomCriteriaSet topCustomCriteriaSet = new CustomCriteriaSet(); topCustomCriteriaSet.logicalOperator = CustomCriteriaSetLogicalOperator.AND; topCustomCriteriaSet.children = new CustomCriteriaNode[] { customCriteria }; // Create the audience segment rule. FirstPartyAudienceSegmentRule rule = new FirstPartyAudienceSegmentRule(); rule.inventoryRule = inventoryTargeting; rule.customCriteriaRule = topCustomCriteriaSet; // Create an audience segment. RuleBasedFirstPartyAudienceSegment audienceSegment = new RuleBasedFirstPartyAudienceSegment(); audienceSegment.name = "Sports enthusiasts audience segment #" + this.GetTimeStamp(); audienceSegment.description = "Sports enthusiasts between the ages of 20 and 30."; audienceSegment.pageViews = 6; audienceSegment.recencyDays = 6; audienceSegment.membershipExpirationDays = 88; audienceSegment.rule = rule; // Create the audience segment on the server. AudienceSegment[] audienceSegments = audienceSegmentService.createAudienceSegments( new FirstPartyAudienceSegment[] { audienceSegment }); foreach (AudienceSegment createdAudienceSegment in audienceSegments) { Console.WriteLine( "An audience segment with ID \"{0}\", name \"{1}\", and " + "type \"{2}\" was created.", createdAudienceSegment.id, createdAudienceSegment.name, createdAudienceSegment.type); } } catch (Exception e) { Console.WriteLine("Failed to get audience segment. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (ReportService reportService = user.GetService <ReportService>()) { try { // Set the ID of the custom field to report on. long customFieldId = long.Parse(_T("INSERT_FIELD_ID_HERE")); // Set the key ID of the custom dimension to report on. long customDimensionKeyId = long.Parse(_T("INSERT_CUSTOM_DIMENSION_KEY_ID_HERE")); // Set the file path where the report will be saved. String filePath = _T("INSERT_FILE_PATH_HERE"); // Create report job. ReportJob reportJob = new ReportJob(); // Create report query. ReportQuery reportQuery = new ReportQuery(); reportQuery.dateRangeType = DateRangeType.LAST_MONTH; reportQuery.dimensions = new Dimension[] { Dimension.CUSTOM_DIMENSION, Dimension.LINE_ITEM_ID, Dimension.LINE_ITEM_NAME }; reportQuery.customFieldIds = new long[] { customFieldId }; reportQuery.customDimensionKeyIds = new long[] { customDimensionKeyId }; reportQuery.columns = new Column[] { Column.AD_SERVER_IMPRESSIONS }; reportJob.reportQuery = reportQuery; // Run report job. reportJob = reportService.runReportJob(reportJob); ReportUtilities reportUtilities = new ReportUtilities(reportService, reportJob.id); // Set download options. ReportDownloadOptions options = new ReportDownloadOptions(); options.exportFormat = ExportFormat.CSV_DUMP; options.useGzipCompression = true; reportUtilities.reportDownloadOptions = options; // Download the report. using (ReportResponse reportResponse = reportUtilities.GetResponse()) { reportResponse.Save(filePath); } Console.WriteLine("Report saved to \"{0}\".", filePath); } catch (Exception e) { Console.WriteLine( "Failed to run custom fields report. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (LineItemCreativeAssociationService licaService = user.GetService <LineItemCreativeAssociationService>()) { // Set the line item to get LICAs by. long lineItemId = long.Parse(_T("INSERT_LINE_ITEM_ID_HERE")); // Create a statement to page through active LICAs. StatementBuilder statementBuilder = new StatementBuilder() .Where("lineItemId = :lineItemId").OrderBy("lineItemId ASC, creativeId ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .AddValue("lineItemId", lineItemId); // Set default for page. LineItemCreativeAssociationPage page = new LineItemCreativeAssociationPage(); List <string> creativeIds = new List <string>(); try { do { // Get LICAs by statement. page = licaService.getLineItemCreativeAssociationsByStatement( statementBuilder.ToStatement()); if (page.results != null) { int i = page.startIndex; foreach (LineItemCreativeAssociation lica in page.results) { Console.WriteLine( "{0}) LICA with line item ID = '{1}', creative ID ='{2}' and " + "status ='{3}' will be deactivated.", i, lica.lineItemId, lica.creativeId, lica.status); i++; creativeIds.Add(lica.creativeId.ToString()); } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of LICAs to be deactivated: {0}", creativeIds.Count); if (creativeIds.Count > 0) { // Modify statement for action. statementBuilder.RemoveLimitAndOffset(); // Create action. DeactivateLineItemCreativeAssociations action = new DeactivateLineItemCreativeAssociations(); // Perform action. UpdateResult result = licaService.performLineItemCreativeAssociationAction(action, statementBuilder.ToStatement()); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of LICAs deactivated: {0}", result.numChanges); } else { Console.WriteLine("No LICAs were deactivated."); } } } catch (Exception e) { Console.WriteLine("Failed to deactivate LICAs. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (CreativeService creativeService = user.GetService <CreativeService>()) { // Set the ID of the advertiser (company) that the creative will be // assigned to. long advertiserId = long.Parse(_T("INSERT_ADVERTISER_COMPANY_ID_HERE")); // Use the system defined native app install creative template. long creativeTemplateId = 10004400L; // Create a native app install creative for the Pie Noon app. TemplateCreative nativeAppInstallCreative = new TemplateCreative(); nativeAppInstallCreative.name = String.Format("Native creative #{0}", new Random().Next(int.MaxValue)); nativeAppInstallCreative.advertiserId = advertiserId; nativeAppInstallCreative.creativeTemplateId = creativeTemplateId; nativeAppInstallCreative.destinationUrl = "https://play.google.com/store/apps/details?id=com.google.fpl.pie_noon"; // Use 1x1 as the size for native creatives. Size size = new Size(); size.width = 1; size.height = 1; size.isAspectRatio = false; nativeAppInstallCreative.size = size; List <BaseCreativeTemplateVariableValue> templateVariables = new List <BaseCreativeTemplateVariableValue>(); // Set the headline. templateVariables.Add(new StringCreativeTemplateVariableValue() { uniqueName = "Headline", value = "Pie Noon" }); // Set the body text. templateVariables.Add(new StringCreativeTemplateVariableValue() { uniqueName = "Body", value = "Try multi-screen mode!" }); // Set the image asset. var imageUrl = "https://lh4.ggpht.com/" + "GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZOPYnTdOQGaSpGSEZflIFs0iw=h300"; templateVariables.Add(new AssetCreativeTemplateVariableValue() { uniqueName = "Image", asset = new CreativeAsset() { fileName = String.Format("image{0}.png", this.GetTimeStamp()), assetByteArray = MediaUtilities.GetAssetDataFromUrl( imageUrl, user.Config) } }); // Set the price. templateVariables.Add(new StringCreativeTemplateVariableValue() { uniqueName = "Price", value = "Free" }); // Set app icon image asset. var iconUrl = "https://lh6.ggpht.com/" + "Jzvjne5CLs6fJ1MHF-XeuUfpABzl0YNMlp4RpHnvPRCIj4--eTDwtyouwUDzVVekXw=w300"; templateVariables.Add(new AssetCreativeTemplateVariableValue() { uniqueName = "Appicon", asset = new CreativeAsset() { fileName = String.Format("icon{0}.png", this.GetTimeStamp()), assetByteArray = MediaUtilities.GetAssetDataFromUrl( iconUrl, user.Config) } }); // Set the call to action text. templateVariables.Add(new StringCreativeTemplateVariableValue() { uniqueName = "Calltoaction", value = "Install" }); // Set the star rating. templateVariables.Add(new StringCreativeTemplateVariableValue() { uniqueName = "Starrating", value = "4" }); // Set the store type. templateVariables.Add(new StringCreativeTemplateVariableValue() { uniqueName = "Store", value = "Google Play" }); // Set the deep link URL. templateVariables.Add(new UrlCreativeTemplateVariableValue() { uniqueName = "DeeplinkclickactionURL", value = "market://details?id=com.google.fpl.pie_noon" }); nativeAppInstallCreative.creativeTemplateVariableValues = templateVariables.ToArray(); try { // Create the native creative on the server. Creative[] createdNativeCreatives = creativeService.createCreatives( new Creative[] { nativeAppInstallCreative }); foreach (Creative createdNativeCreative in createdNativeCreatives) { Console.WriteLine( "A native creative with ID \"{0}\" and name \"{1}\" " + "was created and can be previewed at {2}", createdNativeCreative.id, createdNativeCreative.name, createdNativeCreative.previewUrl); } } catch (Exception e) { Console.WriteLine("Failed to create creatives. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (InventoryService inventoryService = user.GetService <InventoryService>()) { // Get the NetworkService. NetworkService networkService = user.GetService <NetworkService>(); string effectiveRootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId; // Create an array to store local ad unit objects. AdUnit[] adUnits = new AdUnit[5]; for (int i = 0; i < 5; i++) { AdUnit adUnit = new AdUnit(); adUnit.name = string.Format("Ad_Unit_{0}", i); adUnit.parentId = effectiveRootAdUnitId; adUnit.description = "Ad unit description."; adUnit.targetWindow = AdUnitTargetWindow.BLANK; // Set the size of possible creatives that can match this ad unit. Size size = new Size(); size.width = 300; size.height = 250; // Create ad unit size. AdUnitSize adUnitSize = new AdUnitSize(); adUnitSize.size = size; adUnitSize.environmentType = EnvironmentType.BROWSER; adUnit.adUnitSizes = new AdUnitSize[] { adUnitSize }; adUnits[i] = adUnit; } try { // Create the ad units on the server. adUnits = inventoryService.createAdUnits(adUnits); if (adUnits != null) { foreach (AdUnit adUnit in adUnits) { Console.WriteLine( "An ad unit with ID = '{0}' was created under parent with " + "ID = '{1}'.", adUnit.id, adUnit.parentId); } } else { Console.WriteLine("No ad units created."); } } catch (Exception e) { Console.WriteLine("Failed to create ad units. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (CustomFieldService customFieldService = user.GetService <CustomFieldService>()) { // Get the LineItemService. LineItemService lineItemService = user.GetService <LineItemService>(); // Set the IDs of the custom fields, custom field option, and line item. long customFieldId = long.Parse(_T("INSERT_STRING_CUSTOM_FIELD_ID_HERE")); long customFieldOptionId = long.Parse(_T("INSERT_CUSTOM_FIELD_OPTION_ID_HERE")); long lineItemId = long.Parse(_T("INSERT_LINE_ITEM_ID_HERE")); try { // Get the drop-down custom field id. long dropDownCustomFieldId = customFieldService .getCustomFieldOption(customFieldOptionId).customFieldId; StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", lineItemId); // Get the line item. LineItemPage lineItemPage = lineItemService.getLineItemsByStatement(statementBuilder.ToStatement()); LineItem lineItem = lineItemPage.results[0]; // Create custom field values. List <BaseCustomFieldValue> customFieldValues = new List <BaseCustomFieldValue>(); TextValue textValue = new TextValue(); textValue.value = "Custom field value"; CustomFieldValue customFieldValue = new CustomFieldValue(); customFieldValue.customFieldId = customFieldId; customFieldValue.value = textValue; customFieldValues.Add(customFieldValue); DropDownCustomFieldValue dropDownCustomFieldValue = new DropDownCustomFieldValue(); dropDownCustomFieldValue.customFieldId = dropDownCustomFieldId; dropDownCustomFieldValue.customFieldOptionId = customFieldOptionId; customFieldValues.Add(dropDownCustomFieldValue); // Only add existing custom field values for different custom fields than // the ones you are setting. if (lineItem.customFieldValues != null) { foreach (BaseCustomFieldValue oldCustomFieldValue in lineItem .customFieldValues) { if (!(oldCustomFieldValue.customFieldId == customFieldId) && !(oldCustomFieldValue.customFieldId == dropDownCustomFieldId)) { customFieldValues.Add(oldCustomFieldValue); } } } lineItem.customFieldValues = customFieldValues.ToArray(); // Update the line item on the server. LineItem[] lineItems = lineItemService.updateLineItems(new LineItem[] { lineItem }); if (lineItems != null) { foreach (LineItem updatedLineItem in lineItems) { List <String> customFieldValueStrings = new List <String>(); foreach (BaseCustomFieldValue baseCustomFieldValue in lineItem .customFieldValues) { if (baseCustomFieldValue is CustomFieldValue && ((CustomFieldValue)baseCustomFieldValue).value is TextValue) { customFieldValueStrings.Add("{ID: '" + baseCustomFieldValue.customFieldId + "', value: '" + ((TextValue)((CustomFieldValue)baseCustomFieldValue) .value).value + "'}"); } else if (baseCustomFieldValue is DropDownCustomFieldValue) { customFieldValueStrings.Add("{ID: '" + baseCustomFieldValue.customFieldId + "', custom field option ID: '" + ((DropDownCustomFieldValue)baseCustomFieldValue) .customFieldOptionId + "'}"); } } Console.WriteLine( "A line item with ID \"{0}\" set with custom field values " + "\"{1}\".", updatedLineItem.id, string.Join(", ", customFieldValueStrings.ToArray())); } } else { Console.WriteLine("No line items were updated."); } } catch (Exception e) { Console.WriteLine("Failed to update line items. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (NativeStyleService nativeStyleService = user.GetService <NativeStyleService>()) { // This value is typically loaded from a file or other resource. string htmlSnippet = @"<div id=""adunit"" style=""overflow: hidden;""> <img src=""[%Thirdpartyimpressiontracker%]"" style=""display:none""> <div class=""attribution"">Ad</div> <div class=""image""> <a class=""image-link"" href=""%%CLICK_URL_UNESC%%[%Thirdpartyclicktracker%]%%DEST_URL%%"" target=""_top""> <img src=""[%Image%]""> </a> </div> <div class=""app-icon""><img src=""[%Appicon%]""/></div> <div class=""title""> <a class=""title-link"" href=""%%CLICK_URL_UNESC%%[%Thirdpartyclicktracker%]%%DEST_URL%%"" target=""_top"">[%Headline%]</a> </div> <div class=""reviews""></div> <div class=""body""> <a class=""body-link"" href=""%%CLICK_URL_UNESC%%[%Thirdpartyclicktracker%]%%DEST_URL%%"" target=""_top"">[%Body%]</a> </div> <div class=""price"">[%Price%]</div> <div class=""button""> <a class=""button-link"" href=""%%CLICK_URL_UNESC%%[%Thirdpartyclicktracker%]%%DEST_URL%%"" target=""_top"">[%Calltoaction%]</a> </div> </div>"; string cssSnippet = @"body { background-color: rgba(255, 255, 255, 1); font-family: ""Roboto - Regular"", sans-serif; font - weight: normal; font - size: 12px; line - height: 14px; } .attribution { background-color: rgba(236, 182, 0, 1); color: rgba(255, 255, 255, 1); font-size: 13px; display: table; margin: 4px 8px; padding: 0 3px; border-radius: 2px; } .image { text-align: center; margin: 8px; } .image img, .image-link { width: 100%; } .app-icon { float: left; margin: 0 8px 4px 8px; height: 40px; width: 40px; background-color: transparent; } .app-icon img { height: 100%; width: 100%; border-radius: 20%; } .title { font-weight: bold; font-size: 14px; line-height: 20px; margin: 8px 8px 4px 8px; } .title a { color: rgba(112, 112, 112, 1); text-decoration: none; } .reviews { float: left; } .reviews svg { fill: rgba(0, 0, 0, 0.7); } .body { clear: left; margin: 8px; } .body a { color: rgba(110, 110, 110, 1); text-decoration: none; } .price { display: none; } .button { font-size: 14px; font-weight: bold; float: right; margin: 0px 16px 16px 0px; white-space: nowrap; } .button a { color: #2196F3; text-decoration: none; } .button svg { display: none; }"; // Create nativeStyle size. Size size = new Size(); size.width = 300; size.height = 250; // Create a native style. NativeStyle nativeStyle = new NativeStyle(); nativeStyle.name = string.Format("Native style #{0}", new Random().Next()); nativeStyle.size = size; nativeStyle.htmlSnippet = htmlSnippet; nativeStyle.cssSnippet = cssSnippet; // This is the creative template ID for the system-defined native app // install ad format, which we will create the native style from. Use // CreativeTemplateService.getCreativeTemplatesByStatement() and // CreativeTemplate.isNativeEligible to get other native ad formats // availablein your network. nativeStyle.creativeTemplateId = 10004400; try { // Create the native styles on the server. NativeStyle[] nativeStyles = nativeStyleService.createNativeStyles( new NativeStyle[] { nativeStyle }); if (nativeStyles != null) { foreach (NativeStyle createdNativeStyle in nativeStyles) { // Print out some information for each created native style. Console.WriteLine( "A native style with ID ='{0}' and name='{1}' was created.", createdNativeStyle.id, createdNativeStyle.name); } } } catch (Exception e) { Console.WriteLine("Failed to create native styles. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (OrderService orderService = user.GetService <OrderService>()) { // Set the ID of the order. long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE")); // Create statement to select the order. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", orderId); // Set default for page. OrderPage page = new OrderPage(); List <string> orderIds = new List <string>(); int i = 0; try { do { // Get orders by statement. page = orderService.getOrdersByStatement(statementBuilder.ToStatement()); if (page.results != null) { foreach (Order order in page.results) { Console.WriteLine( "{0}) Order with ID = '{1}', name = '{2}', and status ='{3}' " + "will be approved.", i, order.id, order.name, order.status); orderIds.Add(order.id.ToString()); i++; } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of orders to be approved: {0}", orderIds.Count); if (orderIds.Count > 0) { // Modify statement for action. statementBuilder.RemoveLimitAndOffset(); // Create action. ApproveAndOverbookOrders action = new ApproveAndOverbookOrders(); // Perform action. UpdateResult result = orderService.performOrderAction(action, statementBuilder.ToStatement()); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of orders approved: {0}", result.numChanges); } else { Console.WriteLine("No orders were approved."); } } } catch (Exception e) { Console.WriteLine("Failed to approve orders. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (PublisherQueryLanguageService pqlService = user.GetService <PublisherQueryLanguageService>()) { // Create statement to select recent changes. Change_History only supports ordering // by descending ChangeDateTime. Offset is not supported. To page, use the change ID // of the earliest change as a pagination token. A date time range is required when // querying this table. System.DateTime endDateTime = System.DateTime.Now; System.DateTime startDateTime = endDateTime.AddDays(-1); StatementBuilder statementBuilder = new StatementBuilder() .Select("Id, ChangeDateTime, EntityId, EntityType, Operation, UserId") .From("Change_History") .Where("ChangeDateTime < :endDateTime AND ChangeDateTime > :startDateTime") .OrderBy("ChangeDateTime DESC") .AddValue("startDateTime", DateTimeUtilities.FromDateTime(startDateTime, "America/New_York")) .AddValue("endDateTime", DateTimeUtilities.FromDateTime(endDateTime, "America/New_York")) .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); int resultSetSize = 0; List <Row> allRows = new List <Row>(); ResultSet resultSet; do { resultSet = pqlService.select(statementBuilder.ToStatement()); if (resultSet.rows != null && resultSet.rows.Length > 0) { // Get the earliest change ID in the result set. Row lastRow = resultSet.rows[resultSet.rows.Length - 1]; string lastId = (string)PqlUtilities.GetValue(lastRow.values[0]); // Collect all changes from each page. allRows.AddRange(resultSet.rows); // Display results. Console.WriteLine(PqlUtilities.ResultSetToString(resultSet)); // Use the earliest change ID in the result set to page. statementBuilder .Where("Id < :id AND ChangeDateTime < :endDateTime AND " + "ChangeDateTime > :startDateTime").AddValue("id", lastId); } resultSetSize = resultSet.rows == null ? 0 : resultSet.rows.Length; } while (resultSetSize == StatementBuilder.SUGGESTED_PAGE_LIMIT); Console.WriteLine("Number of results found: " + allRows.Count); // Optionally, save all rows to a CSV. // Get a string array representation of the data rows. resultSet.rows = allRows.ToArray(); List <String[]> rows = PqlUtilities.ResultSetToStringArrayList(resultSet); // Write the contents to a csv file. CsvFile file = new CsvFile(); file.Headers.AddRange(rows[0]); file.Records.AddRange(rows.GetRange(1, rows.Count - 1).ToArray()); file.Write("recent_changes_" + this.GetTimeStamp() + ".csv"); } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (CustomFieldService customFieldService = user.GetService <CustomFieldService>()) { // Set the ID of the custom field to update. int customFieldId = int.Parse(_T("INSERT_CUSTOM_FIELD_ID_HERE")); // Create statement to select only active custom fields that apply to // line items. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", customFieldId); // Set default for page. CustomFieldPage page = new CustomFieldPage(); int i = 0; List <string> customFieldIds = new List <string>(); try { do { // Get custom fields by statement. page = customFieldService.getCustomFieldsByStatement( statementBuilder.ToStatement()); if (page.results != null) { foreach (CustomField customField in page.results) { Console.WriteLine( "{0}) Custom field with ID \"{1}\" and name \"{2}\" will be " + "deactivated.", i, customField.id, customField.name); customFieldIds.Add(customField.id.ToString()); i++; } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of custom fields to be deactivated: " + customFieldIds.Count); if (customFieldIds.Count > 0) { // Remove limit and offset from statement. statementBuilder.RemoveLimitAndOffset(); // Create action. Google.Api.Ads.AdManager.v201805.DeactivateCustomFields action = new Google.Api.Ads.AdManager.v201805.DeactivateCustomFields(); // Perform action. UpdateResult result = customFieldService.performCustomFieldAction(action, statementBuilder.ToStatement()); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of custom fields deactivated: " + result.numChanges); } else { Console.WriteLine("No custom fields were deactivated."); } } } catch (Exception e) { Console.WriteLine("Failed to deactivate custom fields. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (LineItemService lineItemService = user.GetService <LineItemService>()) { // Set the ID of the order to get line items from. long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE")); // Create statement to select approved line items from a given order. StatementBuilder statementBuilder = new StatementBuilder() .Where("orderId = :orderId and status = :status").AddValue("orderId", orderId) .AddValue("status", ComputedStatus.INACTIVE.ToString()); // Set default for page. LineItemPage page = new LineItemPage(); List <string> lineItemIds = new List <string>(); try { do { // Get line items by statement. page = lineItemService.getLineItemsByStatement( statementBuilder.ToStatement()); if (page.results != null) { int i = page.startIndex; foreach (LineItemSummary lineItem in page.results) { // Archived line items cannot be activated. if (!lineItem.isArchived) { Console.WriteLine( "{0}) Line item with ID ='{1}', belonging to order " + "ID ='{2}' and name ='{3}' will be activated.", i, lineItem.id, lineItem.orderId, lineItem.name); lineItemIds.Add(lineItem.id.ToString()); i++; } } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of line items to be activated: {0}", lineItemIds.Count); if (lineItemIds.Count > 0) { // Modify statement. statementBuilder.RemoveLimitAndOffset(); // Create action. ActivateLineItems action = new ActivateLineItems(); // Perform action. UpdateResult result = lineItemService.performLineItemAction(action, statementBuilder.ToStatement()); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of line items activated: {0}", result.numChanges); } else { Console.WriteLine("No line items were activated."); } } } catch (Exception e) { Console.WriteLine("Failed to activate line items. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (ReportService reportService = user.GetService <ReportService>()) using (NetworkService networkService = user.GetService <NetworkService>()) { // Set the file path where the report will be saved. String filePath = _T("INSERT_FILE_PATH_HERE"); // Get the root ad unit ID to filter on. String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId; // Create statement to filter on an ancestor ad unit with the root ad unit ID to // include all ad units in the network. StatementBuilder statementBuilder = new StatementBuilder() .Where("PARENT_AD_UNIT_ID = :parentAdUnitId") .AddValue("parentAdUnitId", long.Parse(rootAdUnitId)); // Create report query. ReportQuery reportQuery = new ReportQuery(); reportQuery.dimensions = new Dimension[] { Dimension.AD_UNIT_ID, Dimension.AD_UNIT_NAME }; reportQuery.columns = new Column[] { Column.AD_SERVER_IMPRESSIONS, Column.AD_SERVER_CLICKS, Column.ADSENSE_LINE_ITEM_LEVEL_IMPRESSIONS, Column.ADSENSE_LINE_ITEM_LEVEL_CLICKS, Column.TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS, Column.TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE }; // Set the filter statement. reportQuery.statement = statementBuilder.ToStatement(); reportQuery.adUnitView = ReportQueryAdUnitView.HIERARCHICAL; reportQuery.dateRangeType = DateRangeType.LAST_WEEK; // Create report job. ReportJob reportJob = new ReportJob(); reportJob.reportQuery = reportQuery; try { // Run report. reportJob = reportService.runReportJob(reportJob); ReportUtilities reportUtilities = new ReportUtilities(reportService, reportJob.id); // Set download options. ReportDownloadOptions options = new ReportDownloadOptions(); options.exportFormat = ExportFormat.CSV_DUMP; options.useGzipCompression = true; reportUtilities.reportDownloadOptions = options; // Download the report. using (ReportResponse reportResponse = reportUtilities.GetResponse()) { reportResponse.Save(filePath); } Console.WriteLine("Report saved to \"{0}\".", filePath); } catch (Exception e) { Console.WriteLine("Failed to run inventory report. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (CdnConfigurationService cdnConfigurationService = user.GetService <CdnConfigurationService>()) { // Make CND configuration objects. // Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. // Basic example with no security policies. SecurityPolicySettings noSecurityPolicy = new SecurityPolicySettings() { securityPolicyType = SecurityPolicyType.NONE }; CdnConfiguration cdnConfigurationWithoutSecurityPolicy = new CdnConfiguration() { name = "ApiConfig1", cdnConfigurationType = CdnConfigurationType.LIVE_STREAM_SOURCE_CONTENT, sourceContentConfiguration = new SourceContentConfiguration() { ingestSettings = new MediaLocationSettings() { urlPrefix = "example.google.com", securityPolicy = noSecurityPolicy }, defaultDeliverySettings = new MediaLocationSettings() { urlPrefix = "example.google.com", securityPolicy = noSecurityPolicy } } }; // Complex example with security policies. CdnConfiguration cdnConfigurationWithSecurityPolicy = new CdnConfiguration() { name = "ApiConfig2", cdnConfigurationType = CdnConfigurationType.LIVE_STREAM_SOURCE_CONTENT, sourceContentConfiguration = new SourceContentConfiguration() { ingestSettings = new MediaLocationSettings() { urlPrefix = "example.google.com", securityPolicy = new SecurityPolicySettings() { securityPolicyType = SecurityPolicyType.AKAMAI, disableServerSideUrlSigning = false, tokenAuthenticationKey = "abc123" } }, defaultDeliverySettings = new MediaLocationSettings() { urlPrefix = "example.google.com", securityPolicy = new SecurityPolicySettings() { securityPolicyType = SecurityPolicyType.AKAMAI, disableServerSideUrlSigning = false, originForwardingType = OriginForwardingType.CONVENTIONAL, originPathPrefix = "/path/to/my/origin" } } } }; try { // Create the CDN configurations on the server. CdnConfiguration[] cdnConfigurations = cdnConfigurationService.createCdnConfigurations(new CdnConfiguration[] { cdnConfigurationWithoutSecurityPolicy, cdnConfigurationWithSecurityPolicy }); foreach (CdnConfiguration createdCdnConfiguration in cdnConfigurations) { Console.WriteLine( "A CDN configuration with ID \"{0}\" and name \"{1}\" was created.", createdCdnConfiguration.id, createdCdnConfiguration.name); } } catch (Exception e) { Console.WriteLine("Failed to create company. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (CreativeWrapperService creativeWrapperService = user.GetService <CreativeWrapperService>()) { long labelId = long.Parse(_T("INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE")); try { // Create a query to select the active creative wrapper for the given // label. StatementBuilder statementBuilder = new StatementBuilder() .Where("labelId = :labelId AND status = :status").OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .AddValue("status", CreativeWrapperStatus.ACTIVE.ToString()) .AddValue("labelId", labelId); // Set default for page. CreativeWrapperPage page = new CreativeWrapperPage(); do { page = creativeWrapperService.getCreativeWrappersByStatement( statementBuilder.ToStatement()); CreativeWrapper[] creativeWrappers = page.results; if (creativeWrappers != null) { foreach (CreativeWrapper wrapper in creativeWrappers) { Console.WriteLine( "Creative wrapper with ID '{0}' applying to label " + "'{1}' with status '{2}' will be deactivated.", wrapper.id, wrapper.labelId, wrapper.status); } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of creative wrappers to be deactivated: {0}", page.totalResultSetSize); // Modify statement for action. statementBuilder.RemoveLimitAndOffset(); // Perform action. CreativeWrapperAction action = new DeactivateCreativeWrappers(); UpdateResult result = creativeWrapperService.performCreativeWrapperAction(action, statementBuilder.ToStatement()); // Display results. if (result.numChanges > 0) { Console.WriteLine("Number of creative wrappers deactivated: {0}", result.numChanges); } else { Console.WriteLine("No creative wrappers were deactivated."); } } catch (Exception e) { Console.WriteLine("Failed to create creative wrappers. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (PublisherQueryLanguageService pqlService = user.GetService <PublisherQueryLanguageService>()) { // First day of last month. System.DateTime lastMonth = System.DateTime.Now .AddDays(1 - System.DateTime.Now.Day) .AddMonths(-1); // Create statement to select MCM earnings for the prior month. StatementBuilder statementBuilder = new StatementBuilder() .Select("Month, ChildName, ChildNetworkCode, TotalEarningsCurrencyCode," + " TotalEarningsMicros, ParentPaymentCurrencyCode, ParentPaymentMicros," + " ChildPaymentCurrencyCode, ChildPaymentMicros, DeductionsMicros") .From("Mcm_Earnings") .Where("Month = :month") .OrderBy("ChildNetworkCode") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .AddValue("month", DateTimeUtilities.FromDateTime(lastMonth, "America/New_York").date); int resultSetSize = 0; List <Row> allRows = new List <Row>(); ResultSet resultSet; try { do { // Get earnings information. resultSet = pqlService.select(statementBuilder.ToStatement()); // Collect all data from each page. allRows.AddRange(resultSet.rows); // Display results. Console.WriteLine(PqlUtilities.ResultSetToString(resultSet)); statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); resultSetSize = resultSet.rows == null ? 0 : resultSet.rows.Length; } while (resultSetSize == StatementBuilder.SUGGESTED_PAGE_LIMIT); Console.WriteLine("Number of results found: " + allRows.Count); // Optionally, save all rows to a CSV. // Get a string array representation of the data rows. resultSet.rows = allRows.ToArray(); List <String[]> rows = PqlUtilities.ResultSetToStringArrayList(resultSet); // Write the contents to a csv file. CsvFile file = new CsvFile(); file.Headers.AddRange(rows[0]); file.Records.AddRange(rows.GetRange(1, rows.Count - 1).ToArray()); file.Write("Earnings_Report_" + this.GetTimeStamp() + ".csv"); } catch (Exception e) { Console.WriteLine("Failed to get MCM earnings. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (PlacementService placementService = user.GetService <PlacementService>()) { // Create statement to select active placements. StatementBuilder statementBuilder = new StatementBuilder() .Where("status = :status") .OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .AddValue("status", InventoryStatus.ACTIVE.ToString()); // Sets default for page. PlacementPage page = new PlacementPage(); List <string> placementIds = new List <string>(); try { do { // Get placements by statement. page = placementService.getPlacementsByStatement(statementBuilder .ToStatement()); if (page.results != null) { int i = page.startIndex; foreach (Placement placement in page.results) { Console.WriteLine( "{0}) Placement with ID ='{1}', name ='{2}', and " + "status ='{3}' will be deactivated.", i, placement.id, placement.name, placement.status); placementIds.Add(placement.id.ToString()); i++; } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of placements to be deactivated: {0}", placementIds.Count); if (placementIds.Count > 0) { // Modify statement for action. statementBuilder.RemoveLimitAndOffset(); // Create action. DeactivatePlacements action = new DeactivatePlacements(); // Perform action. UpdateResult result = placementService.performPlacementAction(action, statementBuilder.ToStatement()); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of placements deactivated: {0}", result.numChanges); } else { Console.WriteLine("No placements were deactivated."); } } } catch (Exception e) { Console.WriteLine("Failed to deactivate placements. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (LineItemService lineItemService = user.GetService <LineItemService>()) { // Set the order that all created line items will belong to and the // video ad unit ID to target. long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE")); string targetedVideoAdUnitId = _T("INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE"); // Set the content bundle to target long contentBundleId = long.Parse(_T("INSERT_CONTENT_BUNDLE_ID_HERE")); // Set the CMS metadata value to target long cmsMetadataValueId = long.Parse(_T("INSERT_CMS_METADATA_VALUE_ID_HERE")); // Create content targeting. ContentTargeting contentTargeting = new ContentTargeting() { targetedVideoContentBundleIds = new long[] { contentBundleId } }; // Create inventory targeting. InventoryTargeting inventoryTargeting = new InventoryTargeting() { targetedAdUnits = new AdUnitTargeting[] { new AdUnitTargeting() { adUnitId = targetedVideoAdUnitId, includeDescendants = true } } }; // Create video position targeting. VideoPositionTargeting videoPositionTargeting = new VideoPositionTargeting() { targetedPositions = new VideoPositionTarget[] { new VideoPositionTarget() { videoPosition = new VideoPosition() { positionType = VideoPositionType.PREROLL } } } }; // Target only video platforms RequestPlatformTargeting requestPlatformTargeting = new RequestPlatformTargeting() { targetedRequestPlatforms = new RequestPlatform[] { RequestPlatform.VIDEO_PLAYER } }; // Create custom criteria set CustomCriteriaSet customCriteriaSet = new CustomCriteriaSet() { logicalOperator = CustomCriteriaSetLogicalOperator.AND, children = new CustomCriteriaNode[] { new CmsMetadataCriteria() { cmsMetadataValueIds = new long[] { cmsMetadataValueId }, @operator = CmsMetadataCriteriaComparisonOperator.EQUALS } } }; // Create targeting. Targeting targeting = new Targeting() { contentTargeting = contentTargeting, inventoryTargeting = inventoryTargeting, videoPositionTargeting = videoPositionTargeting, requestPlatformTargeting = requestPlatformTargeting, customTargeting = customCriteriaSet }; // Create local line item object. LineItem lineItem = new LineItem() { name = "Video line item - " + this.GetTimeStamp(), orderId = orderId, targeting = targeting, lineItemType = LineItemType.SPONSORSHIP, allowOverbook = true, environmentType = EnvironmentType.VIDEO_PLAYER, creativeRotationType = CreativeRotationType.OPTIMIZED, // Set the maximum video creative length for this line item to 15 seconds. videoMaxDuration = 15000L }; // Create the master creative placeholder. CreativePlaceholder creativeMasterPlaceholder = new CreativePlaceholder() { size = new Size() { width = 400, height = 300, isAspectRatio = false } }; // Create companion creative placeholders. CreativePlaceholder companionCreativePlaceholder1 = new CreativePlaceholder() { size = new Size() { width = 300, height = 250, isAspectRatio = false } }; CreativePlaceholder companionCreativePlaceholder2 = new CreativePlaceholder() { size = new Size() { width = 728, height = 90, isAspectRatio = false } }; // Set companion creative placeholders. creativeMasterPlaceholder.companions = new CreativePlaceholder[] { companionCreativePlaceholder1, companionCreativePlaceholder2 }; // Set the size of creatives that can be associated with this line item. lineItem.creativePlaceholders = new CreativePlaceholder[] { creativeMasterPlaceholder }; // Set delivery of video companions to optional. lineItem.companionDeliveryOption = CompanionDeliveryOption.OPTIONAL; // Set the line item to run for one month. lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY; lineItem.endDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Now.AddMonths(1), "America/New_York"); // Set the cost per day to $1. lineItem.costType = CostType.CPD; lineItem.costPerUnit = new Money() { currencyCode = "USD", microAmount = 1000000L }; // Set the percentage to be 100%. lineItem.primaryGoal = new Goal() { goalType = GoalType.DAILY, unitType = UnitType.IMPRESSIONS, units = 100 }; try { // Create the line item on the server. LineItem[] createdLineItems = lineItemService.createLineItems(new LineItem[] { lineItem }); foreach (LineItem createdLineItem in createdLineItems) { Console.WriteLine( "A line item with ID \"{0}\", belonging to order ID \"{1}\", and " + "named \"{2}\" was created.", createdLineItem.id, createdLineItem.orderId, createdLineItem.name); } } catch (Exception e) { Console.WriteLine("Failed to create line items. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (ForecastService forecastService = user.GetService <ForecastService>()) { // Set the placement that the prospective line item will target. long[] targetPlacementIds = new long[] { long.Parse(_T("INSERT_PLACEMENT_ID_HERE")) }; // Set the ID of the advertiser (company) to forecast for. Setting an advertiser // will cause the forecast to apply the appropriate unified blocking rules. long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); // Create prospective line item. LineItem lineItem = new LineItem(); lineItem.targeting = new Targeting(); lineItem.targeting.inventoryTargeting = new InventoryTargeting(); lineItem.targeting.inventoryTargeting.targetedPlacementIds = targetPlacementIds; Size size = new Size(); size.width = 300; size.height = 250; // Create the creative placeholder. CreativePlaceholder creativePlaceholder = new CreativePlaceholder(); creativePlaceholder.size = size; lineItem.creativePlaceholders = new CreativePlaceholder[] { creativePlaceholder }; lineItem.lineItemType = LineItemType.SPONSORSHIP; lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY; // Set the line item to run for one month. lineItem.endDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Now.AddMonths(1), "America/New_York"); // Set the cost type to match the unit type. lineItem.costType = CostType.CPM; Goal goal = new Goal(); goal.goalType = GoalType.DAILY; goal.unitType = UnitType.IMPRESSIONS; goal.units = 50L; lineItem.primaryGoal = goal; try { // Get availability forecast. AvailabilityForecastOptions options = new AvailabilityForecastOptions(); options.includeContendingLineItems = true; options.includeTargetingCriteriaBreakdown = true; ProspectiveLineItem prospectiveLineItem = new ProspectiveLineItem(); prospectiveLineItem.advertiserId = advertiserId; prospectiveLineItem.lineItem = lineItem; AvailabilityForecast forecast = forecastService.getAvailabilityForecast(prospectiveLineItem, options); // Display results. long matched = forecast.matchedUnits; double availablePercent = (double)(forecast.availableUnits / (matched * 1.0)) * 100; String unitType = forecast.unitType.ToString().ToLower(); Console.WriteLine("{0} {1} matched.\n{2}% {3} available.", matched, unitType, availablePercent, unitType); if (forecast.possibleUnitsSpecified) { double possiblePercent = (double)(forecast.possibleUnits / (matched * 1.0)) * 100; Console.WriteLine("{0}% {1} possible.\n", possiblePercent, unitType); } Console.WriteLine("{0} contending line items.", (forecast.contendingLineItems != null) ? forecast.contendingLineItems.Length : 0); } catch (Exception e) { Console.WriteLine("Failed to get forecast. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (CreativeService creativeService = user.GetService <CreativeService>()) { long creativeId = long.Parse(_T("INSERT_IMAGE_CREATIVE_ID_HERE")); // Create a statement to get the image creative. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .AddValue("id", creativeId); try { // Get the creative. CreativePage page = creativeService.getCreativesByStatement(statementBuilder.ToStatement()); if (page.results != null) { ImageCreative imageCreative = (ImageCreative)page.results[0]; // Since we cannot set id to null, we mark it as not specified. imageCreative.idSpecified = false; imageCreative.advertiserId = imageCreative.advertiserId; imageCreative.name = imageCreative.name + " (Copy #" + GetTimeStamp() + ")"; // Create image asset. CreativeAsset creativeAsset = new CreativeAsset(); creativeAsset.fileName = "image.jpg"; creativeAsset.assetByteArray = MediaUtilities.GetAssetDataFromUrl( imageCreative.primaryImageAsset.assetUrl, user.Config); creativeAsset.size = imageCreative.primaryImageAsset.size; imageCreative.primaryImageAsset = creativeAsset; // Create the copied creative. Creative[] creatives = creativeService.createCreatives(new Creative[] { imageCreative }); // Display copied creatives. foreach (Creative copiedCreative in creatives) { Console.WriteLine( "Image creative with ID \"{0}\", name \"{1}\", and type \"{2}\" " + "was created and can be previewed at {3}", copiedCreative.id, copiedCreative.name, copiedCreative.GetType().Name, copiedCreative.previewUrl); } } else { Console.WriteLine("No creatives were copied."); } } catch (Exception e) { Console.WriteLine("Failed to copy creatives. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (LabelService labelService = user.GetService <LabelService>()) { // Set the ID of the label to deactivate. int labelId = int.Parse(_T("INSERT_LABEL_ID_HERE")); // Create statement text to select the label. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", labelId); // Set default for page. LabelPage page = new LabelPage(); try { do { // Get labels by statement. page = labelService.getLabelsByStatement(statementBuilder.ToStatement()); if (page.results != null) { int i = page.startIndex; foreach (Label label in page.results) { Console.WriteLine( "{0}) Label with ID '{1}', name '{2}' will be deactivated.", i, label.id, label.name); i++; } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of labels to be deactivated: " + page.totalResultSetSize); // Modify statement for action. statementBuilder.RemoveLimitAndOffset(); // Create action. DeactivateLabels action = new DeactivateLabels(); // Perform action. UpdateResult result = labelService.performLabelAction(action, statementBuilder.ToStatement()); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of labels deactivated: " + result.numChanges); } else { Console.WriteLine("No labels were deactivated."); } } catch (Exception e) { Console.WriteLine("Failed to deactivate labels. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (SuggestedAdUnitService suggestedAdUnitService = user.GetService <SuggestedAdUnitService>()) { // Set the number of requests for suggested ad units greater than which to approve. long NUMBER_OF_REQUESTS = 50L; // Create statement to select all suggested ad units that are highly requested. StatementBuilder statementBuilder = new StatementBuilder() .Where("numRequests > :numRequests").OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .AddValue("numRequests", NUMBER_OF_REQUESTS); // Set default for page. SuggestedAdUnitPage page = new SuggestedAdUnitPage(); try { do { // Get suggested ad units by statement. page = suggestedAdUnitService.getSuggestedAdUnitsByStatement( statementBuilder.ToStatement()); int i = 0; if (page != null && page.results != null) { foreach (SuggestedAdUnit suggestedAdUnit in page.results) { Console.WriteLine( "{0}) Suggested ad unit with ID \"{1}\", and \"{2}\" will be " + "approved.", i, suggestedAdUnit.id, suggestedAdUnit.numRequests); i++; } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of suggested ad units to be approved: " + page.totalResultSetSize); // Modify statement for action. statementBuilder.RemoveLimitAndOffset(); // Create action. Google.Api.Ads.AdManager.v201908.ApproveSuggestedAdUnits action = new Google.Api.Ads.AdManager.v201908.ApproveSuggestedAdUnits(); // Perform action. SuggestedAdUnitUpdateResult result = suggestedAdUnitService.performSuggestedAdUnitAction(action, statementBuilder.ToStatement()); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of new ad units created: " + result.newAdUnitIds.Length); } else { Console.WriteLine("No suggested ad units were approved."); } } catch (Exception e) { Console.WriteLine( "Failed to approve suggested ad units. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user, long savedQueryId) { using (ReportService reportService = user.GetService <ReportService>()) { // Set the file path where the report will be saved. String filePath = _T("INSERT_FILE_PATH_HERE"); // Create statement to retrieve the saved query. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", savedQueryId); SavedQueryPage page = reportService.getSavedQueriesByStatement(statementBuilder.ToStatement()); SavedQuery savedQuery = page.results[0]; if (!savedQuery.isCompatibleWithApiVersion) { throw new InvalidOperationException("Saved query is not compatible with this " + "API version"); } // Optionally modify the query. ReportQuery reportQuery = savedQuery.reportQuery; reportQuery.adUnitView = ReportQueryAdUnitView.HIERARCHICAL; // Create a report job using the saved query. ReportJob reportJob = new ReportJob(); reportJob.reportQuery = reportQuery; try { // Run report. reportJob = reportService.runReportJob(reportJob); ReportUtilities reportUtilities = new ReportUtilities(reportService, reportJob.id); // Set download options. ReportDownloadOptions options = new ReportDownloadOptions(); options.exportFormat = ExportFormat.CSV_DUMP; options.useGzipCompression = true; reportUtilities.reportDownloadOptions = options; // Download the report. using (ReportResponse reportResponse = reportUtilities.GetResponse()) { reportResponse.Save(filePath); } Console.WriteLine("Report saved to \"{0}\".", filePath); } catch (Exception e) { Console.WriteLine("Failed to run saved query. Exception says \"{0}\"", e.Message); } } }