/// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser dfpUser)
        {
            using (LineItemService lineItemService =
                       (LineItemService)dfpUser.GetService(DfpService.v201805.LineItemService)) {
                // Create a statement to select line items.
                int pageSize = StatementBuilder.SUGGESTED_PAGE_LIMIT;
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .OrderBy("id ASC")
                                                    .Limit(pageSize);

                // Retrieve a small amount of line items at a time, paging through until all
                // line items have been retrieved.
                int totalResultSetSize = 0;
                do
                {
                    LineItemPage page = lineItemService.getLineItemsByStatement(
                        statementBuilder.ToStatement());

                    // Print out some information for each line item.
                    if (page.results != null)
                    {
                        totalResultSetSize = page.totalResultSetSize;
                        int i = page.startIndex;
                        foreach (LineItem lineItem in page.results)
                        {
                            Console.WriteLine(
                                "{0}) Line item with ID {1} and name \"{2}\" was found.",
                                i++,
                                lineItem.id,
                                lineItem.name
                                );
                        }
                    }

                    statementBuilder.IncreaseOffsetBy(pageSize);
                } while (statementBuilder.GetOffset() < totalResultSetSize);

                Console.WriteLine("Number of results found: {0}", totalResultSetSize);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (LineItemService lineItemService = user.GetService <LineItemService>())
            {
                // Create a statement to select line items.
                int pageSize = StatementBuilder.SUGGESTED_PAGE_LIMIT;
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("lastModifiedDateTime >= :lastModifiedDateTime").OrderBy("id ASC")
                                                    .Limit(pageSize)
                                                    .AddValue("lastModifiedDateTime",
                                                              DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(-1),
                                                                                             "America/New_York"));

                // Retrieve a small amount of line items at a time, paging through until all
                // line items have been retrieved.
                int totalResultSetSize = 0;
                do
                {
                    LineItemPage page =
                        lineItemService.getLineItemsByStatement(statementBuilder.ToStatement());

                    // Print out some information for each line item.
                    if (page.results != null)
                    {
                        totalResultSetSize = page.totalResultSetSize;
                        int i = page.startIndex;
                        foreach (LineItem lineItem in page.results)
                        {
                            Console.WriteLine(
                                "{0}) Line item with ID {1} and name \"{2}\" was found.", i++,
                                lineItem.id, lineItem.name);
                        }
                    }

                    statementBuilder.IncreaseOffsetBy(pageSize);
                } while (statementBuilder.GetOffset() < totalResultSetSize);

                Console.WriteLine("Number of results found: {0}", totalResultSetSize);
            }
        }
        /// <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 OrderService.
            LineItemService lineItemService = (LineItemService)user.GetService(
                DfpService.v201311.LineItemService);

            long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

            try {
                // Create statement to only select line items for the given order that
                // have been modified in the last 3 days.
                DateTime  threeDaysAgo    = DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(-3));
                Statement filterStatement = new StatementBuilder(
                    "WHERE lastModifiedDateTime >= :lastModifiedDateTime AND orderId = :orderId LIMIT 500").
                                            AddValue("lastModifiedDateTime", threeDaysAgo).
                                            AddValue("orderId", orderId).ToStatement();


                // Get line items by statement.
                LineItemPage page = lineItemService.getLineItemsByStatement(filterStatement);

                // Display results.
                if (page != null && page.results != null)
                {
                    foreach (LineItem lineItem in page.results)
                    {
                        Console.WriteLine("Line item with id \"{0}\", belonging to order id \"{1}\" and " +
                                          "named \"{2}\" was found.", lineItem.id, lineItem.orderId, lineItem.name);
                    }
                    Console.WriteLine("Number of results found: {1}.", page.totalResultSetSize);
                }
                else
                {
                    Console.WriteLine("No line items were found.");
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to get line items. Exception says \"{0}\"", ex.Message);
            }
        }
