/// <summary>
        /// Gets a string representation of the custom criteria node. If it has
        /// children, each child will be appended to the string recursively.
        /// </summary>
        /// <param name="root">The root custom criteria node.</param>
        /// <param name="level">The level of the custom criteria tree.</param>
        /// <returns>
        /// A string representation of the custom criteria node and its
        /// children
        /// </returns>
        private static string getCustomCriteriaSetString(CustomCriteriaNode root, int level)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(new String('\t', level));

            if (root is CustomCriteria)
            {
                CustomCriteria customCriteria = (CustomCriteria)root;
                StringBuilder  ids            = new StringBuilder();
                for (int j = 0; j < customCriteria.valueIds.Length; j++)
                {
                    ids.Append(customCriteria.valueIds[j] + ", ");
                }

                sb.AppendFormat("Custom criteria: operator: [{0}] key: [{1}] values: [{2}]\n",
                                customCriteria.@operator, customCriteria.keyId, ids.ToString().TrimEnd(',', ' '));
                return(sb.ToString());
            }
            else if (root is CustomCriteriaSet)
            {
                CustomCriteriaSet customCriteriaSet = (CustomCriteriaSet)root;
                sb.AppendFormat("Custom criteria set: operator: [{0}] children: \n",
                                customCriteriaSet.logicalOperator);
                foreach (CustomCriteriaNode node in customCriteriaSet.children)
                {
                    sb.Append(getCustomCriteriaSetString(node, level + 1));
                }
                return(sb.Append("\n").ToString());
            }
            else
            {
                throw new Exception("Unexpected node: " + root.GetType().Name);
            }
        }
        /// <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.v201403.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[] 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 ex) {
                Console.WriteLine("Failed to create line items. 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.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);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (AudienceSegmentService audienceSegmentService =
                       user.GetService <AudienceSegmentService>())
            {
                // Get the NetworkService.
                NetworkService networkService =
                    user.GetService <NetworkService>();

                long customTargetingKeyId   = long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE"));
                long customTargetingValueId =
                    long.Parse(_T("INSERT_CUSTOM_TARGETING_VALUE_ID_HERE"));

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

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

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

                    inventoryTargeting.targetedAdUnits = new AdUnitTargeting[]
                    {
                        adUnitTargeting
                    };

                    // Create the custom criteria to be used in the segment rule.
                    // CUSTOM_TARGETING_KEY_ID == CUSTOM_TARGETING_VALUE_ID
                    CustomCriteria customCriteria = new CustomCriteria();
                    customCriteria.keyId     = customTargetingKeyId;
                    customCriteria.@operator = CustomCriteriaComparisonOperator.IS;
                    customCriteria.valueIds  = new long[]
                    {
                        customTargetingValueId
                    };

                    // Create the custom criteria expression.
                    CustomCriteriaSet topCustomCriteriaSet = new CustomCriteriaSet();
                    topCustomCriteriaSet.logicalOperator = CustomCriteriaSetLogicalOperator.AND;
                    topCustomCriteriaSet.children        = new CustomCriteriaNode[]
                    {
                        customCriteria
                    };

                    // Create the audience segment rule.
                    FirstPartyAudienceSegmentRule rule = new FirstPartyAudienceSegmentRule();
                    rule.inventoryRule      = inventoryTargeting;
                    rule.customCriteriaRule = topCustomCriteriaSet;

                    // Create an audience segment.
                    RuleBasedFirstPartyAudienceSegment audienceSegment =
                        new RuleBasedFirstPartyAudienceSegment();
                    audienceSegment.name =
                        "Sports enthusiasts audience segment #" + this.GetTimeStamp();
                    audienceSegment.description =
                        "Sports enthusiasts between the ages of 20 and 30.";
                    audienceSegment.pageViews   = 6;
                    audienceSegment.recencyDays = 6;
                    audienceSegment.membershipExpirationDays = 88;
                    audienceSegment.rule = rule;

                    // Create the audience segment on the server.
                    AudienceSegment[] audienceSegments =
                        audienceSegmentService.createAudienceSegments(
                            new FirstPartyAudienceSegment[]
                    {
                        audienceSegment
                    });

                    foreach (AudienceSegment createdAudienceSegment in audienceSegments)
                    {
                        Console.WriteLine(
                            "An audience segment with ID \"{0}\", name \"{1}\", and " +
                            "type \"{2}\" was created.", createdAudienceSegment.id,
                            createdAudienceSegment.name, createdAudienceSegment.type);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to get audience segment. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (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);

      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 e) {
        Console.WriteLine("Failed to add custom target criteria. Exception says \"{0}\"",
            e.Message);
      }
    }
Ejemplo n.º 7
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);
            }
        }
    /// <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 AudienceSegmentService.
      AudienceSegmentService audienceSegmentService = (AudienceSegmentService) user.GetService(
          DfpService.v201508.AudienceSegmentService);

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

      long customTargetingKeyId = long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE"));
      long customTargetingValueId = long.Parse(_T("INSERT_CUSTOM_TARGETING_VALUE_ID_HERE"));

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

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

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

        inventoryTargeting.targetedAdUnits = new AdUnitTargeting[] {adUnitTargeting};

        // Create the custom criteria to be used in the segment rule.
        // CUSTOM_TARGETING_KEY_ID == CUSTOM_TARGETING_VALUE_ID
        CustomCriteria customCriteria = new CustomCriteria();
        customCriteria.keyId = customTargetingKeyId;
        customCriteria.@operator = CustomCriteriaComparisonOperator.IS;
        customCriteria.valueIds = new long[] {customTargetingValueId};

        // Create the custom criteria expression.
        CustomCriteriaSet topCustomCriteriaSet = new CustomCriteriaSet();
        topCustomCriteriaSet.logicalOperator = CustomCriteriaSetLogicalOperator.AND;
        topCustomCriteriaSet.children = new CustomCriteriaNode[] {customCriteria};

        // Create the audience segment rule.
        FirstPartyAudienceSegmentRule rule = new FirstPartyAudienceSegmentRule();
        rule.inventoryRule = inventoryTargeting;
        rule.customCriteriaRule = topCustomCriteriaSet;

        // Create an audience segment.
        RuleBasedFirstPartyAudienceSegment audienceSegment =
            new RuleBasedFirstPartyAudienceSegment();
        audienceSegment.name = "Sports enthusiasts audience segment #" + this.GetTimeStamp();
        audienceSegment.description = "Sports enthusiasts between the ages of 20 and 30.";
        audienceSegment.pageViews = 6;
        audienceSegment.recencyDays = 6;
        audienceSegment.membershipExpirationDays = 88;
        audienceSegment.rule = rule;

        // Create the audience segment on the server.
        AudienceSegment[] audienceSegments = audienceSegmentService.createAudienceSegments(
            new FirstPartyAudienceSegment[] {audienceSegment});

        foreach (AudienceSegment createdAudienceSegment in audienceSegments) {
          Console.WriteLine("An audience segment with ID \"{0}\", name \"{1}\", and type \"{2}\" " +
              "was created.", createdAudienceSegment.id, createdAudienceSegment.name,
              createdAudienceSegment.type);
        }
      } catch (Exception e) {
        Console.WriteLine("Failed to get audience segment. Exception says \"{0}\"", e.Message);
      }
    }