/// <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 example. /// </summary> public void Run(AdManagerUser user) { using (ForecastService forecastService = user.GetService <ForecastService>()) using (NetworkService networkService = user.GetService <NetworkService>()) { String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId; // Set the date range to include System.DateTime startDate = System.DateTime.Today.AddDays(-7); System.DateTime endDate = System.DateTime.Today.AddDays(7); TrafficDataRequest trafficDataRequest = new TrafficDataRequest() { requestedDateRange = new DateRange() { startDate = DateTimeUtilities.FromDateTime(startDate, "America/New_York").date, endDate = DateTimeUtilities.FromDateTime(endDate, "America/New_York").date }, targeting = new Targeting() { inventoryTargeting = new InventoryTargeting() { targetedAdUnits = new AdUnitTargeting[] { new AdUnitTargeting() { adUnitId = rootAdUnitId, includeDescendants = true } } } } }; try { TrafficDataResponse trafficData = forecastService.getTrafficData(trafficDataRequest); TimeSeries historicalTimeSeries = trafficData.historicalTimeSeries; if (historicalTimeSeries != null) { Date historicalStartDate = historicalTimeSeries.timeSeriesDateRange.startDate; System.DateTime startDateTime = new System.DateTime( historicalStartDate.year, historicalStartDate.month, historicalStartDate.day); for (int i = 0; i < historicalTimeSeries.values.Length; i++) { Console.WriteLine("{0}: {1} historical ad opportunities", startDateTime.AddDays(i).ToString("yyyy-MM-dd"), historicalTimeSeries.values[i]); } } TimeSeries forecastedTimeSeries = trafficData.forecastedTimeSeries; if (forecastedTimeSeries != null) { Date forecastedStartDate = forecastedTimeSeries.timeSeriesDateRange.startDate; System.DateTime startDateTime = new System.DateTime( forecastedStartDate.year, forecastedStartDate.month, forecastedStartDate.day); for (int i = 0; i < forecastedTimeSeries.values.Length; i++) { Console.WriteLine("{0}: {1} forecasted ad opportunities", startDateTime.AddDays(i).ToString("yyyy-MM-dd"), forecastedTimeSeries.values[i]); } } } catch (Exception e) { Console.WriteLine("Failed to get traffic data. 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"); } }