Esempio n. 4
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 ID of the order to get line items from.
            long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

            // Create a statement to only select line items that need creatives from a
            // given order.
            Statement filterStatement =
                new StatementBuilder("WHERE orderId = :orderId AND status = :status LIMIT 500")
                .AddValue("orderId", orderId)
                .AddValue("status", ComputedStatus.NEEDS_CREATIVES.ToString())
                .ToStatement();

            try {
                // Get line items by Statement.
                LineItemPage page = lineItemService.getLineItemsByStatement(filterStatement);

                if (page.results != null && page.results.Length > 0)
                {
                    int i = page.startIndex;
                    foreach (LineItem lineItem in page.results)
                    {
                        Console.WriteLine("{0}) Line item with ID ='{1}', belonging to order ID = '{2}' and " +
                                          "named '{3}' was found.", i, lineItem.id, lineItem.orderId, lineItem.name);
                        i++;
                    }
                }
                Console.WriteLine("Number of results found: {0}", page.totalResultSetSize);
            } catch (Exception ex) {
                Console.WriteLine("Failed to get line item by Statement. Exception says \"{0}\"",
                                  ex.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 CustomFieldService.
            CustomFieldService customFieldService = (CustomFieldService)user.GetService(
                DfpService.v201502.CustomFieldService);

            // Get the LineItemService.
            LineItemService lineItemService = (LineItemService)user.GetService(
                DfpService.v201502.LineItemService);

            // Set the IDs of the custom fields, custom field option, and line item.
            long customFieldId       = long.Parse(_T("INSERT_STRING_CUSTOM_FIELD_ID_HERE"));
            long customFieldOptionId = long.Parse(_T("INSERT_CUSTOM_FIELD_OPTION_ID_HERE"));
            long lineItemId          = long.Parse(_T("INSERT_LINE_ITEM_ID_HERE"));

            try {
                // Get the drop-down custom field id.
                long dropDownCustomFieldId =
                    customFieldService.getCustomFieldOption(customFieldOptionId).customFieldId;

                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :id")
                                                    .OrderBy("id ASC")
                                                    .Limit(1)
                                                    .AddValue("id", lineItemId);

                // Get the line item.
                LineItemPage lineItemPage = lineItemService.getLineItemsByStatement(
                    statementBuilder.ToStatement());
                LineItem lineItem = lineItemPage.results[0];

                // Create custom field values.
                List <BaseCustomFieldValue> customFieldValues = new List <BaseCustomFieldValue>();
                TextValue textValue = new TextValue();
                textValue.value = "Custom field value";

                CustomFieldValue customFieldValue = new CustomFieldValue();
                customFieldValue.customFieldId = customFieldId;
                customFieldValue.value         = textValue;
                customFieldValues.Add(customFieldValue);

                DropDownCustomFieldValue dropDownCustomFieldValue = new DropDownCustomFieldValue();
                dropDownCustomFieldValue.customFieldId       = dropDownCustomFieldId;
                dropDownCustomFieldValue.customFieldOptionId = customFieldOptionId;
                customFieldValues.Add(dropDownCustomFieldValue);

                // Only add existing custom field values for different custom fields than
                // the ones you are setting.
                if (lineItem.customFieldValues != null)
                {
                    foreach (BaseCustomFieldValue oldCustomFieldValue in lineItem.customFieldValues)
                    {
                        if (!(oldCustomFieldValue.customFieldId == customFieldId) &&
                            !(oldCustomFieldValue.customFieldId == dropDownCustomFieldId))
                        {
                            customFieldValues.Add(oldCustomFieldValue);
                        }
                    }
                }

                lineItem.customFieldValues = customFieldValues.ToArray();

                // Update the line item on the server.
                LineItem[] lineItems = lineItemService.updateLineItems(new LineItem[] { lineItem });

                if (lineItems != null)
                {
                    foreach (LineItem updatedLineItem in lineItems)
                    {
                        List <String> customFieldValueStrings = new List <String>();
                        foreach (BaseCustomFieldValue baseCustomFieldValue in lineItem.customFieldValues)
                        {
                            if (baseCustomFieldValue is CustomFieldValue &&
                                ((CustomFieldValue)baseCustomFieldValue).value is TextValue)
                            {
                                customFieldValueStrings.Add("{ID: '" + baseCustomFieldValue.customFieldId
                                                            + "', value: '"
                                                            + ((TextValue)((CustomFieldValue)baseCustomFieldValue).value).value
                                                            + "'}");
                            }
                            else if (baseCustomFieldValue is DropDownCustomFieldValue)
                            {
                                customFieldValueStrings.Add("{ID: '" + baseCustomFieldValue.customFieldId
                                                            + "', custom field option ID: '"
                                                            + ((DropDownCustomFieldValue)baseCustomFieldValue).customFieldOptionId
                                                            + "'}");
                            }
                        }
                        Console.WriteLine("A line item with ID \"{0}\" set with custom field values \"{1}\".",
                                          updatedLineItem.id, string.Join(", ", customFieldValueStrings.ToArray()));
                    }
                }
                else
                {
                    Console.WriteLine("No line items were updated.");
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to update line items. Exception says \"{0}\"", ex.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);
                }
            }
        }
    public void Init() {
      TestUtils utils = new TestUtils();
      lineItemService = (LineItemService)user.GetService(DfpService.v201508.LineItemService);

      advertiserId = utils.CreateCompany(user, CompanyType.ADVERTISER).id;
      salespersonId = utils.GetSalesperson(user).id;
      traffickerId = utils.GetTrafficker(user).id;
      orderId = utils.CreateOrder(user, advertiserId, salespersonId, traffickerId).id;
      adUnitId = utils.CreateAdUnit(user).id;
      placementId = utils.CreatePlacement(user, new string[] {adUnitId}).id;
      lineItem1 = utils.CreateLineItem(user, orderId, adUnitId);
      lineItem2 = utils.CreateLineItem(user, orderId, adUnitId);
    }
