Ejemplo n.º 1
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the LineItemService.
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201605.LineItemService);
            // Get the ReportService.
            ReportService reportService =
                (ReportService)user.GetService(DfpService.v201605.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);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the CreativeService.
            CreativeService creativeService =
                (CreativeService)user.GetService(DfpService.v201608.CreativeService);

            // Set the ID of the advertiser (company) that the creative will be
            // assigned to.
            long advertiserId = long.Parse(_T("INSERT_ADVERTISER_COMPANY_ID_HERE"));

            // Use the system defined native app install creative template.
            long creativeTemplateId = 10004400L;

            // Create a native app install creative for the Pie Noon app.
            TemplateCreative nativeAppInstallCreative = new TemplateCreative();

            nativeAppInstallCreative.name =
                String.Format("Native creative #{0}", new Random().Next(int.MaxValue));
            nativeAppInstallCreative.advertiserId       = advertiserId;
            nativeAppInstallCreative.creativeTemplateId = creativeTemplateId;
            nativeAppInstallCreative.destinationUrl     =
                "https://play.google.com/store/apps/details?id=com.google.fpl.pie_noon";

            // Use 1x1 as the size for native creatives.
            Size size = new Size();

            size.width                    = 1;
            size.height                   = 1;
            size.isAspectRatio            = false;
            nativeAppInstallCreative.size = size;

            List <BaseCreativeTemplateVariableValue> templateVariables =
                new List <BaseCreativeTemplateVariableValue>();

            // Set the headline.
            templateVariables.Add(new StringCreativeTemplateVariableValue()
            {
                uniqueName = "Headline",
                value      = "Pie Noon"
            });

            // Set the body text.
            templateVariables.Add(new StringCreativeTemplateVariableValue()
            {
                uniqueName = "Body",
                value      = "Try multi-screen mode!"
            });

            // Set the image asset.
            templateVariables.Add(new AssetCreativeTemplateVariableValue()
            {
                uniqueName = "Image",
                asset      = new CreativeAsset()
                {
                    fileName       = String.Format("image{0}.png", this.GetTimeStamp()),
                    assetByteArray = MediaUtilities.GetAssetDataFromUrl("https://lh4.ggpht.com/"
                                                                        + "GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZOPYnTdOQGaSpGSEZflIFs0iw=h300")
                }
            });

            // Set the price.
            templateVariables.Add(new StringCreativeTemplateVariableValue()
            {
                uniqueName = "Price",
                value      = "Free"
            });

            // Set app icon image asset.
            templateVariables.Add(new AssetCreativeTemplateVariableValue()
            {
                uniqueName = "Appicon",
                asset      = new CreativeAsset()
                {
                    fileName       = String.Format("icon{0}.png", this.GetTimeStamp()),
                    assetByteArray = MediaUtilities.GetAssetDataFromUrl("https://lh6.ggpht.com/"
                                                                        + "Jzvjne5CLs6fJ1MHF-XeuUfpABzl0YNMlp4RpHnvPRCIj4--eTDwtyouwUDzVVekXw=w300")
                }
            });

            // Set the call to action text.
            templateVariables.Add(new StringCreativeTemplateVariableValue()
            {
                uniqueName = "Calltoaction",
                value      = "Install"
            });

            // Set the star rating.
            templateVariables.Add(new StringCreativeTemplateVariableValue()
            {
                uniqueName = "Starrating",
                value      = "4"
            });

            // Set the store type.
            templateVariables.Add(new StringCreativeTemplateVariableValue()
            {
                uniqueName = "Store",
                value      = "Google Play"
            });

            // Set the deep link URL.
            templateVariables.Add(new UrlCreativeTemplateVariableValue()
            {
                uniqueName = "DeeplinkclickactionURL",
                value      = "market://details?id=com.google.fpl.pie_noon"
            });

            nativeAppInstallCreative.creativeTemplateVariableValues = templateVariables.ToArray();

            try {
                // Create the native creative on the server.
                Creative[] createdNativeCreatives = creativeService.createCreatives(
                    new Creative[] { nativeAppInstallCreative });

                foreach (Creative createdNativeCreative in createdNativeCreatives)
                {
                    Console.WriteLine("A native creative with ID \"{0}\" and name \"{1}\" " +
                                      "was created and can be previewed at {2}", createdNativeCreative.id,
                                      createdNativeCreative.name, createdNativeCreative.previewUrl);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create creatives. Exception says \"{0}\"", e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user, long productId)
        {
            // Get the ProductService.
            ProductService productService =
                (ProductService)user.GetService(DfpService.v201608.ProductService);

            // Create statement to select a product template by ID.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("id = :id")
                                                .OrderBy("id ASC")
                                                .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                .AddValue("id", productId);

            // Set default for page.
            ProductPage page       = new ProductPage();
            List <long> productIds = new List <long>();

            try {
                do
                {
                    // Get products by statement.
                    page = productService.getProductsByStatement(
                        statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        int i = page.startIndex;
                        foreach (Product product in page.results)
                        {
                            Console.WriteLine("{0}) Product with ID ='{1}' will be published.",
                                              i++, product.id);
                            productIds.Add(product.id);
                        }
                    }

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

                Console.WriteLine("Number of products to be published: {0}", productIds.Count);

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

                    // Create action.
                    Google.Api.Ads.Dfp.v201608.PublishProducts action =
                        new Google.Api.Ads.Dfp.v201608.PublishProducts();

                    // Perform action.
                    UpdateResult result = productService.performProductAction(action,
                                                                              statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of products published: {0}", result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No products were published.");
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to publish products. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the InventoryService.
            InventoryService inventoryService =
                (InventoryService)user.GetService(DfpService.v201702.InventoryService);

            // Set the ID of the ad unit to deactivate.
            int adUnitId = int.Parse(_T("INSERT_AD_UNIT_ID_HERE"));

            // Create a statement to select the ad unit.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("id = :id")
                                                .OrderBy("id ASC")
                                                .Limit(1)
                                                .AddValue("id", adUnitId);

            // Set default for page.
            AdUnitPage    page      = new AdUnitPage();
            List <string> adUnitIds = new List <string>();

            try {
                do
                {
                    // Get ad units by statement.
                    page = inventoryService.getAdUnitsByStatement(statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        int i = page.startIndex;
                        foreach (AdUnit adUnit in page.results)
                        {
                            Console.WriteLine("{0}) Ad unit with ID ='{1}', name = {2} and status = {3} will" +
                                              " be deactivated.", i, adUnit.id, adUnit.name, adUnit.status);
                            adUnitIds.Add(adUnit.id);
                            i++;
                        }
                    }

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

                Console.WriteLine("Number of ad units to be deactivated: {0}", adUnitIds.Count);

                // Modify statement for action.
                statementBuilder.RemoveLimitAndOffset();

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

                // Perform action.
                UpdateResult result = inventoryService.performAdUnitAction(action,
                                                                           statementBuilder.ToStatement());

                // Display results.
                if (result != null && result.numChanges > 0)
                {
                    Console.WriteLine("Number of ad units deactivated: {0}", result.numChanges);
                }
                else
                {
                    Console.WriteLine("No ad units were deactivated.");
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to deactivate ad units. Exception says \"{0}\"", e.Message);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the OrderService.
            OrderService orderService =
                (OrderService)user.GetService(DfpService.v201705.OrderService);

            // Set the ID of the order.
            long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

            // Create statement to select the order.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("id = :id")
                                                .OrderBy("id ASC")
                                                .Limit(1)
                                                .AddValue("id", orderId);

            // Set default for page.
            OrderPage     page     = new OrderPage();
            List <string> orderIds = new List <string>();
            int           i        = 0;

            try {
                do
                {
                    // Get orders by statement.
                    page = orderService.getOrdersByStatement(statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        foreach (Order order in page.results)
                        {
                            Console.WriteLine("{0}) Order with ID = '{1}', name = '{2}', and status ='{3}' " +
                                              "will be approved.", i, order.id, order.name, order.status);
                            orderIds.Add(order.id.ToString());
                            i++;
                        }
                    }

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

                Console.WriteLine("Number of orders to be approved: {0}", orderIds.Count);

                if (orderIds.Count > 0)
                {
                    // Modify statement for action.
                    statementBuilder.RemoveLimitAndOffset();

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

                    // Perform action.
                    UpdateResult result = orderService.performOrderAction(action,
                                                                          statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of orders approved: {0}", result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No orders were approved.");
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to approve orders. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (CreativeService creativeService =
                       (CreativeService)user.GetService(DfpService.v201708.CreativeService)) {
                // Set the ID of the advertiser (company) that all creatives will be
                // assigned to.
                long advertiserId = long.Parse(_T("INSERT_ADVERTISER_COMPANY_ID_HERE"));

                // Create an array to store local image creative objects.
                Creative[] imageCreatives = new ImageCreative[5];

                for (int i = 0; i < 5; i++)
                {
                    // Create creative size.
                    Size size = new Size();
                    size.width  = 300;
                    size.height = 250;

                    // Create an image creative.
                    ImageCreative imageCreative = new ImageCreative();
                    imageCreative.name           = string.Format("Image creative #{0}", i);
                    imageCreative.advertiserId   = advertiserId;
                    imageCreative.destinationUrl = "http://www.google.com";
                    imageCreative.size           = size;

                    // Create image asset.
                    CreativeAsset creativeAsset = new CreativeAsset();
                    creativeAsset.fileName       = "image.jpg";
                    creativeAsset.assetByteArray = MediaUtilities.GetAssetDataFromUrl(
                        "https://goo.gl/3b9Wfh");
                    creativeAsset.size = size;
                    imageCreative.primaryImageAsset = creativeAsset;

                    imageCreatives[i] = imageCreative;
                }

                try {
                    // Create the image creatives on the server.
                    imageCreatives = creativeService.createCreatives(imageCreatives);

                    if (imageCreatives != null)
                    {
                        foreach (Creative creative in imageCreatives)
                        {
                            // Use "is" operator to determine what type of creative was
                            // returned.
                            if (creative is ImageCreative)
                            {
                                ImageCreative imageCreative = (ImageCreative)creative;
                                Console.WriteLine("An image creative with ID ='{0}', name ='{1}' and size = " +
                                                  "({2},{3}) was created and can be previewed at: {4}", imageCreative.id,
                                                  imageCreative.name, imageCreative.size.width, imageCreative.size.height,
                                                  imageCreative.previewUrl);
                            }
                            else
                            {
                                Console.WriteLine("A creative with ID ='{0}', name='{1}' and type='{2}' " +
                                                  "was created.", creative.id, creative.name, creative.GetType().Name);
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("No creatives created.");
                    }
                } catch (Exception e) {
                    Console.WriteLine("Failed to create creatives. Exception says \"{0}\"", e.Message);
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the LineItemService.
            LineItemService lineItemService = (LineItemService)user.GetService(
                DfpService.v201705.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.º 8
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 CreativeService.
            CustomTargetingService customTargetingService =
                (CustomTargetingService)user.GetService(DfpService.v201311.CustomTargetingService);

            // Set the ID of the predefined custom targeting key to get custom
            // targeting values for.
            long customTargetingKeyId = long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE"));

            // Create a statement to only select predefined custom targeting values
            // for a given key.
            Statement filterStatement =
                new StatementBuilder("WHERE customTargetingKeyId = :customTargetingKeyId LIMIT 500")
                .AddValue("customTargetingKeyId", customTargetingKeyId).ToStatement();

            try {
                // Get custom targeting values by statement.
                CustomTargetingValuePage page =
                    customTargetingService.getCustomTargetingValuesByStatement(filterStatement);

                if (page.results != null)
                {
                    CustomTargetingValue[] customTargetingValues = page.results;

                    // Update each local custom targeting value object by changing its
                    // display name.
                    foreach (CustomTargetingValue customTargetingValue in customTargetingValues)
                    {
                        if (customTargetingValue.displayName == null)
                        {
                            customTargetingValue.displayName = customTargetingValue.displayName;
                        }
                        customTargetingValue.displayName = customTargetingValue.displayName + " (Deprecated)";
                    }

                    // Update the custom targeting values on the server.
                    customTargetingValues =
                        customTargetingService.updateCustomTargetingValues(customTargetingValues);

                    if (customTargetingValues != null)
                    {
                        foreach (CustomTargetingValue customTargetingValue in customTargetingValues)
                        {
                            Console.WriteLine("Custom targeting value with ID \"{0}\", name \"{1}\", and " +
                                              "display name \"{2}\" was updated.", customTargetingValue.id,
                                              customTargetingValue.name, customTargetingValue.displayName);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No custom targeting values updated.");
                    }
                }
                else
                {
                    Console.WriteLine("No custom targeting values found to update.");
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to update display names of custom targeting values. Exception " +
                                  "says \"{0}\"", ex.Message);
            }
        }
        /// <summary>
        /// Run the code examples.
        /// </summary>
        /// <param name="user">The DFP user object running the code examples.</param>
        public override void Run(DfpUser user)
        {
            // [START get_proposal_line_item_service] MOE:strip_line
            // Get the ProposalLineItemService.
            ProposalLineItemService proposalLineItemService =
                (ProposalLineItemService)user.GetService(DfpService.v201602.ProposalLineItemService);
            // [END get_proposal_line_item_service] MOE:strip_line

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

            long proposalId = long.Parse(_T("INSERT_PROPOSAL_ID_HERE"));
            long rateCardId = long.Parse(_T("INSERT_RATE_CARD_ID_HERE"));
            long productId  = long.Parse(_T("INSERT_PRODUCT_ID_HERE"));

            // [START add_targeting] MOE:strip_line
            // Get the root ad unit ID used to target the whole site.
            String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;

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

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

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

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

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

            targeting.inventoryTargeting = inventoryTargeting;
            // [END add_targeting] MOE:strip_line

            // [START create_proposal_line_item_local] MOE:strip_line
            // Create a proposal line item.
            ProposalLineItem proposalLineItem = new ProposalLineItem();

            proposalLineItem.name = "Proposal line item #" + new Random().Next(int.MaxValue);
            // [END create_proposal_line_item_local] MOE:strip_line

            // [START set_required_creation_fields] MOE:strip_line
            proposalLineItem.proposalId = proposalId;
            proposalLineItem.rateCardId = rateCardId;
            proposalLineItem.productId  = productId;
            proposalLineItem.targeting  = targeting;
            // [END set_required_creation_fields] MOE:strip_line

            // [START set_dates] MOE:strip_line
            // Set the length of the proposal line item to run.
            proposalLineItem.startDateTime =
                DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(7), "America/New_York");
            proposalLineItem.endDateTime =
                DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(30), "America/New_York");
            // [END set_dates] MOE:strip_line

            // [START set_delivery_info] MOE:strip_line
            // Set delivery specifications for the proposal line item.
            proposalLineItem.deliveryRateType     = DeliveryRateType.EVENLY;
            proposalLineItem.creativeRotationType = CreativeRotationType.OPTIMIZED;
            // [END set_delivery_info] MOE:strip_line

            // [START set_billing] MOE:strip_line
            // Set billing specifications for the proposal line item.
            proposalLineItem.billingCap    = BillingCap.CAPPED_CUMULATIVE;
            proposalLineItem.billingSource = BillingSource.THIRD_PARTY_VOLUME;
            // [END set_billing] MOE:strip_line

            // [START set_goal] MOE:strip_line
            // Set pricing for the proposal line item for 1000 impressions at a CPM of $2
            // for a total value of $2.
            proposalLineItem.goal = new Goal()
            {
                unitType = UnitType.IMPRESSIONS, units = 1000L
            };
            // [END set_goal] MOE:strip_line
            // [START set_costs] MOE:strip_line
            proposalLineItem.cost = new Money()
            {
                currencyCode = "USD", microAmount = 2000000L
            };
            proposalLineItem.costPerUnit = new Money()
            {
                currencyCode = "USD", microAmount = 2000000L
            };
            proposalLineItem.rateType = RateType.CPM;
            // [END set_costs] MOE:strip_line

            try {
                // [START create_proposal_line_item_server] MOE:strip_line
                // Create the proposal line item on the server.
                ProposalLineItem[] proposalLineItems = proposalLineItemService.createProposalLineItems(
                    new ProposalLineItem[] { proposalLineItem });
                // [END create_proposal_line_item_server] MOE:strip_line

                foreach (ProposalLineItem createdProposalLineItem in proposalLineItems)
                {
                    Console.WriteLine("A proposal line item with ID \"{0}\" and name \"{1}\" was created.",
                                      createdProposalLineItem.id, createdProposalLineItem.name);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create proposal line items. Exception says \"{0}\"",
                                  e.Message);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the SuggestedAdUnitService.
            SuggestedAdUnitService suggestedAdUnitService = (SuggestedAdUnitService)user.GetService(
                DfpService.v201705.SuggestedAdUnitService);

            // Set the number of requests for suggested ad units greater than which to approve.
            long NUMBER_OF_REQUESTS = 50L;

            // Create statement to select all suggested ad units that are highly requested.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("numRequests > :numRequests")
                                                .OrderBy("id ASC")
                                                .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                .AddValue("numRequests", NUMBER_OF_REQUESTS);

            // Set default for page.
            SuggestedAdUnitPage page = new SuggestedAdUnitPage();

            try {
                do
                {
                    // Get suggested ad units by statement.
                    page = suggestedAdUnitService.getSuggestedAdUnitsByStatement(
                        statementBuilder.ToStatement());

                    int i = 0;
                    if (page != null && page.results != null)
                    {
                        foreach (SuggestedAdUnit suggestedAdUnit in page.results)
                        {
                            Console.WriteLine("{0}) Suggested ad unit with ID \"{1}\", and \"{2}\" will be " +
                                              "approved.", i, suggestedAdUnit.id, suggestedAdUnit.numRequests);
                            i++;
                        }
                    }
                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while(statementBuilder.GetOffset() < page.totalResultSetSize);

                Console.WriteLine("Number of suggested ad units to be approved: " +
                                  page.totalResultSetSize);

                // Modify statement for action.
                statementBuilder.RemoveLimitAndOffset();

                // Create action.
                Google.Api.Ads.Dfp.v201705.ApproveSuggestedAdUnits action =
                    new Google.Api.Ads.Dfp.v201705.ApproveSuggestedAdUnits();

                // Perform action.
                SuggestedAdUnitUpdateResult result = suggestedAdUnitService.performSuggestedAdUnitAction(
                    action, statementBuilder.ToStatement());

                // Display results.
                if (result != null && result.numChanges > 0)
                {
                    Console.WriteLine("Number of new ad units created: " + result.newAdUnitIds.Length);
                }
                else
                {
                    Console.WriteLine("No suggested ad units were approved.");
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to approve suggested ad units. Exception says \"{0}\"",
                                  e.Message);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Run the code examples.
        /// </summary>
        /// <param name="user">The DFP user object running the code examples.</param>
        public void Run(DfpUser user)
        {
            // Get the LineItemService.
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201605.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.v201605.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.v201605.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)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201502.ReportService);

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

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

            // Get the root ad unit ID to filter on.
            String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;

            // Create statement to filter on an ancestor ad unit with the root ad unit ID to include all
            // ad units in the network.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("PARENT_AD_UNIT_ID = :parentAdUnitId")
                                                .AddValue("parentAdUnitId", long.Parse(rootAdUnitId));

            // Create report query.
            ReportQuery reportQuery = new ReportQuery();

            reportQuery.dimensions =
                new Dimension[] { Dimension.AD_UNIT_ID, Dimension.AD_UNIT_NAME };
            reportQuery.columns = new Column[] { Column.AD_SERVER_IMPRESSIONS,
                                                 Column.AD_SERVER_CLICKS, Column.DYNAMIC_ALLOCATION_INVENTORY_LEVEL_IMPRESSIONS,
                                                 Column.DYNAMIC_ALLOCATION_INVENTORY_LEVEL_CLICKS,
                                                 Column.TOTAL_INVENTORY_LEVEL_IMPRESSIONS,
                                                 Column.TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE };

            // Set the filter statement.
            reportQuery.statement = statementBuilder.ToStatement();

            reportQuery.adUnitView    = ReportQueryAdUnitView.HIERARCHICAL;
            reportQuery.dateRangeType = DateRangeType.LAST_WEEK;

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

            reportJob.reportQuery = reportQuery;

            try {
                // Run report.
                reportJob = reportService.runReportJob(reportJob);

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

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

                // Download the report.
                using (ReportResponse reportResponse = reportUtilities.GetResponse()) {
                    reportResponse.Save(filePath);
                }
                Console.WriteLine("Report saved to \"{0}\".", filePath);
            } catch (Exception e) {
                Console.WriteLine("Failed to run inventory report. Exception says \"{0}\"",
                                  e.Message);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Run the code examples.
        /// </summary>
        public void Run(DfpUser user, long proposalId, long rateCardId, long productId)
        {
            // Get the ProposalLineItemService.
            ProposalLineItemService proposalLineItemService =
                (ProposalLineItemService)user.GetService(DfpService.v201702.ProposalLineItemService);

            // Create a proposal line item.
            ProposalLineItem proposalLineItem = new ProposalLineItem();

            proposalLineItem.name =
                "Programmatic proposal line item #" + new Random().Next(int.MaxValue);
            proposalLineItem.proposalId = proposalId;
            proposalLineItem.rateCardId = rateCardId;
            proposalLineItem.productId  = productId;

            // Set the Marketplace information.
            proposalLineItem.marketplaceInfo = new ProposalLineItemMarketplaceInfo()
            {
                adExchangeEnvironment = AdExchangeEnvironment.DISPLAY
            };

            // Set the length of the proposal line item to run.
            proposalLineItem.startDateTime =
                DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(7), "America/New_York");
            proposalLineItem.endDateTime =
                DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(30), "America/New_York");

            // Set pricing for the proposal line item for 1000 impressions at a CPM of $2
            // for a total value of $2.
            proposalLineItem.goal = new Goal()
            {
                unitType = UnitType.IMPRESSIONS,
                units    = 1000L
            };
            proposalLineItem.netCost = new Money()
            {
                currencyCode = "USD", microAmount = 2000000L
            };
            proposalLineItem.netRate = new Money()
            {
                currencyCode = "USD", microAmount = 2000000L
            };
            proposalLineItem.rateType = RateType.CPM;

            try {
                // Create the proposal line item on the server.
                ProposalLineItem[] proposalLineItems = proposalLineItemService.createProposalLineItems(
                    new ProposalLineItem[] { proposalLineItem });

                foreach (ProposalLineItem createdProposalLineItem in proposalLineItems)
                {
                    Console.WriteLine("A programmatic proposal line item with ID \"{0}\" "
                                      + "and name \"{1}\" was created.",
                                      createdProposalLineItem.id,
                                      createdProposalLineItem.name);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create proposal line items. Exception says \"{0}\"",
                                  e.Message);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Run the sample code.
        /// </summary>
        public void Run(DfpUser user, long adUnitId)
        {
            using (InventoryService inventoryService =
                       (InventoryService)user.GetService(DfpService.v201805.InventoryService))
            {
                // Create a statement to get the ad unit.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :id")
                                                    .OrderBy("id ASC")
                                                    .Limit(1)
                                                    .AddValue("id", adUnitId);

                try
                {
                    // Get ad units by statement.
                    AdUnitPage page =
                        inventoryService.getAdUnitsByStatement(statementBuilder.ToStatement());

                    // Create a 480x60 web ad unit size.
                    AdUnitSize adUnitSize = new AdUnitSize()
                    {
                        size = new Size()
                        {
                            width  = 480,
                            height = 60
                        },
                        environmentType = EnvironmentType.BROWSER
                    };

                    AdUnit adUnit = page.results[0];
                    adUnit.adUnitSizes = new AdUnitSize[]
                    {
                        adUnitSize
                    };

                    // Update the ad units on the server.
                    AdUnit[] updatedAdUnits = inventoryService.updateAdUnits(new AdUnit[]
                    {
                        adUnit
                    });

                    foreach (AdUnit updatedAdUnit in updatedAdUnits)
                    {
                        List <string> adUnitSizeStrings = new List <string>();
                        foreach (AdUnitSize size in updatedAdUnit.adUnitSizes)
                        {
                            adUnitSizeStrings.Add(size.fullDisplayString);
                        }

                        Console.WriteLine(
                            "Ad unit with ID \"{0}\", name \"{1}\", and sizes [{2}] was " +
                            "updated.", updatedAdUnit.id, updatedAdUnit.name,
                            String.Join(",", adUnitSizeStrings));
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to update ad units. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
        /// <summary>
        /// Run the code examples.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the ProductTemplateService.
            ProductTemplateService productTemplateService =
                (ProductTemplateService)user.GetService(DfpService.v201708.ProductTemplateService);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            countryLocation.id = 2840L;

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

            regionLocation.id = 2344L;

            GeoTargeting geoTargeting = new GeoTargeting();

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

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

            chromeBrowser.id = 500072L;

            BrowserTargeting browserTargeting = new BrowserTargeting();

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

            TechnologyTargeting technologyTargeting = new TechnologyTargeting();

            technologyTargeting.browserTargeting = browserTargeting;

            Targeting productTemplateTargeting = new Targeting();

            productTemplateTargeting.technologyTargeting = technologyTargeting;

            productTemplate.builtInTargeting = productTemplateTargeting;

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

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

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

            productTemplate.productSegmentation = productSegmentation;

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

                foreach (ProductTemplate createdProductTemplate in productTemplates)
                {
                    Console.WriteLine("A product template with ID \"{0}\" and name \"{1}\" was created.",
                                      createdProductTemplate.id, createdProductTemplate.name);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create product templates. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (ProductTemplateService productTemplateService =
                       (ProductTemplateService)user.GetService(DfpService.v201805.ProductTemplateService))
            {
                // Set the ID of the product template to activate.
                long productTemplateId = long.Parse(_T("INSERT_PRODUCT_TEMPLATE_ID_HERE"));

                // Create statement to select a product template by ID.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :id")
                                                    .OrderBy("id ASC")
                                                    .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                    .AddValue("id", productTemplateId);

                // Set default for page.
                ProductTemplatePage page = new ProductTemplatePage();
                List <string>       productTemplateIds = new List <string>();

                try
                {
                    do
                    {
                        // Get product templates by statement.
                        page = productTemplateService.getProductTemplatesByStatement(
                            statementBuilder.ToStatement());

                        if (page.results != null)
                        {
                            int i = page.startIndex;
                            foreach (ProductTemplate productTemplate in page.results)
                            {
                                Console.WriteLine(
                                    "{0}) Product template with ID ='{1}' will be activated.", i++,
                                    productTemplate.id);
                                productTemplateIds.Add(productTemplate.id.ToString());
                            }
                        }

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

                    Console.WriteLine("Number of product templates to be activated: {0}",
                                      productTemplateIds.Count);

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

                        // Create action.
                        Google.Api.Ads.Dfp.v201805.ActivateProductTemplates action =
                            new Google.Api.Ads.Dfp.v201805.ActivateProductTemplates();

                        // Perform action.
                        UpdateResult result =
                            productTemplateService.performProductTemplateAction(action,
                                                                                statementBuilder.ToStatement());

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine("Number of product templates activated: {0}",
                                              result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No product templates were activated.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(
                        "Failed to activate product templates. Exception says \"{0}\"", e.Message);
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (UserTeamAssociationService userTeamAssociationService =
                       (UserTeamAssociationService)user.GetService(DfpService.v201805
                                                                   .UserTeamAssociationService))
            {
                // Set the user id of the user team association to update.
                long userId = long.Parse(_T("INSERT_USER_ID_HERE"));

                // Set the team id of the user team association to update.
                long teamId = long.Parse(_T("INSERT_TEAM_ID_HERE"));

                // Create a statement to select the user team association.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("userId = :userId and teamId = :teamId")
                                                    .OrderBy("userId ASC, teamId ASC")
                                                    .Limit(1)
                                                    .AddValue("userId", userId)
                                                    .AddValue("teamId", teamId);

                try
                {
                    // Get user team associations by statement.
                    UserTeamAssociationPage page =
                        userTeamAssociationService.getUserTeamAssociationsByStatement(
                            statementBuilder.ToStatement());

                    UserTeamAssociation userTeamAssociation = page.results[0];

                    userTeamAssociation.overriddenTeamAccessType = TeamAccessType.READ_ONLY;

                    // Update the user team associations on the server.
                    UserTeamAssociation[] userTeamAssociations =
                        userTeamAssociationService.updateUserTeamAssociations(
                            new UserTeamAssociation[]
                    {
                        userTeamAssociation
                    });

                    if (userTeamAssociations != null)
                    {
                        foreach (UserTeamAssociation updatedUserTeamAssociation in
                                 userTeamAssociations)
                        {
                            Console.WriteLine(
                                "User team association between user with ID \"{0}\" and team " +
                                "with ID \"{1}\" was updated to access type \"{2}\".",
                                updatedUserTeamAssociation.userId,
                                updatedUserTeamAssociation.teamId,
                                updatedUserTeamAssociation.overriddenTeamAccessType);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No user team associations updated.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(
                        "Failed to update user team associations. Exception says \"{0}\"",
                        e.Message);
                }
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (WorkflowRequestService workflowRequestService =
                       (WorkflowRequestService)user.GetService(DfpService.v201805.WorkflowRequestService)) {
                // Set the ID of the proposal to approve workflow approval requests for.
                long proposalId = long.Parse(_T("INSERT_PROPOSAL_ID_HERE"));

                // Create a statement to select workflow approval requests for a proposal.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("WHERE entityId = :entityId and entityType = :entityType and type = :type")
                                                    .OrderBy("id ASC")
                                                    .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                    .AddValue("entityId", proposalId)
                                                    .AddValue("entityType", WorkflowEntityType.PROPOSAL.ToString())
                                                    .AddValue("type", WorkflowRequestType.WORKFLOW_APPROVAL_REQUEST.ToString());

                // Set default for page.
                WorkflowRequestPage page = new WorkflowRequestPage();
                List <long>         worflowRequestIds = new List <long>();

                try {
                    do
                    {
                        // Get workflow requests by statement.
                        page = workflowRequestService.getWorkflowRequestsByStatement(
                            statementBuilder.ToStatement());

                        if (page.results != null)
                        {
                            int i = page.startIndex;
                            foreach (WorkflowRequest workflowRequest in page.results)
                            {
                                Console.WriteLine("{0})  Workflow approval request with ID '{1}' will be " +
                                                  "approved.", i++, workflowRequest.id);
                                worflowRequestIds.Add(workflowRequest.id);
                            }
                        }

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

                    Console.WriteLine("Number of workflow approval requests to be approved: {0}",
                                      worflowRequestIds.Count);

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

                        // Create action.
                        Google.Api.Ads.Dfp.v201805.ApproveWorkflowApprovalRequests action =
                            new Google.Api.Ads.Dfp.v201805.ApproveWorkflowApprovalRequests();

                        // Add a comment to the approval.
                        action.comment = "The proposal looks good to me. Approved.";

                        // Perform action.
                        UpdateResult result = workflowRequestService.performWorkflowRequestAction(action,
                                                                                                  statementBuilder.ToStatement());

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine("Number of workflow requests approved: {0}", result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No workflow requests were approved.");
                        }
                    }
                } catch (Exception e) {
                    Console.WriteLine("Failed to archive workflow requests. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the ProductTemplateService.
            ProductTemplateService productTemplateService =
                (ProductTemplateService)user.GetService(DfpService.v201611.ProductTemplateService);

            // Set the ID of the product template.
            long productTemplateId = long.Parse(_T("INSERT_PRODUCT_TEMPLATE_ID_HERE"));

            // Create a statement to get the product template.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("id = :id")
                                                .OrderBy("id ASC")
                                                .Limit(1)
                                                .AddValue("id", productTemplateId);

            try {
                // Get product templates by statement.
                ProductTemplatePage page = productTemplateService
                                           .getProductTemplatesByStatement(statementBuilder.ToStatement());

                ProductTemplate productTemplate = page.results[0];

                // Add geo targeting for Canada to the product template.
                Location countryLocation = new Location();
                countryLocation.id = 2124L;

                Targeting    productTemplateTargeting = productTemplate.builtInTargeting;
                GeoTargeting geoTargeting             = productTemplateTargeting.geoTargeting;

                List <Location> existingTargetedLocations = new List <Location>();

                if (geoTargeting == null)
                {
                    geoTargeting = new GeoTargeting();
                }
                else if (geoTargeting.targetedLocations != null)
                {
                    existingTargetedLocations = new List <Location>(geoTargeting.targetedLocations);
                }

                existingTargetedLocations.Add(countryLocation);

                Location[] newTargetedLocations = new Location[existingTargetedLocations.Count];
                existingTargetedLocations.CopyTo(newTargetedLocations);
                geoTargeting.targetedLocations = newTargetedLocations;

                productTemplateTargeting.geoTargeting = geoTargeting;
                productTemplate.builtInTargeting      = productTemplateTargeting;

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

                if (productTemplates != null)
                {
                    foreach (ProductTemplate updatedProductTemplate in productTemplates)
                    {
                        Console.WriteLine("A product template with ID = '{0}' and name '{1}' was updated.",
                                          updatedProductTemplate.id, updatedProductTemplate.name);
                    }
                }
                else
                {
                    Console.WriteLine("No product templates updated.");
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to update product templates. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <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);

            // Set the ID of the custom field to update.
            int customFieldId = int.Parse(_T("INSERT_CUSTOM_FIELD_ID_HERE"));

            // Create statement to select only active custom fields that apply to
            // line items.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("id = :id")
                                                .OrderBy("id ASC")
                                                .Limit(1)
                                                .AddValue("id", customFieldId);

            // Set default for page.
            CustomFieldPage page           = new CustomFieldPage();
            int             i              = 0;
            List <string>   customFieldIds = new List <string>();

            try {
                do
                {
                    // Get custom fields by statement.
                    page = customFieldService.getCustomFieldsByStatement(statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        foreach (CustomField customField in page.results)
                        {
                            Console.WriteLine("{0}) Custom field with ID \"{1}\" and name \"{2}\" will be " +
                                              "deactivated.", i, customField.id, customField.name);
                            customFieldIds.Add(customField.id.ToString());
                            i++;
                        }
                    }
                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                Console.WriteLine("Number of custom fields to be deactivated: " + customFieldIds.Count);

                if (customFieldIds.Count > 0)
                {
                    // Remove limit and offset from statement.
                    statementBuilder.RemoveLimitAndOffset();

                    // Create action.
                    Google.Api.Ads.Dfp.v201502.DeactivateCustomFields action =
                        new Google.Api.Ads.Dfp.v201502.DeactivateCustomFields();

                    // Perform action.
                    UpdateResult result = customFieldService.performCustomFieldAction(action,
                                                                                      statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of custom fields deactivated: " + result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No custom fields were deactivated.");
                    }
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to deactivate custom fields. 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 CustomTargetingService.
            CustomTargetingService customTargetingService =
                (CustomTargetingService)user.GetService(DfpService.v201405.CustomTargetingService);

            // Create predefined key.
            CustomTargetingKey genderKey = new CustomTargetingKey();

            genderKey.displayName = "gender";
            genderKey.name        = "g";
            genderKey.type        = CustomTargetingKeyType.PREDEFINED;

            // Create predefined key that may be used for content targeting.
            CustomTargetingKey genreKey = new CustomTargetingKey();

            genreKey.displayName = "genre";
            genreKey.name        = "genre";
            genreKey.type        = CustomTargetingKeyType.PREDEFINED;

            // Create free-form key.
            CustomTargetingKey carModelKey = new CustomTargetingKey();

            carModelKey.displayName = "car model";
            carModelKey.name        = "c";
            carModelKey.type        = CustomTargetingKeyType.FREEFORM;

            try {
                // Create the custom targeting keys on the server.
                CustomTargetingKey[] keys = customTargetingService.createCustomTargetingKeys(
                    new CustomTargetingKey[] { genderKey, genreKey, carModelKey });

                if (keys != null)
                {
                    foreach (CustomTargetingKey key in keys)
                    {
                        Console.WriteLine("A custom targeting key with ID \"{0}\", name \"{1}\", and display " +
                                          "name \"{2}\" was created.", key.id, key.name, key.displayName);
                    }
                }
                else
                {
                    Console.WriteLine("No keys were created.");
                }

                // Create custom targeting value for the predefined gender key.
                CustomTargetingValue genderMaleValue = new CustomTargetingValue();
                genderMaleValue.customTargetingKeyId = keys[0].id;
                genderMaleValue.displayName          = "male";
                // Name is set to 1 so that the actual name can be hidden from website
                // users.
                genderMaleValue.name      = "1";
                genderMaleValue.matchType = CustomTargetingValueMatchType.EXACT;

                CustomTargetingValue genderFemaleValue = new CustomTargetingValue();
                genderFemaleValue.customTargetingKeyId = keys[0].id;
                genderFemaleValue.displayName          = "female";
                // Name is set to 2 so that the actual name can be hidden from website
                // users.
                genderFemaleValue.name      = "2";
                genderFemaleValue.matchType = CustomTargetingValueMatchType.EXACT;

                // Create custom targeting value for the predefined genre key.
                CustomTargetingValue genreComedyValue = new CustomTargetingValue();
                genreComedyValue.customTargetingKeyId = keys[1].id;
                genreComedyValue.displayName          = "comedy";
                genreComedyValue.name      = "comedy";
                genreComedyValue.matchType = CustomTargetingValueMatchType.EXACT;

                CustomTargetingValue genreDramaValue = new CustomTargetingValue();
                genreDramaValue.customTargetingKeyId = keys[1].id;
                genreDramaValue.displayName          = "drama";
                genreDramaValue.name      = "drama";
                genreDramaValue.matchType = CustomTargetingValueMatchType.EXACT;

                // Create custom targeting value for the free-form age key. These are
                // values that would be suggested in the UI or can be used when
                // targeting with a FreeFormCustomCriteria.
                CustomTargetingValue carModelHondaCivicValue = new CustomTargetingValue();
                carModelHondaCivicValue.customTargetingKeyId = keys[2].id;
                carModelHondaCivicValue.displayName          = "honda civic";
                carModelHondaCivicValue.name = "honda civic";
                // Setting match type to exact will match exactly "honda civic".
                carModelHondaCivicValue.matchType = CustomTargetingValueMatchType.EXACT;

                // Create the custom targeting values on the server.
                CustomTargetingValue[] returnValues = customTargetingService.createCustomTargetingValues(
                    new CustomTargetingValue[] { genderMaleValue, genderFemaleValue, genreComedyValue,
                                                 genreDramaValue, carModelHondaCivicValue });

                if (returnValues != null)
                {
                    foreach (CustomTargetingValue value in returnValues)
                    {
                        Console.WriteLine("A custom targeting value with ID \"{0}\", belonging to key with " +
                                          "ID \"{1}\", name \"{2}\", and display name \"{3}\" was created.", value.id,
                                          value.customTargetingKeyId, value.name, value.displayName);
                    }
                }
                else
                {
                    Console.WriteLine("No values were created.");
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to create custom targeting keys and values. 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 PlacementService.
            PlacementService placementService =
                (PlacementService)user.GetService(DfpService.v201605.PlacementService);

            // Create statement to select active placements.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("status = :status")
                                                .OrderBy("id ASC")
                                                .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                .AddValue("status", InventoryStatus.ACTIVE.ToString());

            // Sets default for page.
            PlacementPage page         = new PlacementPage();
            List <string> placementIds = new List <string>();

            try {
                do
                {
                    // Get placements by statement.
                    page = placementService.getPlacementsByStatement(statementBuilder.ToStatement());

                    if (page.results != null && page.results.Length > 0)
                    {
                        int i = page.startIndex;
                        foreach (Placement placement in page.results)
                        {
                            Console.WriteLine("{0}) Placement with ID ='{1}', name ='{2}', and status ='{3}'" +
                                              " will be deactivated.", i, placement.id, placement.name, placement.status);
                            placementIds.Add(placement.id.ToString());
                            i++;
                        }
                    }

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

                Console.WriteLine("Number of placements to be deactivated: {0}", placementIds.Count);

                if (placementIds.Count > 0)
                {
                    // Modify statement for action.
                    statementBuilder.RemoveLimitAndOffset();

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

                    // Perform action.
                    UpdateResult result = placementService.performPlacementAction(action,
                                                                                  statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of placements deactivated: {0}", result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No placements were deactivated.");
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to deactivate placements. Exception says \"{0}\"",
                                  e.Message);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public void Run(DfpUser user)
        {
            // Get the ForecastService.
            ForecastService forecastService =
                (ForecastService)user.GetService(DfpService.v201608.ForecastService);

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

            // Set the ID of the advertiser (company) to forecast for. Setting an advertiser
            // will cause the forecast to apply the appropriate unified blocking rules.
            long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE"));

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

            lineItem.targeting = new Targeting();
            lineItem.targeting.inventoryTargeting = new InventoryTargeting();
            lineItem.targeting.inventoryTargeting.targetedPlacementIds = targetPlacementIds;

            Size size = new Size();

            size.width  = 300;
            size.height = 250;

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

            creativePlaceholder.size = size;

            lineItem.creativePlaceholders = new CreativePlaceholder[] { creativePlaceholder };

            lineItem.lineItemType      = LineItemType.SPONSORSHIP;
            lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;

            // Set the line item to run for one month.
            lineItem.endDateTime =
                DateTimeUtilities.FromDateTime(System.DateTime.Now.AddMonths(1), "America/New_York");

            // Set the cost type to match the unit type.
            lineItem.costType = CostType.CPM;
            Goal goal = new Goal();

            goal.goalType        = GoalType.DAILY;
            goal.unitType        = UnitType.IMPRESSIONS;
            goal.units           = 50L;
            lineItem.primaryGoal = goal;

            try {
                // [START forecasting_3] MOE:strip_line
                // Get availability forecast.
                AvailabilityForecastOptions options = new AvailabilityForecastOptions();
                options.includeContendingLineItems        = true;
                options.includeTargetingCriteriaBreakdown = true;
                ProspectiveLineItem prospectiveLineItem = new ProspectiveLineItem();
                prospectiveLineItem.advertiserId = advertiserId;
                prospectiveLineItem.lineItem     = lineItem;
                AvailabilityForecast forecast =
                    forecastService.getAvailabilityForecast(prospectiveLineItem, options);
                // [END forecasting_3] MOE:strip_line

                // Display results.
                long   matched          = forecast.matchedUnits;
                double availablePercent = (double)(forecast.availableUnits / (matched * 1.0)) * 100;
                String unitType         = forecast.unitType.ToString().ToLower();
                Console.WriteLine("{0} {1} matched.\n{2}%  available.", matched, unitType,
                                  availablePercent, unitType);

                if (forecast.possibleUnitsSpecified)
                {
                    double possiblePercent = (double)(forecast.possibleUnits / (matched * 1.0)) * 100;
                    Console.WriteLine("{0}% {1} possible.\n", possiblePercent, unitType);
                }
                Console.WriteLine("{0} contending line items.", (forecast.contendingLineItems != null) ?
                                  forecast.contendingLineItems.Length : 0);
            } catch (Exception e) {
                Console.WriteLine("Failed to get forecast. Exception says \"{0}\"", e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (UserService userService =
                       (UserService)user.GetService(DfpService.v201805.UserService))
            {
                // Set the ID of the user to deactivate
                long userId = long.Parse(_T("INSERT_USER_ID_HERE"));

                // Create statement text to select user by id.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :userId")
                                                    .OrderBy("id ASC")
                                                    .Limit(1)
                                                    .AddValue("userId", userId);

                // Sets default for page.
                UserPage      page    = new UserPage();
                List <string> userIds = new List <string>();

                try
                {
                    do
                    {
                        // Get users by statement.
                        page = userService.getUsersByStatement(statementBuilder.ToStatement());

                        if (page.results != null)
                        {
                            int i = page.startIndex;
                            foreach (User userResult in page.results)
                            {
                                Console.WriteLine(
                                    "{0}) User with ID = '{1}', email = '{2}', and status = '{3}'" +
                                    " will be deactivated.", i, userResult.id, userResult.email,
                                    userResult.isActive ? "ACTIVE" : "INACTIVE");
                                userIds.Add(userResult.id.ToString());
                                i++;
                            }
                        }

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

                    Console.WriteLine("Number of users to be deactivated: {0}",
                                      page.totalResultSetSize);

                    if (userIds.Count > 0)
                    {
                        // Modify statement for action.
                        statementBuilder.RemoveLimitAndOffset();

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

                        // Perform action.
                        UpdateResult result =
                            userService.performUserAction(action, statementBuilder.ToStatement());

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine(
                                "Number of users deactivated: {0}" + result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No users were deactivated.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to deactivate users. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Ejemplo n.º 25
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)
        {
            // Create the CreativeWrapperService.
            CreativeWrapperService creativeWrapperService = (CreativeWrapperService)user.GetService(
                DfpService.v201502.CreativeWrapperService);

            long labelId = long.Parse(_T("INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE"));

            try {
                // Create a query to select the active creative wrapper for the given
                // label.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("labelId = :labelId AND status = :status")
                                                    .OrderBy("id ASC")
                                                    .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                    .AddValue("status", CreativeWrapperStatus.ACTIVE.ToString())
                                                    .AddValue("labelId", labelId);

                // Set default for page.
                CreativeWrapperPage page = new CreativeWrapperPage();

                do
                {
                    page =
                        creativeWrapperService.getCreativeWrappersByStatement(statementBuilder.ToStatement());
                    CreativeWrapper[] creativeWrappers = page.results;
                    if (creativeWrappers != null)
                    {
                        foreach (CreativeWrapper wrapper in creativeWrappers)
                        {
                            Console.WriteLine("Creative wrapper with ID \'{0}\' applying to label \'{1}\' with " +
                                              "status \'{2}\' will be deactivated.", wrapper.id, wrapper.labelId,
                                              wrapper.status);
                        }
                    }
                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                Console.WriteLine("Number of creative wrappers to be deactivated: {0}",
                                  page.totalResultSetSize);

                // Modify statement for action.
                statementBuilder.RemoveLimitAndOffset();

                // Perform action.
                CreativeWrapperAction action = new DeactivateCreativeWrappers();
                UpdateResult          result = creativeWrapperService.performCreativeWrapperAction(action,
                                                                                                   statementBuilder.ToStatement());

                // Display results.
                if (result.numChanges > 0)
                {
                    Console.WriteLine("Number of creative wrappers deactivated: {0}", result.numChanges);
                }
                else
                {
                    Console.WriteLine("No creative wrappers were deactivated.");
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to create creative wrappers. 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.v201511.CustomFieldService);

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

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

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

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

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

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

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

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

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

                lineItem.customFieldValues = customFieldValues.ToArray();

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

                if (lineItems != null)
                {
                    foreach (LineItem updatedLineItem in lineItems)
                    {
                        List <String> customFieldValueStrings = new List <String>();
                        foreach (BaseCustomFieldValue baseCustomFieldValue in lineItem.customFieldValues)
                        {
                            if (baseCustomFieldValue is CustomFieldValue &&
                                ((CustomFieldValue)baseCustomFieldValue).value is TextValue)
                            {
                                customFieldValueStrings.Add("{ID: '" + baseCustomFieldValue.customFieldId
                                                            + "', value: '"
                                                            + ((TextValue)((CustomFieldValue)baseCustomFieldValue).value).value
                                                            + "'}");
                            }
                            else if (baseCustomFieldValue is DropDownCustomFieldValue)
                            {
                                customFieldValueStrings.Add("{ID: '" + baseCustomFieldValue.customFieldId
                                                            + "', custom field option ID: '"
                                                            + ((DropDownCustomFieldValue)baseCustomFieldValue).customFieldOptionId
                                                            + "'}");
                            }
                        }
                        Console.WriteLine("A line item with ID \"{0}\" set with custom field values \"{1}\".",
                                          updatedLineItem.id, string.Join(", ", customFieldValueStrings.ToArray()));
                    }
                }
                else
                {
                    Console.WriteLine("No line items were updated.");
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to update line items. Exception says \"{0}\"", e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            // Get the LabelService.
            LabelService labelService =
                (LabelService)user.GetService(DfpService.v201505.LabelService);

            // Set the ID of the label to deactivate.
            int labelId = int.Parse(_T("INSERT_LABEL_ID_HERE"));

            // Create statement text to select the label.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("id = :id")
                                                .OrderBy("id ASC")
                                                .Limit(1)
                                                .AddValue("id", labelId);

            // Set default for page.
            LabelPage page = new LabelPage();

            try {
                do
                {
                    // Get labels by statement.
                    page = labelService.getLabelsByStatement(statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        int i = page.startIndex;
                        foreach (Label label in page.results)
                        {
                            Console.WriteLine("{0}) Label with ID '{1}', name '{2}' will be deactivated.",
                                              i, label.id, label.name);
                            i++;
                        }
                    }
                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                Console.WriteLine("Number of labels to be deactivated: " + page.totalResultSetSize);

                // Modify statement for action.
                statementBuilder.RemoveLimitAndOffset();

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

                // Perform action.
                UpdateResult result = labelService.performLabelAction(action,
                                                                      statementBuilder.ToStatement());

                // Display results.
                if (result != null && result.numChanges > 0)
                {
                    Console.WriteLine("Number of labels deactivated: " + result.numChanges);
                }
                else
                {
                    Console.WriteLine("No labels were deactivated.");
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to deactivate labels. Exception says \"{0}\"", ex.Message);
            }
        }
Ejemplo n.º 28
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 AudienceSegmentService.
            AudienceSegmentService audienceSegmentService = (AudienceSegmentService)user.GetService(
                DfpService.v201403.AudienceSegmentService);

            // Get the NetworkService.
            NetworkService networkService = (NetworkService)user.GetService(
                DfpService.v201403.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 ex) {
                Console.WriteLine("Failed to get audience segment. Exception says \"{0}\"", ex.Message);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public void Run(DfpUser user)
        {
            // Get the LineItemCreativeAssociationService.
            LineItemCreativeAssociationService licaService = (LineItemCreativeAssociationService)
                                                             user.GetService(DfpService.v201605.LineItemCreativeAssociationService);

            // Set the line item to get LICAs by.
            long lineItemId = long.Parse(_T("INSERT_LINE_ITEM_ID_HERE"));

            // Create a statement to page through active LICAs.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("lineItemId = :lineItemId")
                                                .OrderBy("lineItemId ASC, creativeId ASC")
                                                .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                .AddValue("lineItemId", lineItemId);

            // Set default for page.
            LineItemCreativeAssociationPage page = new LineItemCreativeAssociationPage();
            List <string> creativeIds            = new List <string>();

            try {
                do
                {
                    // Get LICAs by statement.
                    page = licaService.getLineItemCreativeAssociationsByStatement(
                        statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        int i = page.startIndex;
                        foreach (LineItemCreativeAssociation lica in page.results)
                        {
                            Console.WriteLine("{0}) LICA with line item ID = '{1}', creative ID ='{2}' and " +
                                              "status ='{3}' will be deactivated.", i, lica.lineItemId, lica.creativeId,
                                              lica.status);
                            i++;
                            creativeIds.Add(lica.creativeId.ToString());
                        }
                    }

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

                Console.WriteLine("Number of LICAs to be deactivated: {0}", creativeIds.Count);

                if (creativeIds.Count > 0)
                {
                    // Modify statement for action.
                    statementBuilder.RemoveLimitAndOffset();

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

                    // Perform action.
                    UpdateResult result = licaService.performLineItemCreativeAssociationAction(action,
                                                                                               statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of LICAs deactivated: {0}", result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No LICAs were deactivated.");
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to deactivate LICAs. Exception says \"{0}\"", e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201702.ReportService);

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

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

            // [START report_guide_include_1] MOE:strip_line
            // Create report job.
            ReportJob reportJob = new ReportJob();

            reportJob.reportQuery                     = new ReportQuery();
            reportJob.reportQuery.dimensions          = new Dimension[] { Dimension.ORDER_ID, Dimension.ORDER_NAME };
            reportJob.reportQuery.dimensionAttributes = new DimensionAttribute[] {
                DimensionAttribute.ORDER_TRAFFICKER, DimensionAttribute.ORDER_START_DATE_TIME,
                DimensionAttribute.ORDER_END_DATE_TIME
            };
            reportJob.reportQuery.columns = new Column[] { Column.AD_SERVER_IMPRESSIONS,
                                                           Column.AD_SERVER_CLICKS, Column.AD_SERVER_CTR, Column.AD_SERVER_CPM_AND_CPC_REVENUE,
                                                           Column.AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM };

            // Set a custom date range for the last 8 days
            reportJob.reportQuery.dateRangeType = DateRangeType.CUSTOM_DATE;
            System.DateTime endDateTime = System.DateTime.Now;
            reportJob.reportQuery.startDate =
                DateTimeUtilities.FromDateTime(endDateTime.AddDays(-8), "America/New_York").date;
            reportJob.reportQuery.endDate =
                DateTimeUtilities.FromDateTime(endDateTime, "America/New_York").date;

            // Create statement object to filter for an order.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("ORDER_ID = :id")
                                                .AddValue("id", orderId);

            reportJob.reportQuery.statement = statementBuilder.ToStatement();
            // [END report_guide_include_1] MOE:strip_line

            try {
                // [START report_guide_include_2] MOE:strip_line
                // Run report job.
                reportJob = reportService.runReportJob(reportJob);
                // [END report_guide_include_2] MOE:strip_line

                // [START report_guide_include_3] MOE:strip_line
                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);
                // [END report_guide_include_3] MOE:strip_line
            } catch (Exception e) {
                Console.WriteLine("Failed to run delivery report. Exception says \"{0}\"",
                                  e.Message);
            }
        }