/// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="user">The DFP user object running the code example.</param>
    public override void Run(DfpUser user) {
      // Get the ForecastService.
      ForecastService forecastService =
          (ForecastService)user.GetService(DfpService.v201403.ForecastService);

      // Set the placement that the prospective line item will target.
      long[] targetPlacementIds = new long[] {long.Parse(_T("INSERT_PLACEMENT_ID_HERE"))};

      // Set the end date time to have the line line item run till.
      string endDateTime = "INSERT_END_DATE_TIME_HERE (yyyyMMdd HH:mm:ss)";

      // 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;

      lineItem.endDateTime = DateTimeUtilities.FromString(endDateTime);

      // Set the cost type to match the unit type.
      lineItem.costType = CostType.CPM;

      try {
        // Get forecast.
        Forecast forecast = forecastService.getForecast(lineItem);

        // 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}%  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 ex) {
        Console.WriteLine("Failed to get forecast. Exception says \"{0}\"", ex.Message);
      }
    }
        public void TestCreateLineItems()
        {
            // Create inventory targeting.
            InventoryTargeting inventoryTargeting = new InventoryTargeting();

            inventoryTargeting.targetedPlacementIds = new long[] { placementId };

            // 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 };

            // 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.Dfp.v201602.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.Dfp.v201602.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[2];

            for (int i = 0; i < lineItems.Length; i++)
            {
                LineItem lineItem = new LineItem();
                lineItem.name      = "Line item #" + new TestUtils().GetTimeStamp();
                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.units           = 500000L;
                goal.unitType        = UnitType.IMPRESSIONS;
                lineItem.primaryGoal = goal;

                lineItems[i] = lineItem;
            }

            LineItem[] localLineItems = null;

            Assert.DoesNotThrow(delegate() {
                localLineItems = lineItemService.createLineItems(lineItems);
            });

            Assert.NotNull(localLineItems);
            Assert.AreEqual(localLineItems.Length, 2);

            Assert.AreEqual(localLineItems[0].name, lineItems[0].name);
            Assert.AreEqual(localLineItems[0].orderId, lineItems[0].orderId);

            Assert.AreEqual(localLineItems[1].name, lineItems[1].name);
            Assert.AreEqual(localLineItems[1].orderId, lineItems[1].orderId);
        }
        /// <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 = "Programmatic 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 programmatic proposal line item with ID \"{0}\" " +
                                "and name \"{1}\" was created.", createdProposalLineItem.id,
                                createdProposalLineItem.name);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(
                            "Failed to create programmatic proposal line items. " +
                            "Exception says \"{0}\"", e.Message);
                    }
                }
        }