Esempio n. 8
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (LineItemService lineItemService =
                       (LineItemService)user.GetService(DfpService.v201802.LineItemService))
                using (ReportService reportService =
                           (ReportService)user.GetService(DfpService.v201802.ReportService)) {
                    try {
                        // Set the ID of the order to get line items from.
                        long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

                        // Set the file path where the report will be saved.
                        String filePath = _T("INSERT_FILE_PATH_HERE");

                        // Sets default for page.
                        LineItemPage page = new LineItemPage();

                        // Create a statement to only select line items from a given order.
                        StatementBuilder statementBuilder = new StatementBuilder()
                                                            .Where("orderId = :orderId")
                                                            .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                            .AddValue("orderId", orderId);


                        // Collect all line item custom field IDs for an order.
                        List <long> customFieldIds = new List <long>();
                        do
                        {
                            // Get line items by statement.
                            page = lineItemService.getLineItemsByStatement(statementBuilder.ToStatement());

                            // Get custom field IDs from the line items of an order.
                            if (page.results != null)
                            {
                                foreach (LineItem lineItem in page.results)
                                {
                                    if (lineItem.customFieldValues != null)
                                    {
                                        foreach (BaseCustomFieldValue customFieldValue in lineItem.customFieldValues)
                                        {
                                            if (!customFieldIds.Contains(customFieldValue.customFieldId))
                                            {
                                                customFieldIds.Add(customFieldValue.customFieldId);
                                            }
                                        }
                                    }
                                }
                            }

                            statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                        } while (statementBuilder.GetOffset() < page.totalResultSetSize);


                        // Create statement to filter for an order.
                        statementBuilder.RemoveLimitAndOffset();

                        // Create report job.
                        ReportJob reportJob = new ReportJob();

                        // Create report query.
                        ReportQuery reportQuery = new ReportQuery();
                        reportQuery.dateRangeType = DateRangeType.LAST_MONTH;
                        reportQuery.dimensions    = new Dimension[] {
                            Dimension.LINE_ITEM_ID,
                            Dimension.LINE_ITEM_NAME
                        };
                        reportQuery.statement      = statementBuilder.ToStatement();
                        reportQuery.customFieldIds = customFieldIds.ToArray();
                        reportQuery.columns        = new Column[] { Column.AD_SERVER_IMPRESSIONS };
                        reportJob.reportQuery      = reportQuery;

                        // Run report job.
                        reportJob = reportService.runReportJob(reportJob);

                        ReportUtilities reportUtilities = new ReportUtilities(reportService, reportJob.id);

                        // Set download options.
                        ReportDownloadOptions options = new ReportDownloadOptions();
                        options.exportFormat                  = ExportFormat.CSV_DUMP;
                        options.useGzipCompression            = true;
                        reportUtilities.reportDownloadOptions = options;

                        // Download the report.
                        using (ReportResponse reportResponse = reportUtilities.GetResponse()) {
                            reportResponse.Save(filePath);
                        }
                        Console.WriteLine("Report saved to \"{0}\".", filePath);
                    } catch (Exception e) {
                        Console.WriteLine("Failed to run cusom fields report. Exception says \"{0}\"",
                                          e.Message);
                    }
                }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <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.v201408.LineItemService);

            long lineItemId = long.Parse(_T("INSERT_LINE_ITEM_ID_HERE"));

            long[] customCriteriaIds1 =
                new long[] { long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE")),
                             long.Parse(_T("INSERT_CUSTOM_TARGETING_VALUE_ID_HERE")) };
            long[] customCriteriaIds2 =
                new long[] { long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE")),
                             long.Parse(_T("INSERT_CUSTOM_TARGETING_VALUE_ID_HERE")) };
            long[] customCriteriaIds3 =
                new long[] { long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE")),
                             long.Parse(_T("INSERT_CUSTOM_TARGETING_VALUE_ID_HERE")) };

            // Create custom criteria.
            CustomCriteria customCriteria1 = new CustomCriteria();

            customCriteria1.keyId     = customCriteriaIds1[0];
            customCriteria1.valueIds  = new long[] { customCriteriaIds1[1] };
            customCriteria1.@operator = CustomCriteriaComparisonOperator.IS;

            CustomCriteria customCriteria2 = new CustomCriteria();

            customCriteria2.keyId     = customCriteriaIds2[0];
            customCriteria2.valueIds  = new long[] { customCriteriaIds2[1] };
            customCriteria2.@operator = CustomCriteriaComparisonOperator.IS_NOT;

            CustomCriteria customCriteria3 = new CustomCriteria();

            customCriteria3.keyId     = customCriteriaIds3[0];
            customCriteria3.valueIds  = new long[] { customCriteriaIds3[1] };
            customCriteria3.@operator = CustomCriteriaComparisonOperator.IS;

            // Create the custom criteria set that will resemble:
            //
            // (customCriteria1.key == customCriteria1.value OR
            //     (customCriteria2.key != customCriteria2.value AND
            //         customCriteria3.key == customCriteria3.value))
            CustomCriteriaSet topCustomCriteriaSet = new CustomCriteriaSet();

            topCustomCriteriaSet.logicalOperator = CustomCriteriaSetLogicalOperator.OR;

            CustomCriteriaSet subCustomCriteriaSet = new CustomCriteriaSet();

            subCustomCriteriaSet.logicalOperator = CustomCriteriaSetLogicalOperator.AND;
            subCustomCriteriaSet.children        =
                new CustomCriteriaNode[] { customCriteria2, customCriteria3 };
            topCustomCriteriaSet.children =
                new CustomCriteriaNode[] { customCriteria1, subCustomCriteriaSet };

            try {
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :id")
                                                    .OrderBy("id ASC")
                                                    .Limit(1)
                                                    .AddValue("id", lineItemId);
                // Set the custom criteria targeting on the line item.
                LineItemPage page     = lineItemService.getLineItemsByStatement(statementBuilder.ToStatement());
                LineItem     lineItem = page.results[0];
                lineItem.targeting.customTargeting = topCustomCriteriaSet;

                // Update the line items on the server.
                LineItem[] updatedLineItems = lineItemService.updateLineItems(new LineItem[] { lineItem });

                foreach (LineItem updatedLineItem in updatedLineItems)
                {
                    // Display the updated line item.
                    Console.WriteLine("Line item with ID {0} updated with custom criteria targeting \n{1}\n",
                                      updatedLineItem.id,
                                      getCustomCriteriaSetString(updatedLineItem.targeting.customTargeting, 0));
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to add custom target criteria. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
 public ExpenseReportController()
 {
     _reportService   = new ExpenseReportService();
     _lineItemService = new LineItemService();
     _categoryService = new CategoryService();
 }
Esempio n. 11
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);

            // Get the CustomTargetingService.
            CustomTargetingService customTargetingService = (CustomTargetingService)user.GetService(
                DfpService.v201311.CustomTargetingService);

            long lineItemId = long.Parse(_T("INSERT_LINE_ITEM_ID_HERE"));

            long[] customCriteriaIds1 =
                new long[] { long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE")),
                             long.Parse(_T("INSERT_CUSTOM_TARGETING_VALUE_ID_HERE")) };
            long[] customCriteriaIds2 =
                new long[] { long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE")),
                             long.Parse(_T("INSERT_CUSTOM_TARGETING_VALUE_ID_HERE")) };
            long[] customCriteriaIds3 =
                new long[] { long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE")),
                             long.Parse(_T("INSERT_CUSTOM_TARGETING_VALUE_ID_HERE")) };

            // Create custom criteria.
            CustomCriteria customCriteria1 = new CustomCriteria();

            customCriteria1.keyId     = customCriteriaIds1[0];
            customCriteria1.valueIds  = new long[] { customCriteriaIds1[1] };
            customCriteria1.@operator = CustomCriteriaComparisonOperator.IS;

            CustomCriteria customCriteria2 = new CustomCriteria();

            customCriteria2.keyId     = customCriteriaIds2[0];
            customCriteria2.valueIds  = new long[] { customCriteriaIds2[1] };
            customCriteria2.@operator = CustomCriteriaComparisonOperator.IS_NOT;

            CustomCriteria customCriteria3 = new CustomCriteria();

            customCriteria3.keyId     = customCriteriaIds3[0];
            customCriteria3.valueIds  = new long[] { customCriteriaIds3[1] };
            customCriteria3.@operator = CustomCriteriaComparisonOperator.IS;

            // Create the custom criteria set that will resemble:
            //
            // (customCriteria1.key == customCriteria1.value OR
            //     (customCriteria2.key != customCriteria2.value AND
            //         customCriteria3.key == customCriteria3.value))
            CustomCriteriaSet topCustomCriteriaSet = new CustomCriteriaSet();

            topCustomCriteriaSet.logicalOperator = CustomCriteriaSetLogicalOperator.OR;

            CustomCriteriaSet subCustomCriteriaSet = new CustomCriteriaSet();

            subCustomCriteriaSet.logicalOperator = CustomCriteriaSetLogicalOperator.AND;
            subCustomCriteriaSet.children        =
                new CustomCriteriaNode[] { customCriteria2, customCriteria3 };
            topCustomCriteriaSet.children =
                new CustomCriteriaNode[] { customCriteria1, subCustomCriteriaSet };

            try {
                // Set the custom criteria targeting on the line item.
                LineItem lineItem = lineItemService.getLineItem(lineItemId);
                lineItem.targeting.customTargeting = topCustomCriteriaSet;

                // Update the line items on the server.
                lineItem = lineItemService.updateLineItem(lineItem);

                // Display the updated line item.
                Console.WriteLine("Line item with ID {0} updated with custom criteria targeting \n{1}\n",
                                  lineItem.id, getCustomCriteriaSetString(lineItem.targeting.customTargeting, 0));
            } catch (Exception ex) {
                Console.WriteLine("Failed to add custom target criteria. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
Esempio n. 12
0
        protected async Task Delete_Click(int SelectedId)
        {
            await LineItemService.DeleteLineItem(SelectedId);

            NavigationManager.NavigateTo("/ins/LineItem", true);
        }
Esempio n. 13
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);
            }
        }
