/// <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.v201411.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 e) {
                Console.WriteLine("Failed to deactivate labels. Exception says \"{0}\"", e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            ReportService reportService = (ReportService)user.GetService(
                DfpService.v201708.ReportService);

            // Get the NetworkService.
            NetworkService networkService = (NetworkService)user.GetService(
                DfpService.v201708.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);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the CreativeService.
            CreativeService creativeService =
                (CreativeService)user.GetService(DfpService.v201705.CreativeService);

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

            // Use the image banner with optional third party tracking template.
            long creativeTemplateId = 10000680L;

            // Create the local custom creative object.
            TemplateCreative templateCreative = new TemplateCreative();

            templateCreative.name               = "Template creative";
            templateCreative.advertiserId       = advertiserId;
            templateCreative.creativeTemplateId = creativeTemplateId;

            // Set the creative size.
            Size size = new Size();

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

            templateCreative.size = size;

            // Create the asset variable value.
            AssetCreativeTemplateVariableValue assetVariableValue =
                new AssetCreativeTemplateVariableValue();

            assetVariableValue.uniqueName = "Imagefile";
            CreativeAsset asset = new CreativeAsset();

            asset.assetByteArray = MediaUtilities.GetAssetDataFromUrl(
                "http://www.google.com/intl/en/adwords/select/images/samples/inline.jpg");
            asset.fileName           = String.Format("image{0}.jpg", this.GetTimeStamp());
            assetVariableValue.asset = asset;

            // Create the image width variable value.
            LongCreativeTemplateVariableValue imageWidthVariableValue =
                new LongCreativeTemplateVariableValue();

            imageWidthVariableValue.uniqueName = "Imagewidth";
            imageWidthVariableValue.value      = 300;

            // Create the image height variable value.
            LongCreativeTemplateVariableValue imageHeightVariableValue =
                new LongCreativeTemplateVariableValue();

            imageHeightVariableValue.uniqueName = "Imageheight";
            imageHeightVariableValue.value      = 250;

            // Create the URL variable value.
            UrlCreativeTemplateVariableValue urlVariableValue = new UrlCreativeTemplateVariableValue();

            urlVariableValue.uniqueName = "ClickthroughURL";
            urlVariableValue.value      = "www.google.com";

            // Create the target window variable value.
            StringCreativeTemplateVariableValue targetWindowVariableValue =
                new StringCreativeTemplateVariableValue();

            targetWindowVariableValue.uniqueName = "Targetwindow";
            targetWindowVariableValue.value      = "_blank";

            templateCreative.creativeTemplateVariableValues = new BaseCreativeTemplateVariableValue[] {
                assetVariableValue, imageWidthVariableValue, imageHeightVariableValue, urlVariableValue,
                targetWindowVariableValue
            };

            try {
                // Create the template creative on the server.
                Creative[] createdTemplateCreatives = creativeService.createCreatives(
                    new Creative[] { templateCreative });

                foreach (Creative createdTemplateCreative in createdTemplateCreatives)
                {
                    Console.WriteLine("A template creative with ID \"{0}\", name \"{1}\", and type " +
                                      "\"{2}\" was created and can be previewed at {3}", createdTemplateCreative.id,
                                      createdTemplateCreative.name, createdTemplateCreative.GetType().Name,
                                      createdTemplateCreative.previewUrl);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create creatives. Exception says \"{0}\"", e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            // Get the LineItemService.
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201411.LineItemService);

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

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

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

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

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

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


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

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

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

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

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of line items activated: {0}", result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No line items were activated.");
                    }
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to activate line items. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the InventoryService.
            InventoryService inventoryService =
                (InventoryService)user.GetService(DfpService.v201602.InventoryService);

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

            // Set the parent ad unit's ID for all ad units to be created under.
            String effectiveRootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;

            // Create local ad unit object.
            AdUnit adUnit = new AdUnit();

            adUnit.name               = "Video_Ad_Unit";
            adUnit.parentId           = effectiveRootAdUnitId;
            adUnit.description        = "Ad unit description.";
            adUnit.targetWindow       = AdUnitTargetWindow.BLANK;
            adUnit.explicitlyTargeted = true;

            // Create master ad unit size.
            AdUnitSize masterAdUnitSize = new AdUnitSize();
            Size       size1            = new Size();

            size1.width                      = 400;
            size1.height                     = 300;
            size1.isAspectRatio              = false;
            masterAdUnitSize.size            = size1;
            masterAdUnitSize.environmentType = EnvironmentType.VIDEO_PLAYER;

            // Create companion sizes.
            AdUnitSize companionAdUnitSize1 = new AdUnitSize();
            Size       size2 = new Size();

            size2.width                          = 300;
            size2.height                         = 250;
            size2.isAspectRatio                  = false;
            companionAdUnitSize1.size            = size2;
            companionAdUnitSize1.environmentType = EnvironmentType.BROWSER;

            AdUnitSize companionAdUnitSize2 = new AdUnitSize();
            Size       size3 = new Size();

            size3.width                          = 728;
            size3.height                         = 90;
            size3.isAspectRatio                  = false;
            companionAdUnitSize2.size            = size3;
            companionAdUnitSize2.environmentType = EnvironmentType.BROWSER;

            // Add companions to master ad unit size.
            masterAdUnitSize.companions = new AdUnitSize[] { companionAdUnitSize1, companionAdUnitSize2 };

            // Set the size of possible creatives that can match this ad unit.
            adUnit.adUnitSizes = new AdUnitSize[] { masterAdUnitSize };

            try {
                // Create the ad unit on the server.
                AdUnit[] createdAdUnits = inventoryService.createAdUnits(new AdUnit[] { adUnit });

                foreach (AdUnit createdAdUnit in createdAdUnits)
                {
                    Console.WriteLine("A video ad unit with ID \"{0}\" was created under parent with ID " +
                                      "\"{1}\".", createdAdUnit.id, createdAdUnit.parentId);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create video ad units. Exception says \"{0}\"", e.Message);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (CreativeService creativeService =
                       (CreativeService)user.GetService(DfpService.v201705.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 examples.
        /// </summary>
        /// <param name="user">The DFP user object running the code examples.</param>
        public override void Run(DfpUser user)
        {
            // Get the ProductTemplateService.
            ProductTemplateService productTemplateService =
                (ProductTemplateService)user.GetService(DfpService.v201505.ProductTemplateService);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            countryLocation.id = 2840L;

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

            regionLocation.id = 2344L;

            GeoTargeting geoTargeting = new GeoTargeting();

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

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

            chromeBrowser.id = 500072L;

            BrowserTargeting browserTargeting = new BrowserTargeting();

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

            ProductTemplateTargeting productTemplateTargeting = new ProductTemplateTargeting();

            productTemplateTargeting.browserTargeting = browserTargeting;

            productTemplate.targeting = productTemplateTargeting;

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

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

            productTemplate.productSegmentation = productSegmentation;

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

                foreach (ProductTemplate createdProductTemplate in productTemplates)
                {
                    Console.WriteLine("A product template with ID \"{0}\" and name \"{1}\" was created.",
                                      createdProductTemplate.id, createdProductTemplate.name);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create product templates. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        /// <summary>
        /// Run the code examples.
        /// </summary>
        /// <param name="user">The DFP user object running the code examples.</param>
        public void Run(DfpUser user, long proposalId)
        {
            // Get the ProposalLineItemService.
            ProposalLineItemService proposalLineItemService =
                (ProposalLineItemService)user.GetService(DfpService.v201608.ProposalLineItemService);

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

            ProposalLineItem proposalLineItem = new ProposalLineItem();

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

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

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

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

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

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

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

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

            targeting.inventoryTargeting = inventoryTargeting;
            proposalLineItem.targeting   = targeting;

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

            creativePlaceholder.size = size;

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

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

            // Set delivery specifications for the proposal line item.
            proposalLineItem.deliveryRateType = DeliveryRateType.EVENLY;

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

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

                foreach (ProposalLineItem createdProposalLineItem in proposalLineItems)
                {
                    Console.WriteLine("A programmatic proposal line item with ID \"{0}\" "
                                      + "and name \"{1}\" was created.",
                                      createdProposalLineItem.id,
                                      createdProposalLineItem.name);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create programmatic proposal line items. "
                                  + "Exception says \"{0}\"",
                                  e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // [START get_proposal_service] MOE:strip_line
            // Get the ProposalService.
            ProposalService proposalService =
                (ProposalService)user.GetService(DfpService.v201705.ProposalService);
            // [END get_proposal_service] MOE:strip_line

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

            // Set the advertiser, salesperson, and trafficker to assign to each
            // order.
            long advertiserId           = long.Parse(_T("INSERT_ADVERTISER_ID_HERE"));
            long primarySalespersonId   = long.Parse(_T("INSERT_PRIMARY_SALESPERSON_ID_HERE"));
            long secondarySalespersonId = long.Parse(_T("INSERT_SECONDARY_SALESPERSON_ID_HERE"));
            long primaryTraffickerId    = long.Parse(_T("INSERT_PRIMARY_TRAFFICKER_ID_HERE"));
            long secondaryTraffickerId  = long.Parse(_T("INSERT_SECONDARY_TRAFFICKER_ID_HERE"));

            // [START create_proposal_local] MOE:strip_line
            // Create a proposal.
            Proposal proposal = new Proposal();

            proposal.name = "Proposal #" + new Random().Next(int.MaxValue);
            // [END create_proposal_local] MOE:strip_line

            // [START add_proposal_company_associations] MOE:strip_line
            // Create a proposal company association.
            ProposalCompanyAssociation proposalCompanyAssociation = new ProposalCompanyAssociation();

            proposalCompanyAssociation.companyId = advertiserId;
            proposalCompanyAssociation.type      = ProposalCompanyAssociationType.ADVERTISER;
            proposal.advertiser = proposalCompanyAssociation;
            // [END add_proposal_company_associations] MOE:strip_line

            // [START add_salespeople] MOE:strip_line
            // Create salesperson splits for the primary salesperson and secondary salespeople.
            SalespersonSplit primarySalesperson = new SalespersonSplit();

            primarySalesperson.userId   = primarySalespersonId;
            primarySalesperson.split    = 75000;
            proposal.primarySalesperson = primarySalesperson;

            SalespersonSplit secondarySalesperson = new SalespersonSplit();

            secondarySalesperson.userId   = secondarySalespersonId;
            secondarySalesperson.split    = 25000;
            proposal.secondarySalespeople = new SalespersonSplit[] { secondarySalesperson };
            // [END add_salespeople] MOE:strip_line

            // [START set_probability_to_close] MOE:strip_line
            // Set the probability to close to 100%.
            proposal.probabilityOfClose = 100000L;
            // [END set_probability_to_close] MOE:strip_line

            // [START set_primary_trafficker] MOE:strip_line
            // Set the primary trafficker on the proposal for when it becomes an order.
            proposal.primaryTraffickerId = primaryTraffickerId;
            // [END set_primary_trafficker] MOE:strip_line

            // [START set_budget] MOE:strip_line
            // Create a budget for the proposal worth 100 in the network local currency.
            Money budget = new Money();

            budget.microAmount  = 100000000L;
            budget.currencyCode = networkService.getCurrentNetwork().currencyCode;
            proposal.budget     = budget;
            // [END set_budget] MOE:strip_line

            // [START set_billing_info] MOE:strip_line
            proposal.billingCap    = BillingCap.CAPPED_CUMULATIVE;
            proposal.billingSource = BillingSource.DFP_VOLUME;
            // [END set_billing_info] MOE:strip_line

            try {
                // [START create_proposal_server] MOE:strip_line
                // Create the proposal on the server.
                Proposal[] proposals = proposalService.createProposals(new Proposal[] { proposal });
                // [END create_proposal_server] MOE:strip_line

                foreach (Proposal createdProposal in proposals)
                {
                    Console.WriteLine("A proposal with ID \"{0}\" and name \"{1}\" was created.",
                                      createdProposal.id, createdProposal.name);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create proposals. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the SuggestedAdUnitService.
            SuggestedAdUnitService suggestedAdUnitService = (SuggestedAdUnitService)user.GetService(
                DfpService.v201702.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.v201702.ApproveSuggestedAdUnits action =
                    new Google.Api.Ads.Dfp.v201702.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);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the LineItemService.
            LineItemService lineItemService = (LineItemService)user.GetService(
                DfpService.v201708.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);
            }
        }
        /// <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.v201405.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.v201405.DeactivateCustomFields action =
                        new Google.Api.Ads.Dfp.v201405.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);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (ForecastService forecastService =
                       (ForecastService)user.GetService(DfpService.v201711.ForecastService)) {
                // Set the placement that the prospective line item will target.
                long[] targetPlacementIds = new long[] { long.Parse(_T("INSERT_PLACEMENT_ID_HERE")) };

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

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

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

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

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

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

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

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

                // Set the cost type to match the unit type.
                lineItem.costType = CostType.CPM;
                Goal goal = new Goal();
                goal.goalType        = GoalType.DAILY;
                goal.unitType        = UnitType.IMPRESSIONS;
                goal.units           = 50L;
                lineItem.primaryGoal = goal;

                try {
                    // Get availability forecast.
                    AvailabilityForecastOptions options = new AvailabilityForecastOptions();
                    options.includeContendingLineItems        = true;
                    options.includeTargetingCriteriaBreakdown = true;
                    ProspectiveLineItem prospectiveLineItem = new ProspectiveLineItem();
                    prospectiveLineItem.advertiserId = advertiserId;
                    prospectiveLineItem.lineItem     = lineItem;
                    AvailabilityForecast forecast =
                        forecastService.getAvailabilityForecast(prospectiveLineItem, options);

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

                    if (forecast.possibleUnitsSpecified)
                    {
                        double possiblePercent = (double)(forecast.possibleUnits / (matched * 1.0)) * 100;
                        Console.WriteLine("{0}% {1} possible.\n", possiblePercent, unitType);
                    }
                    Console.WriteLine("{0} contending line items.", (forecast.contendingLineItems != null) ?
                                      forecast.contendingLineItems.Length : 0);
                } catch (Exception e) {
                    Console.WriteLine("Failed to get forecast. Exception says \"{0}\"", e.Message);
                }
            }
        }
Beispiel #14
0
        /// <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.v201508.ProposalLineItemService);
            // [END get_proposal_line_item_service] MOE:strip_line

            // Get the NetworkService.
            NetworkService networkService =
                (NetworkService)user.GetService(DfpService.v201508.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);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (CreativeService creativeService =
                       (CreativeService)user.GetService(DfpService.v201802.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", user.Config);
                    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);
                }
            }
        }
Beispiel #16
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the CustomFieldService.
            CustomFieldService customFieldService = (CustomFieldService)user.GetService(
                DfpService.v201602.CustomFieldService);

            // Get the LineItemService.
            LineItemService lineItemService = (LineItemService)user.GetService(
                DfpService.v201602.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);
            }
        }
Beispiel #17
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (LineItemService lineItemService =
                       (LineItemService)user.GetService(DfpService.v201711.LineItemService)) {
                // Set the order that all created line items will belong to and the
                // video ad unit ID to target.
                long   orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));
                string targetedVideoAdUnitId = _T("INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE");

                // Set the custom targeting value ID representing the metadata
                // on the content to target. This would typically be from a key representing
                // a "genre" and a value representing something like "comedy". The value must
                // be from a key in a content metadata key hierarchy.
                long contentCustomTargetingValueId =
                    long.Parse(_T("INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE"));

                // Create content targeting.
                ContentMetadataKeyHierarchyTargeting contentMetadataTargeting =
                    new ContentMetadataKeyHierarchyTargeting();
                contentMetadataTargeting.customTargetingValueIds =
                    new long[] { contentCustomTargetingValueId };

                ContentTargeting contentTargeting = new ContentTargeting();
                contentTargeting.targetedContentMetadata =
                    new ContentMetadataKeyHierarchyTargeting[] { contentMetadataTargeting };

                // Create inventory targeting.
                InventoryTargeting inventoryTargeting = new InventoryTargeting();
                AdUnitTargeting    adUnitTargeting    = new AdUnitTargeting();
                adUnitTargeting.adUnitId           = targetedVideoAdUnitId;
                adUnitTargeting.includeDescendants = true;
                inventoryTargeting.targetedAdUnits = new AdUnitTargeting[] { adUnitTargeting };

                // Create video position targeting.
                VideoPosition videoPosition = new VideoPosition();
                videoPosition.positionType = VideoPositionType.PREROLL;
                VideoPositionTarget videoPositionTarget = new VideoPositionTarget();
                videoPositionTarget.videoPosition = videoPosition;
                VideoPositionTargeting videoPositionTargeting = new VideoPositionTargeting();
                videoPositionTargeting.targetedPositions =
                    new VideoPositionTarget[] { videoPositionTarget };

                // Create targeting.
                Targeting targeting = new Targeting();
                targeting.contentTargeting       = contentTargeting;
                targeting.inventoryTargeting     = inventoryTargeting;
                targeting.videoPositionTargeting = videoPositionTargeting;

                // Create local line item object.
                LineItem lineItem = new LineItem();
                lineItem.name          = "Video line item - " + this.GetTimeStamp();
                lineItem.orderId       = orderId;
                lineItem.targeting     = targeting;
                lineItem.lineItemType  = LineItemType.SPONSORSHIP;
                lineItem.allowOverbook = true;

                // Set the environment type to video.
                lineItem.environmentType = EnvironmentType.VIDEO_PLAYER;

                // Set the creative rotation type to optimized.
                lineItem.creativeRotationType = CreativeRotationType.OPTIMIZED;

                // Create the master creative placeholder.
                CreativePlaceholder creativeMasterPlaceholder = new CreativePlaceholder();
                Size size1 = new Size();
                size1.width                    = 400;
                size1.height                   = 300;
                size1.isAspectRatio            = false;
                creativeMasterPlaceholder.size = size1;

                // Create companion creative placeholders.
                CreativePlaceholder companionCreativePlaceholder1 = new CreativePlaceholder();
                Size size2 = new Size();
                size2.width         = 300;
                size2.height        = 250;
                size2.isAspectRatio = false;
                companionCreativePlaceholder1.size = size2;

                CreativePlaceholder companionCreativePlaceholder2 = new CreativePlaceholder();
                Size size3 = new Size();
                size3.width         = 728;
                size3.height        = 90;
                size3.isAspectRatio = false;
                companionCreativePlaceholder2.size = size3;

                // Set companion creative placeholders.
                creativeMasterPlaceholder.companions = new CreativePlaceholder[] {
                    companionCreativePlaceholder1, companionCreativePlaceholder2
                };

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

                // Set delivery of video companions to optional.
                lineItem.companionDeliveryOption = CompanionDeliveryOption.OPTIONAL;

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

                // Set the cost per day to $1.
                lineItem.costType = CostType.CPD;
                Money money = new Money();
                money.currencyCode   = "USD";
                money.microAmount    = 1000000L;
                lineItem.costPerUnit = money;

                // Set the percentage to be 100%.
                Goal goal = new Goal();
                goal.goalType        = GoalType.DAILY;
                goal.unitType        = UnitType.IMPRESSIONS;
                goal.units           = 100;
                lineItem.primaryGoal = goal;

                try {
                    // Create the line item on the server.
                    LineItem[] createdLineItems = lineItemService.createLineItems(
                        new LineItem[] { lineItem });

                    foreach (LineItem createdLineItem in createdLineItems)
                    {
                        Console.WriteLine("A line item with ID \"{0}\", belonging to order ID \"{1}\", and " +
                                          "named \"{2}\" was created.", createdLineItem.id, createdLineItem.orderId,
                                          createdLineItem.name);
                    }
                } catch (Exception e) {
                    Console.WriteLine("Failed to create line items. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Beispiel #18
0
        public LineItem CreateLineItem(DfpUser user, long orderId, string adUnitId)
        {
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201511.LineItemService);

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

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

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

            // Create geographical targeting.
            GeoTargeting geoTargeting = new GeoTargeting();

            // Include the US and Quebec, Canada.
            Location countryLocation = new Location();

            countryLocation.id = 2840L;

            Location regionLocation = new Location();

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

            // Exclude Chicago and the New York metro area.
            Location cityLocation = new Location();

            cityLocation.id = 1016367L;

            Location metroLocation = new Location();

            metroLocation.id = 200501L;
            geoTargeting.excludedLocations = new Location[] { cityLocation, metroLocation };

            // Exclude domains that are not under the network's control.
            UserDomainTargeting userDomainTargeting = new UserDomainTargeting();

            userDomainTargeting.domains  = new String[] { "usa.gov" };
            userDomainTargeting.targeted = false;

            // Create day-part targeting.
            DayPartTargeting dayPartTargeting = new DayPartTargeting();

            dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER;

            // Target only the weekend in the browser's timezone.
            DayPart saturdayDayPart = new DayPart();

            saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201511.DayOfWeek.SATURDAY;

            saturdayDayPart.startTime        = new TimeOfDay();
            saturdayDayPart.startTime.hour   = 0;
            saturdayDayPart.startTime.minute = MinuteOfHour.ZERO;

            saturdayDayPart.endTime        = new TimeOfDay();
            saturdayDayPart.endTime.hour   = 24;
            saturdayDayPart.endTime.minute = MinuteOfHour.ZERO;

            DayPart sundayDayPart = new DayPart();

            sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201511.DayOfWeek.SUNDAY;

            sundayDayPart.startTime        = new TimeOfDay();
            sundayDayPart.startTime.hour   = 0;
            sundayDayPart.startTime.minute = MinuteOfHour.ZERO;

            sundayDayPart.endTime        = new TimeOfDay();
            sundayDayPart.endTime.hour   = 24;
            sundayDayPart.endTime.minute = MinuteOfHour.ZERO;

            dayPartTargeting.dayParts = new DayPart[] { saturdayDayPart, sundayDayPart };


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

            // Create browser targeting.
            BrowserTargeting browserTargeting = new BrowserTargeting();

            browserTargeting.isTargeted = true;

            // Target just the Chrome browser.
            Technology browserTechnology = new Technology();

            browserTechnology.id                 = 500072L;
            browserTargeting.browsers            = new Technology[] { browserTechnology };
            technologyTargeting.browserTargeting = browserTargeting;

            LineItem lineItem = new LineItem();

            lineItem.name      = "Line item #" + new TestUtils().GetTimeStamp();
            lineItem.orderId   = orderId;
            lineItem.targeting = new Targeting();

            lineItem.targeting.inventoryTargeting  = inventoryTargeting;
            lineItem.targeting.geoTargeting        = geoTargeting;
            lineItem.targeting.userDomainTargeting = userDomainTargeting;
            lineItem.targeting.dayPartTargeting    = dayPartTargeting;
            lineItem.targeting.technologyTargeting = technologyTargeting;

            lineItem.lineItemType  = LineItemType.STANDARD;
            lineItem.allowOverbook = true;

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

            // Set the size of creatives that can be associated with this line item.
            Size size = new Size();

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

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

            creativePlaceholder.size = size;

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

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

            // Set the cost per unit to $2.
            lineItem.costType    = CostType.CPM;
            lineItem.costPerUnit = new Money();
            lineItem.costPerUnit.currencyCode = "USD";
            lineItem.costPerUnit.microAmount  = 2000000L;

            // Set the number of units bought to 500,000 so that the budget is
            // $1,000.
            Goal goal = new Goal();

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

            return(lineItemService.createLineItems(new LineItem[] { lineItem })[0]);
        }
Beispiel #19
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the OrderService.
            OrderService orderService =
                (OrderService)user.GetService(DfpService.v201608.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);
            }
        }