示例#4
0
        /// <summary>
        /// Run the code examples.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the ProductTemplateService.
            ProductTemplateService productTemplateService =
                (ProductTemplateService)user.GetService(DfpService.v201705.ProductTemplateService);

            // Get the NetworkService.
            NetworkService networkService =
                (NetworkService)user.GetService(DfpService.v201705.NetworkService);

            // Create a product template.
            ProductTemplate productTemplate = new ProductTemplate();

            productTemplate.name        = "Product template #" + new Random().Next(int.MaxValue);
            productTemplate.description = "This product template creates standard proposal line items "
                                          + "targeting Chrome browsers with product segmentation on ad units and geo targeting.";

            // Set the name macro which will be used to generate the names of the products.
            // This will create a segmentation based on the line item type, ad unit, and location.
            productTemplate.nameMacro = "<line-item-type> - <ad-unit> - <template-name> - <location>";

            // Set the product type so the created proposal line items will be trafficked in DFP.
            productTemplate.productType = ProductType.DFP;

            // Set rate type to create CPM priced proposal line items.
            productTemplate.rateType = RateType.CPM;

            // Optionally set the creative rotation of the product to serve one or more creatives.
            productTemplate.roadblockingType = RoadblockingType.ONE_OR_MORE;
            productTemplate.deliveryRateType = DeliveryRateType.AS_FAST_AS_POSSIBLE;

            // Create the master creative placeholder.
            CreativePlaceholder creativeMasterPlaceholder = new CreativePlaceholder();

            creativeMasterPlaceholder.size =
                new Size()
            {
                width = 728, height = 90, isAspectRatio = false
            };

            // Create companion creative placeholders.
            CreativePlaceholder companionCreativePlaceholder = new CreativePlaceholder();

            companionCreativePlaceholder.size =
                new Size()
            {
                width = 300, height = 250, isAspectRatio = false
            };

            // Set the size of creatives that can be associated with the product template.
            productTemplate.creativePlaceholders =
                new CreativePlaceholder[] { creativeMasterPlaceholder, companionCreativePlaceholder };

            // Set the type of proposal line item to be created from the product template.
            productTemplate.lineItemType = LineItemType.STANDARD;

            // Get the root ad unit ID used to target the whole site.
            String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;

            // Create ad unit targeting for the root ad unit (i.e. the whole network).
            AdUnitTargeting adUnitTargeting = new AdUnitTargeting();

            adUnitTargeting.adUnitId           = rootAdUnitId;
            adUnitTargeting.includeDescendants = true;

            // Create geo targeting for the US.
            Location countryLocation = new Location();

            countryLocation.id = 2840L;

            // Create geo targeting for Hong Kong.
            Location regionLocation = new Location();

            regionLocation.id = 2344L;

            GeoTargeting geoTargeting = new GeoTargeting();

            geoTargeting.targetedLocations = new Location[] { countryLocation, regionLocation };

            // Add browser targeting to Chrome on the product template distinct from product
            // segmentation.
            Browser chromeBrowser = new Browser();

            chromeBrowser.id = 500072L;

            BrowserTargeting browserTargeting = new BrowserTargeting();

            browserTargeting.browsers = new Browser[] { chromeBrowser };

            TechnologyTargeting technologyTargeting = new TechnologyTargeting();

            technologyTargeting.browserTargeting = browserTargeting;

            Targeting productTemplateTargeting = new Targeting();

            productTemplateTargeting.technologyTargeting = technologyTargeting;

            productTemplate.builtInTargeting = productTemplateTargeting;

            productTemplate.customizableAttributes = new CustomizableAttributes()
            {
                allowPlacementTargetingCustomization = true
            };

            // Add inventory and geo targeting as product segmentation.
            ProductSegmentation productSegmentation = new ProductSegmentation();

            productSegmentation.adUnitSegments = new AdUnitTargeting[] { adUnitTargeting };
            productSegmentation.geoSegment     = geoTargeting;

            productTemplate.productSegmentation = productSegmentation;

            try {
                // Create the product template on the server.
                ProductTemplate[] productTemplates = productTemplateService.createProductTemplates(
                    new ProductTemplate[] { productTemplate });

                foreach (ProductTemplate createdProductTemplate in productTemplates)
                {
                    Console.WriteLine("A product template with ID \"{0}\" and name \"{1}\" was created.",
                                      createdProductTemplate.id, createdProductTemplate.name);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create product templates. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        public void TestGetAvailabilityForecast()
        {
            TestUtils utils = new TestUtils();

            LineItem lineItem = new LineItem();

            lineItem.name = string.Format("Line item #{0}", utils.GetTimeStamp());

            lineItem.orderId = orderId;

            lineItem.targeting = new Targeting();
            lineItem.targeting.inventoryTargeting = new InventoryTargeting();
            lineItem.targeting.inventoryTargeting.targetedPlacementIds = new long[] { placementId };

            Size size1 = new Size();

            size1.width  = 300;
            size1.height = 250;

            Size size2 = new Size();

            size2.width  = 120;
            size2.height = 600;

            // Create the creative placeholders.
            CreativePlaceholder creativePlaceholder1 = new CreativePlaceholder();

            creativePlaceholder1.size = size1;

            CreativePlaceholder creativePlaceholder2 = new CreativePlaceholder();

            creativePlaceholder1.size = size2;

            lineItem.creativePlaceholders =
                new CreativePlaceholder[] { creativePlaceholder1, creativePlaceholder2 };

            lineItem.lineItemType = LineItemType.STANDARD;

            // Set start date time and end date time.
            lineItem.startDateTime =
                DateTimeUtilities.FromDateTime(System.DateTime.Today.AddDays(1), "America/New_York");
            lineItem.endDateTime =
                DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1), "America/New_York");

            lineItem.costType    = CostType.CPM;
            lineItem.costPerUnit = new Money();
            lineItem.costPerUnit.currencyCode = "USD";
            lineItem.costPerUnit.microAmount  = 2000000;

            lineItem.creativeRotationType = CreativeRotationType.EVEN;
            lineItem.discountType         = LineItemDiscountType.PERCENTAGE;

            Goal goal = new Goal();

            goal.units           = 500000;
            goal.unitType        = UnitType.IMPRESSIONS;
            lineItem.primaryGoal = goal;

            ProspectiveLineItem prospectiveLineItem = new ProspectiveLineItem();

            prospectiveLineItem.lineItem = lineItem;

            AvailabilityForecast forecast = null;

            Assert.DoesNotThrow(delegate() {
                forecast = forecastService.getAvailabilityForecast(prospectiveLineItem,
                                                                   new AvailabilityForecastOptions());
            });
            Assert.NotNull(forecast);
            Assert.AreEqual(forecast.orderId, orderId);
            Assert.AreEqual(forecast.unitType, lineItem.primaryGoal.unitType);
        }
        public LineItem CreateLineItem(DfpUser user, long orderId, string adUnitId)
        {
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201306.LineItemService);

            long placementId = CreatePlacement(user, new string[] { adUnitId }).id;

            // Create inventory targeting.
            InventoryTargeting inventoryTargeting = new InventoryTargeting();

            inventoryTargeting.targetedPlacementIds = new long[] { placementId };

            // 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 };

            // 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.Dfp.v201306.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.Dfp.v201306.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;

            LineItem lineItem = new LineItem();

            lineItem.name      = "Line item #" + new TestUtils().GetTimeStamp();
            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 length of the line item to run.
            //lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
            lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
            lineItem.endDateTime       = DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1));

            // 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.
            lineItem.unitsBought = 500000L;
            lineItem.unitType    = UnitType.IMPRESSIONS;

            return(lineItemService.createLineItem(lineItem));
        }
        /// <summary>
        /// Run the code examples.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (ProductService productTemplateService =
                       (ProductService)user.GetService(DfpService.v201708.ProductService))

                using (NetworkService networkService =
                           (NetworkService)user.GetService(DfpService.v201708.NetworkService)) {
                    // Create a product.
                    Product product = new Product();
                    product.name = "Non-sales programmatic product #" + new Random().Next(int.MaxValue);

                    // Set required Marketplace information.
                    product.productMarketplaceInfo = new ProductMarketplaceInfo()
                    {
                        additionalTerms       = "Additional terms for the product",
                        adExchangeEnvironment = AdExchangeEnvironment.DISPLAY
                    };

                    // Set common required fields for a programmatic product.
                    product.productType     = ProductType.DFP;
                    product.rateType        = RateType.CPM;
                    product.lineItemType    = LineItemType.STANDARD;
                    product.priority        = 8;
                    product.environmentType = EnvironmentType.BROWSER;
                    product.rate            = new Money()
                    {
                        currencyCode = "USD", microAmount = 6000000L
                    };

                    CreativePlaceholder placeholder = new CreativePlaceholder();
                    placeholder.size = new Size()
                    {
                        width = 300, height = 250, isAspectRatio = false
                    };
                    product.creativePlaceholders = new CreativePlaceholder[] { placeholder };

                    // Create inventory targeting to serve to run of network..
                    String          rootAdUnitId    = networkService.getCurrentNetwork().effectiveRootAdUnitId;
                    AdUnitTargeting adUnitTargeting = new AdUnitTargeting();
                    adUnitTargeting.adUnitId           = rootAdUnitId;
                    adUnitTargeting.includeDescendants = true;

                    Targeting productTargeting = new Targeting();
                    productTargeting.inventoryTargeting = new InventoryTargeting()
                    {
                        targetedAdUnits = new AdUnitTargeting[] { adUnitTargeting }
                    };

                    product.builtInTargeting = productTargeting;

                    try {
                        // Create the product on the server.
                        Product[] products = productTemplateService.createProducts(
                            new Product[] { product });

                        foreach (Product createdProduct in products)
                        {
                            Console.WriteLine("A programmatic product with ID \"{0}\" and name \"{1}\" " +
                                              "was created.", createdProduct.id, createdProduct.name);
                        }
                    } catch (Exception e) {
                        Console.WriteLine("Failed to create products. Exception says \"{0}\"",
                                          e.Message);
                    }
                }
        }
    public void TestGetAvailabilityForecast() {
      TestUtils utils = new TestUtils();

      LineItem lineItem = new LineItem();
      lineItem.name = string.Format("Line item #{0}", utils.GetTimeStamp());

      lineItem.orderId = orderId;

      lineItem.targeting = new Targeting();
      lineItem.targeting.inventoryTargeting = new InventoryTargeting();
      lineItem.targeting.inventoryTargeting.targetedPlacementIds = new long[] {placementId};

      Size size1 = new Size();
      size1.width = 300;
      size1.height = 250;

      Size size2 = new Size();
      size2.width = 120;
      size2.height = 600;

      // Create the creative placeholders.
      CreativePlaceholder creativePlaceholder1 = new CreativePlaceholder();
      creativePlaceholder1.size = size1;

      CreativePlaceholder creativePlaceholder2 = new CreativePlaceholder();
      creativePlaceholder1.size = size2;

      lineItem.creativePlaceholders =
          new CreativePlaceholder[] {creativePlaceholder1, creativePlaceholder2};

      lineItem.lineItemType = LineItemType.STANDARD;

      // Set start date time and end date time.
      lineItem.startDateTime =
          DateTimeUtilities.FromDateTime(System.DateTime.Today.AddDays(1), "America/New_York");
      lineItem.endDateTime =
          DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1), "America/New_York");

      lineItem.costType = CostType.CPM;
      lineItem.costPerUnit = new Money();
      lineItem.costPerUnit.currencyCode = "USD";
      lineItem.costPerUnit.microAmount = 2000000;

      lineItem.creativeRotationType = CreativeRotationType.EVEN;
      lineItem.discountType = LineItemDiscountType.PERCENTAGE;

      Goal goal = new Goal();
      goal.units = 500000;
      goal.unitType = UnitType.IMPRESSIONS;
      lineItem.primaryGoal = goal;

      ProspectiveLineItem prospectiveLineItem = new ProspectiveLineItem();
      prospectiveLineItem.lineItem = lineItem;

      AvailabilityForecast forecast = null;
      Assert.DoesNotThrow(delegate() {
        forecast = forecastService.getAvailabilityForecast(prospectiveLineItem,
            new AvailabilityForecastOptions());
      });
      Assert.NotNull(forecast);
      Assert.AreEqual(forecast.orderId, orderId);
      Assert.AreEqual(forecast.unitType, lineItem.primaryGoal.unitType);
    }
    public void TestCreateLineItems() {
      // Create inventory targeting.
      InventoryTargeting inventoryTargeting = new InventoryTargeting();
      inventoryTargeting.targetedPlacementIds = new long[] {placementId};

      // 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};

      // 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.Dfp.v201508.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.Dfp.v201508.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[2];

      for (int i = 0; i < lineItems.Length; i++) {
        LineItem lineItem = new LineItem();
        lineItem.name = "Line item #" + new TestUtils().GetTimeStamp();
        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.units = 500000L;
        goal.unitType = UnitType.IMPRESSIONS;
        lineItem.primaryGoal = goal;

        lineItems[i] = lineItem;
      }

      LineItem[] localLineItems = null;

      Assert.DoesNotThrow(delegate() {
        localLineItems = lineItemService.createLineItems(lineItems);
      });

      Assert.NotNull(localLineItems);
      Assert.AreEqual(localLineItems.Length, 2);

      Assert.AreEqual(localLineItems[0].name, lineItems[0].name);
      Assert.AreEqual(localLineItems[0].orderId, lineItems[0].orderId);

      Assert.AreEqual(localLineItems[1].name, lineItems[1].name);
      Assert.AreEqual(localLineItems[1].orderId, lineItems[1].orderId);
    }
    /// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="user">The DFP user object running the code example.</param>
    public override void Run(DfpUser user) {
      // Get the LineItemService.
      LineItemService lineItemService =
          (LineItemService) user.GetService(DfpService.v201508.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>
    /// <param name="user">The DFP user object running the code example.</param>
    public override void Run(DfpUser user) {
      // Get the ForecastService.
      ForecastService forecastService =
          (ForecastService)user.GetService(DfpService.v201508.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}%  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 examples.
    /// </summary>
    /// <param name="user">The DFP user object running the code examples.</param>
    public override void Run(DfpUser user) {
      // Get the ProductTemplateService.
      ProductTemplateService productTemplateService =
          (ProductTemplateService) user.GetService(DfpService.v201508.ProductTemplateService);

      // Get the NetworkService.
      NetworkService networkService =
          (NetworkService) user.GetService(DfpService.v201508.NetworkService);

      // Create a product template.
      ProductTemplate productTemplate = new ProductTemplate();
      productTemplate.name = "Product template #" + new Random().Next(int.MaxValue);
      productTemplate.description = "This product template creates standard proposal line items "
          + "targeting Chrome browsers with product segmentation on ad units and geo targeting.";

      // Set the name macro which will be used to generate the names of the products.
      // This will create a segmentation based on the line item type, ad unit, and location.
      productTemplate.nameMacro = "<line-item-type> - <ad-unit> - <template-name> - <location>";

      // Set the product type so the created proposal line items will be trafficked in DFP.
      productTemplate.productType = ProductType.DFP;

      // Set rate type to create CPM priced proposal line items.
      productTemplate.rateType = RateType.CPM;

      // Optionally set the creative rotation of the product to serve one or more creatives.
      productTemplate.roadblockingType = RoadblockingType.ONE_OR_MORE;

      // Create the master creative placeholder.
      CreativePlaceholder creativeMasterPlaceholder = new CreativePlaceholder();
      creativeMasterPlaceholder.size =
          new Size() {width = 728, height = 90, isAspectRatio = false};

      // Create companion creative placeholders.
      CreativePlaceholder companionCreativePlaceholder = new CreativePlaceholder();
      companionCreativePlaceholder.size =
          new Size() {width = 300, height = 250, isAspectRatio = false};

      // Set the size of creatives that can be associated with the product template.
      productTemplate.creativePlaceholders =
          new CreativePlaceholder[] {creativeMasterPlaceholder, companionCreativePlaceholder};

      // Set the type of proposal line item to be created from the product template.
      productTemplate.lineItemType = LineItemType.STANDARD;

      // Get the root ad unit ID used to target the whole site.
      String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;

      // Create ad unit targeting for the root ad unit (i.e. the whole network).
      AdUnitTargeting adUnitTargeting = new AdUnitTargeting();
      adUnitTargeting.adUnitId = rootAdUnitId;
      adUnitTargeting.includeDescendants = true;

      // Create geo targeting for the US.
      Location countryLocation = new Location();
      countryLocation.id = 2840L;

      // Create geo targeting for Hong Kong.
      Location regionLocation = new Location();
      regionLocation.id = 2344L;

      GeoTargeting geoTargeting = new GeoTargeting();
      geoTargeting.targetedLocations = new Location[] {countryLocation, regionLocation};

      // Add browser targeting to Chrome on the product template distinct from product
      // segmentation.
      Browser chromeBrowser = new Browser();
      chromeBrowser.id = 500072L;

      BrowserTargeting browserTargeting = new BrowserTargeting();
      browserTargeting.browsers = new Browser[] {chromeBrowser};

      TechnologyTargeting technologyTargeting = new TechnologyTargeting();
      technologyTargeting.browserTargeting = browserTargeting;

      Targeting productTemplateTargeting = new Targeting();
      productTemplateTargeting.technologyTargeting = technologyTargeting;

      productTemplate.builtInTargeting = productTemplateTargeting;

      // Add inventory and geo targeting as product segmentation.
      ProductSegmentation productSegmentation = new ProductSegmentation();
      productSegmentation.adUnitSegments = new AdUnitTargeting[] {adUnitTargeting};
      productSegmentation.geoSegment = geoTargeting;

      productTemplate.productSegmentation = productSegmentation;

      try {
        // Create the product template on the server.
        ProductTemplate[] productTemplates = productTemplateService.createProductTemplates(
            new ProductTemplate[] {productTemplate});

        foreach (ProductTemplate createdProductTemplate in productTemplates) {
          Console.WriteLine("A product template with ID \"{0}\" and name \"{1}\" was created.",
              createdProductTemplate.id, createdProductTemplate.name);
        }

      } catch (Exception e) {
        Console.WriteLine("Failed to create product templates. Exception says \"{0}\"",
            e.Message);
      }
    }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            // Get the LineItemService.
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201311.LineItemService);

            // Set the order that all created line items will belong to and the
            // placement containing ad units with a mobile target platform.
            long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

            long[] targetedPlacementIds = new long[] { long.Parse(_T("INSERT_MOBILE_PLACEMENT_ID_HERE")) };

            // Create inventory targeting.
            InventoryTargeting inventoryTargeting = new InventoryTargeting();

            inventoryTargeting.targetedPlacementIds = targetedPlacementIds;

            // Create technology targeting.
            TechnologyTargeting technologyTargeting = new TechnologyTargeting();

            // Create device manufacturer targeting.
            DeviceManufacturerTargeting deviceManufacturerTargeting = new DeviceManufacturerTargeting();

            deviceManufacturerTargeting.isTargeted = true;

            // Target the Google device manufacturer (40100).
            Technology deviceManufacturerTechnology = new Technology();

            deviceManufacturerTechnology.id = 40100L;
            deviceManufacturerTargeting.deviceManufacturers =
                new Technology[] { deviceManufacturerTechnology };
            technologyTargeting.deviceManufacturerTargeting = deviceManufacturerTargeting;

            // Create mobile device targeting.
            MobileDeviceTargeting mobileDeviceTargeting = new MobileDeviceTargeting();

            // Exclude the Nexus One device (604046).
            Technology mobileDeviceTechnology = new Technology();

            mobileDeviceTechnology.id = 604046L;
            mobileDeviceTargeting.targetedMobileDevices = new Technology[] { mobileDeviceTechnology };
            technologyTargeting.mobileDeviceTargeting   = mobileDeviceTargeting;

            // Create mobile device submodel targeting.
            MobileDeviceSubmodelTargeting mobileDeviceSubmodelTargeting =
                new MobileDeviceSubmodelTargeting();

            // Target the iPhone 4 device submodel (640003).
            Technology mobileDeviceSubmodelTechnology = new Technology();

            mobileDeviceSubmodelTechnology.id = 640003L;
            mobileDeviceSubmodelTargeting.targetedMobileDeviceSubmodels =
                new Technology[] { mobileDeviceSubmodelTechnology };
            technologyTargeting.mobileDeviceSubmodelTargeting = mobileDeviceSubmodelTargeting;

            // Create targeting.
            Targeting targeting = new Targeting();

            targeting.inventoryTargeting  = inventoryTargeting;
            targeting.technologyTargeting = technologyTargeting;

            // Create local line item object.
            LineItem lineItem = new LineItem();

            lineItem.name          = "Mobile line item";
            lineItem.orderId       = orderId;
            lineItem.targeting     = targeting;
            lineItem.lineItemType  = LineItemType.STANDARD;
            lineItem.allowOverbook = true;

            // Set the target platform to mobile.
            lineItem.targetPlatform = TargetPlatform.MOBILE;

            // Set the creative rotation type to even.
            lineItem.creativeRotationType = CreativeRotationType.EVEN;

            // Create the creative placeholder.
            CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
            Size size = new Size();

            size.width               = 300;
            size.height              = 250;
            size.isAspectRatio       = false;
            creativePlaceholder.size = size;

            // Set the size of creatives that can be associated with this line item.
            lineItem.creativePlaceholders = new CreativePlaceholder[] { creativePlaceholder };

            // Set the length of the line item to run.
            lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
            lineItem.endDateTime       = DateTimeUtilities.FromString("20120901 00:00:00");

            // Set the cost per unit to $2.
            lineItem.costType = CostType.CPM;
            Money money = new Money();

            money.currencyCode   = "USD";
            money.microAmount    = 2000000L;
            lineItem.costPerUnit = money;

            // Set the number of units bought to 500,000 so that the budget is
            // $1,000.
            lineItem.unitsBought = 500000L;
            lineItem.unitType    = UnitType.IMPRESSIONS;

            try {
                // Create the line item on the server.
                lineItem = lineItemService.createLineItem(lineItem);

                if (lineItem != null)
                {
                    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 item created.");
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to create line items. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
    /// <summary>
    /// Run the code examples.
    /// </summary>
    /// <param name="user">The DFP user object running the code examples.</param>
    public override void Run(DfpUser user) {
      // Get the LineItemService.
      LineItemService lineItemService =
          (LineItemService) user.GetService(DfpService.v201511.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.Dfp.v201511.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.Dfp.v201511.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);
      }
    }
示例#15
0
        /// <summary>
        /// Run the code examples.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (LineItemService lineItemService =
                       (LineItemService)user.GetService(DfpService.v201705.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.Dfp.v201705.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.Dfp.v201705.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 examples.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the ProductTemplateService.
            ProductTemplateService productTemplateService =
                (ProductTemplateService)user.GetService(DfpService.v201708.ProductTemplateService);

            // Get the NetworkService.
            NetworkService networkService =
                (NetworkService)user.GetService(DfpService.v201708.NetworkService);

            // Create a product template.
            ProductTemplate productTemplate = new ProductTemplate();

            productTemplate.name        = "Programmatic product template #" + new Random().Next(int.MaxValue);
            productTemplate.description = "This product template creates programmatic proposal line "
                                          + "items targeting all ad units with product segmentation on geo targeting.";

            // Set the name macro which will be used to generate the names of the products.
            // This will create a segmentation based on the line item type, ad unit, and location.
            productTemplate.nameMacro = "<line-item-type> - <ad-unit> - <template-name> - <location>";

            // Set the product type so the created proposal line items will be trafficked in DFP.
            productTemplate.productType = ProductType.DFP;

            // Set required Marketplace information.
            productTemplate.productTemplateMarketplaceInfo = new ProductTemplateMarketplaceInfo()
            {
                adExchangeEnvironment = AdExchangeEnvironment.DISPLAY,
            };

            // Set rate type to create CPM priced proposal line items.
            productTemplate.rateType = RateType.CPM;

            // Create the creative placeholder.
            CreativePlaceholder creativePlaceholder = new CreativePlaceholder();

            creativePlaceholder.size =
                new Size()
            {
                width = 300, height = 250, isAspectRatio = false
            };

            // Set the size of creatives that can be associated with the product template.
            productTemplate.creativePlaceholders =
                new CreativePlaceholder[] { creativePlaceholder };

            // Set the type of proposal line item to be created from the product template.
            productTemplate.lineItemType = LineItemType.STANDARD;

            // Get the root ad unit ID used to target the whole site.
            String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;

            // Create ad unit targeting for the root ad unit (i.e. the whole network).
            AdUnitTargeting adUnitTargeting = new AdUnitTargeting();

            adUnitTargeting.adUnitId           = rootAdUnitId;
            adUnitTargeting.includeDescendants = true;

            // Create geo targeting for the US.
            Location countryLocation = new Location();

            countryLocation.id = 2840L;

            // Create geo targeting for Hong Kong.
            Location regionLocation = new Location();

            regionLocation.id = 2344L;

            GeoTargeting geoTargeting = new GeoTargeting();

            geoTargeting.targetedLocations = new Location[] { countryLocation, regionLocation };

            // Add inventory and geo targeting as product segmentation.
            ProductSegmentation productSegmentation = new ProductSegmentation();

            productSegmentation.adUnitSegments = new AdUnitTargeting[] { adUnitTargeting };
            productSegmentation.geoSegment     = geoTargeting;

            productTemplate.productSegmentation = productSegmentation;

            try {
                // Create the product template on the server.
                ProductTemplate[] productTemplates = productTemplateService.createProductTemplates(
                    new ProductTemplate[] { productTemplate });

                foreach (ProductTemplate createdProductTemplate in productTemplates)
                {
                    Console.WriteLine("A programmatic product template with ID \"{0}\" "
                                      + "and name \"{1}\" was created.",
                                      createdProductTemplate.id,
                                      createdProductTemplate.name);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create product templates. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (ForecastService forecastService =
                       (ForecastService)user.GetService(DfpService.v201802.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 (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
                };


                // 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>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            // Get the LineItemService.
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201511.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);
            }
        }
示例#20
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            // Get the LineItemService.
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201311.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 key ID and value ID representing the metadata
            // on the content to target. This would typically be a key representing
            // a "genre" and a value representing something like "comedy".
            long contentCustomTargetingKeyId =
                long.Parse(_T("INSERT_CONTENT_CUSTOM_TARGETING_KEY_ID_HERE"));
            long contentCustomTargetingValueId =
                long.Parse(_T("INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE"));

            // Create custom criteria for the content metadata targeting.
            CustomCriteria contentCustomCriteria = new CustomCriteria();

            contentCustomCriteria.keyId     = contentCustomTargetingKeyId;
            contentCustomCriteria.valueIds  = new long[] { contentCustomTargetingValueId };
            contentCustomCriteria.@operator = CustomCriteriaComparisonOperator.IS;

            // Create custom criteria set.
            CustomCriteriaSet customCriteriaSet = new CustomCriteriaSet();

            customCriteriaSet.children = new CustomCriteriaNode[] { contentCustomCriteria };

            // 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.customTargeting        = customCriteriaSet;
            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 length of the line item to run.
            lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
            lineItem.endDateTime       = DateTimeUtilities.FromString("20120901 00:00:00");

            // 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%.
            lineItem.unitsBought = 100;

            try {
                // Create the line item on the server.
                lineItem = lineItemService.createLineItem(lineItem);

                if (lineItem != null)
                {
                    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 item created.");
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to create line items. Exception says \"{0}\"",
                                  ex.Message);
            }
        }