Esempio n. 14
0
        public LineItem CreateLineItem(DfpUser user, long orderId, string adUnitId)
        {
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201602.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.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;

            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;

            return(lineItemService.createLineItems(new LineItem[] { lineItem })[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
            // 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 example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (LineItemService lineItemService =
                       (LineItemService)user.GetService(DfpService.v201802.LineItemService)) {
                // Set the ID of the order to get line items from.
                long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

                // Create statement to select approved line items from a given order.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("orderId = :orderId and status = :status")
                                                    .AddValue("orderId", orderId)
                                                    .AddValue("status", ComputedStatus.INACTIVE.ToString());

                // Set default for page.
                LineItemPage  page        = new LineItemPage();
                List <string> lineItemIds = new List <string>();

                try {
                    do
                    {
                        // Get line items by statement.
                        page = lineItemService.getLineItemsByStatement(statementBuilder.ToStatement());

                        if (page.results != null)
                        {
                            int i = page.startIndex;
                            foreach (LineItemSummary lineItem in page.results)
                            {
                                // Archived line items cannot be activated.
                                if (!lineItem.isArchived)
                                {
                                    Console.WriteLine("{0}) Line item with ID ='{1}', belonging to order " +
                                                      "ID ='{2}' and name ='{3}' will be activated.",
                                                      i, lineItem.id, lineItem.orderId, lineItem.name);
                                    lineItemIds.Add(lineItem.id.ToString());
                                    i++;
                                }
                            }
                        }

                        statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                    } while (statementBuilder.GetOffset() < page.totalResultSetSize);


                    Console.WriteLine("Number of line items to be activated: {0}", lineItemIds.Count);

                    if (lineItemIds.Count > 0)
                    {
                        // Modify statement.
                        statementBuilder.RemoveLimitAndOffset();

                        // Create action.
                        ActivateLineItems action = new ActivateLineItems();

                        // Perform action.
                        UpdateResult result = lineItemService.performLineItemAction(action,
                                                                                    statementBuilder.ToStatement());

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine("Number of line items activated: {0}", result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No line items were activated.");
                        }
                    }
                } catch (Exception e) {
                    Console.WriteLine("Failed to activate line items. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
        protected async Task Delete_Click(int SelectedId, int SeletedClaimId)
        {
            await LineItemService.DeleteLineItem(SelectedId);

            NavigationManager.NavigateTo($"/detail/{SeletedClaimId}", true);
        }
Esempio n. 18
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 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.v201408.LineItemService);
            // Get the ReportService.
            ReportService reportService =
                (ReportService)user.GetService(DfpService.v201408.ReportService);

            try {
                // Set the ID of the order to get line items from.
                long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

                // Sets default for page.
                LineItemPage page = new LineItemPage();

                // Create a statement to only select line items from a given order.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("orderId = :orderId")
                                                    .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                    .AddValue("orderId", orderId);


                // Collect all line item custom field IDs for an order.
                List <long> customFieldIds = new List <long>();
                do
                {
                    // Get line items by statement.
                    page = lineItemService.getLineItemsByStatement(statementBuilder.ToStatement());

                    // Get custom field IDs from the line items of an order.
                    if (page.results != null)
                    {
                        foreach (LineItem lineItem in page.results)
                        {
                            if (lineItem.customFieldValues != null)
                            {
                                foreach (BaseCustomFieldValue customFieldValue in lineItem.customFieldValues)
                                {
                                    if (!customFieldIds.Contains(customFieldValue.customFieldId))
                                    {
                                        customFieldIds.Add(customFieldValue.customFieldId);
                                    }
                                }
                            }
                        }
                    }

                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while (statementBuilder.GetOffset() < page.totalResultSetSize);


                // Create statement to filter for an order.
                statementBuilder.RemoveLimitAndOffset();

                // Create report job.
                ReportJob reportJob = new ReportJob();

                // Create report query.
                ReportQuery reportQuery = new ReportQuery();
                reportQuery.dateRangeType  = DateRangeType.LAST_MONTH;
                reportQuery.dimensions     = new Dimension[] { Dimension.LINE_ITEM_ID, Dimension.LINE_ITEM_NAME };
                reportQuery.statement      = statementBuilder.ToStatement();
                reportQuery.customFieldIds = customFieldIds.ToArray();
                reportQuery.columns        = new Column[] { Column.AD_SERVER_IMPRESSIONS };
                reportJob.reportQuery      = reportQuery;

                // Run report job.
                reportJob = reportService.runReportJob(reportJob);

                do
                {
                    Console.WriteLine("Report with ID '{0}' is still running.", reportJob.id);
                    Thread.Sleep(30000);
                    // Get report job.
                    reportJob = reportService.getReportJob(reportJob.id);
                } while (reportJob.reportJobStatus == ReportJobStatus.IN_PROGRESS);

                if (reportJob.reportJobStatus == ReportJobStatus.FAILED)
                {
                    Console.WriteLine("Report job with ID '{0}' failed to finish successfully.",
                                      reportJob.id);
                }
                else
                {
                    Console.WriteLine("Report job with ID '{0}' completed successfully.", reportJob.id);
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to run cusom fields report. Exception says \"{0}\"",
                                  ex.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);
            }
        }
Esempio n. 21
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 ID of the order to get line items from.
            long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

            // Create Statement text to select approved line items from a given order.
            string    statementText = "WHERE orderId = :orderId and status = :status LIMIT 500";
            Statement statement     = new StatementBuilder("").AddValue("orderId", orderId).
                                      AddValue("status", ComputedStatus.NEEDS_CREATIVES.ToString()).ToStatement();

            // Set defaults for page and offset.
            LineItemPage  page        = new LineItemPage();
            int           offset      = 0;
            int           i           = 0;
            List <string> lineItemIds = new List <string>();

            try {
                do
                {
                    // Create a Statement to page through approved line items.
                    statement.query = string.Format("{0} OFFSET {1}", statementText, offset);

                    // Get line items by Statement.
                    page = lineItemService.getLineItemsByStatement(statement);

                    if (page.results != null && page.results.Length > 0)
                    {
                        foreach (LineItemSummary lineItem in page.results)
                        {
                            // Archived line items cannot be activated.
                            if (!lineItem.isArchived)
                            {
                                Console.WriteLine("{0}) Line item with ID ='{1}', belonging to order ID ='{2}' " +
                                                  "and name ='{2}' will be activated.", i, lineItem.id, lineItem.orderId,
                                                  lineItem.name);
                                lineItemIds.Add(lineItem.id.ToString());
                                i++;
                            }
                        }
                    }

                    offset += 500;
                } while (offset < page.totalResultSetSize);

                Console.WriteLine("Number of line items to be activated: {0}", lineItemIds.Count);

                if (lineItemIds.Count > 0)
                {
                    // Create action Statement.
                    statement = new StatementBuilder(
                        string.Format("WHERE id IN ({0})", string.Join(",", lineItemIds.ToArray()))).
                                ToStatement();

                    // Create action.
                    ActivateLineItems action = new ActivateLineItems();

                    // Perform action.
                    UpdateResult result = lineItemService.performLineItemAction(action, statement);

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of line items activated: {0}", result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No line items were activated.");
                    }
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to activate line items. Exception says \"{0}\"",
                                  ex.Message);
            }
        }