Beispiel #20
0
 public User GetCurrentUser(DfpUser user)
 {
     return(GetUserByEmail(user, new DfpAppConfig().Email));
 }
        /// <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 InventoryService.
            InventoryService inventoryService =
                (InventoryService)user.GetService(DfpService.v201403.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 && page.results.Length > 0)
                    {
                        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 ex) {
                Console.WriteLine("Failed to deactivate ad units. Exception says \"{0}\"", ex.Message);
            }
        }
Beispiel #22
0
 public User GetTrafficker(DfpUser user)
 {
     return(GetUserByEmail(user, "*****@*****.**"));
 }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (WorkflowRequestService workflowRequestService =
                       (WorkflowRequestService)user.GetService(DfpService.v201711.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.v201711.ApproveWorkflowApprovalRequests action =
                            new Google.Api.Ads.Dfp.v201711.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);
                }
            }
        }
Beispiel #24
0
 public User GetSalesperson(DfpUser user)
 {
     return(GetUserByEmail(user, "*****@*****.**"));
 }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (LineItemService lineItemService =
                       (LineItemService)user.GetService(DfpService.v201711.LineItemService))
                using (ReportService reportService =
                           (ReportService)user.GetService(DfpService.v201711.ReportService)) {
                    try {
                        // Set the ID of the order to get line items from.
                        long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

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

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

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


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

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

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


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

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

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

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

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

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

                        // Download the report.
                        using (ReportResponse reportResponse = reportUtilities.GetResponse()) {
                            reportResponse.Save(filePath);
                        }
                        Console.WriteLine("Report saved to \"{0}\".", filePath);
                    } catch (Exception e) {
                        Console.WriteLine("Failed to run cusom fields report. Exception says \"{0}\"",
                                          e.Message);
                    }
                }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public void Run(DfpUser user)
        {
            // Get the LineItemCreativeAssociationService.
            LineItemCreativeAssociationService licaService = (LineItemCreativeAssociationService)
                                                             user.GetService(DfpService.v201608.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>
        /// <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.v201502.AudienceSegmentService);

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

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

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

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

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

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

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

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

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

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

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

                foreach (AudienceSegment createdAudienceSegment in audienceSegments)
                {
                    Console.WriteLine("An audience segment with ID \"{0}\", name \"{1}\", and type \"{2}\" " +
                                      "was created.", createdAudienceSegment.id, createdAudienceSegment.name,
                                      createdAudienceSegment.type);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to get audience segment. Exception says \"{0}\"", e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user, long proposalId)
        {
            // Get the ProposalService.
            ProposalService proposalService =
                (ProposalService)user.GetService(DfpService.v201708.ProposalService);

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

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

            try {
                do
                {
                    // Get proposals by statement.
                    page = proposalService.getProposalsByStatement(statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        foreach (Proposal proposal in page.results)
                        {
                            Console.WriteLine("{0}) Proposal with ID = '{1}', name = '{2}', and status ='{3}' " +
                                              "will be sent to Marketplace for buyer acceptance.",
                                              i++,
                                              proposal.id,
                                              proposal.name,
                                              proposal.status);
                            proposalIds.Add(proposal.id.ToString());
                        }
                    }

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

                Console.WriteLine("Number of proposals to be sent to Marketplace: {0}", proposalIds.Count);

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

                    // Create action.
                    Google.Api.Ads.Dfp.v201708.RequestBuyerAcceptance action =
                        new Google.Api.Ads.Dfp.v201708.RequestBuyerAcceptance();

                    // Perform action.
                    UpdateResult result = proposalService.performProposalAction(action,
                                                                                statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of proposals that were sent to Marketplace: {0}",
                                          result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No proposals were sent to Marketplace.");
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to send proposals to Marketplace. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the ProductTemplateService.
            ProductTemplateService productTemplateService =
                (ProductTemplateService)user.GetService(DfpService.v201705.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.v201705.ActivateProductTemplates action =
                        new Google.Api.Ads.Dfp.v201705.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);
            }
        }
Beispiel #30
0
        /// <summary>
        /// Run the code examples.
        /// </summary>
        /// <param name="user">The DFP user object running the code examples.</param>
        public override void Run(DfpUser user)
        {
            // Get the LineItemService.
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201408.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.v201408.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.v201408.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 length of the line item to run.
                //lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
                lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
                lineItem.endDateTime       = DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1));

                // Set the cost per unit to $2.
                lineItem.costType    = CostType.CPM;
                lineItem.costPerUnit = new Money();
                lineItem.costPerUnit.currencyCode = "USD";
                lineItem.costPerUnit.microAmount  = 2000000L;

                // Set the number of units bought to 500,000 so that the budget is
                // $1,000.
                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 ex) {
                Console.WriteLine("Failed to create line items. Exception says \"{0}\"",
                                  ex.Message);
            }
        }