/// <summary> /// Run the code example. /// </summary> public void Run(DfpUser user) { // Get the ProductTemplateService. ProductTemplateService productTemplateService = (ProductTemplateService)user.GetService(DfpService.v201702.ProductTemplateService); // Set the ID of the product template to activate. long productTemplateId = long.Parse(_T("INSERT_PRODUCT_TEMPLATE_ID_HERE")); // [START product_template_statement] MOE:strip_line // 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); // [END product_template_statement] MOE:strip_line // 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(); // [START its_activation_time] MOE:strip_line // Create action. Google.Api.Ads.Dfp.v201702.ActivateProductTemplates action = new Google.Api.Ads.Dfp.v201702.ActivateProductTemplates(); // Perform action. UpdateResult result = productTemplateService.performProductTemplateAction(action, statementBuilder.ToStatement()); // [END its_activation_time] MOE:strip_line // 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); } }
/// <summary> /// Run the code example. /// </summary> public void Run(DfpUser user) { // Get the CustomFieldService. CustomFieldService customFieldService = (CustomFieldService)user.GetService( DfpService.v201602.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.v201602.DeactivateCustomFields action = new Google.Api.Ads.Dfp.v201602.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 e) { Console.WriteLine("Failed to deactivate custom fields. 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 ProductTemplateService. ProductTemplateService productTemplateService = (ProductTemplateService)user.GetService(DfpService.v201602.ProductTemplateService); // Set the ID of the product template. long productTemplateId = long.Parse(_T("INSERT_PRODUCT_TEMPLATE_ID_HERE")); // Create a statement to get the product template. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", productTemplateId); try { // Get product templates by statement. ProductTemplatePage page = productTemplateService .getProductTemplatesByStatement(statementBuilder.ToStatement()); ProductTemplate productTemplate = page.results[0]; // Add geo targeting for Canada to the product template. Location countryLocation = new Location(); countryLocation.id = 2124L; Targeting productTemplateTargeting = productTemplate.builtInTargeting; GeoTargeting geoTargeting = productTemplateTargeting.geoTargeting; List <Location> existingTargetedLocations = new List <Location>(); if (geoTargeting == null) { geoTargeting = new GeoTargeting(); } else if (geoTargeting.targetedLocations != null) { existingTargetedLocations = new List <Location>(geoTargeting.targetedLocations); } existingTargetedLocations.Add(countryLocation); Location[] newTargetedLocations = new Location[existingTargetedLocations.Count]; existingTargetedLocations.CopyTo(newTargetedLocations); geoTargeting.targetedLocations = newTargetedLocations; productTemplateTargeting.geoTargeting = geoTargeting; productTemplate.builtInTargeting = productTemplateTargeting; // Update the product template on the server. ProductTemplate[] productTemplates = productTemplateService .updateProductTemplates(new ProductTemplate[] { productTemplate }); if (productTemplates != null) { foreach (ProductTemplate updatedProductTemplate in productTemplates) { Console.WriteLine("A product template with ID = '{0}' and name '{1}' was updated.", updatedProductTemplate.id, updatedProductTemplate.name); } } else { Console.WriteLine("No product templates updated."); } } catch (Exception e) { Console.WriteLine("Failed to update product templates. Exception says \"{0}\"", e.Message); } }
/// <summary> /// Run the code example. /// </summary> /// <param name="user">The DFP user object running the code example.</param> public override void Run(DfpUser user) { // Get the UserService. UserService userService = (UserService)user.GetService(DfpService.v201508.UserService); // Set the ID of the user to deactivate long userId = long.Parse(_T("INSERT_USER_ID_HERE")); // Create statement text to select user by id. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :userId") .OrderBy("id ASC") .Limit(1) .AddValue("userId", userId); // Sets default for page. UserPage page = new UserPage(); List <string> userIds = new List <string>(); try { do { // Get users by statement. page = userService.getUsersByStatement(statementBuilder.ToStatement()); if (page.results != null && page.results.Length > 0) { int i = page.startIndex; foreach (User userResult in page.results) { Console.WriteLine("{0}) User with ID = '{1}', email = '{2}', and status = '{3}'" + " will be deactivated.", i, userResult.id, userResult.email, userResult.isActive ? "ACTIVE" : "INACTIVE"); userIds.Add(userResult.id.ToString()); i++; } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of users to be deactivated: {0}", page.totalResultSetSize); if (userIds.Count > 0) { // Modify statement for action. statementBuilder.RemoveLimitAndOffset(); // Create action. DeactivateUsers action = new DeactivateUsers(); // Perform action. UpdateResult result = userService.performUserAction(action, statementBuilder.ToStatement()); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of users deactivated: {0}" + result.numChanges); } else { Console.WriteLine("No users were deactivated."); } } } catch (Exception e) { Console.WriteLine("Failed to deactivate users. Exception says \"{0}\"", e.Message); } }
/// <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.v201505.InventoryService); // Get the PlacementService. PlacementService placementService = (PlacementService)user.GetService(DfpService.v201505.PlacementService); // Create local placement object to store skyscraper ad units. Placement skyscraperAdUnitPlacement = new Placement(); skyscraperAdUnitPlacement.name = string.Format("Skyscraper AdUnit Placement #{0}", this.GetTimeStamp()); skyscraperAdUnitPlacement.description = "Contains ad units that can hold creatives " + "of size 120x600"; // Create local placement object to store medium square ad units. Placement mediumSquareAdUnitPlacement = new Placement(); mediumSquareAdUnitPlacement.name = string.Format("Medium Square AdUnit Placement #{0}", this.GetTimeStamp()); mediumSquareAdUnitPlacement.description = "Contains ad units that can hold creatives " + "of size 300x250"; // Create local placement object to store banner ad units. Placement bannerAdUnitPlacement = new Placement(); bannerAdUnitPlacement.name = string.Format("Banner AdUnit Placement #{0}", this.GetTimeStamp()); bannerAdUnitPlacement.description = "Contains ad units that can hold creatives " + "of size 468x60"; List <Placement> placementList = new List <Placement>(); // Get the first 500 ad units. StatementBuilder statementBuilder = new StatementBuilder() .OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); List <string> mediumSquareTargetedUnitIds = new List <string>(); List <string> skyscraperTargetedUnitIds = new List <string>(); List <string> bannerTargetedUnitIds = new List <string>(); try { AdUnitPage page = inventoryService.getAdUnitsByStatement(statementBuilder.ToStatement()); // Separate the ad units by size. if (page.results != null) { foreach (AdUnit adUnit in page.results) { if (adUnit.parentId != null && adUnit.adUnitSizes != null) { foreach (AdUnitSize adUnitSize in adUnit.adUnitSizes) { Size size = adUnitSize.size; if (size.width == 300 && size.height == 250) { if (!mediumSquareTargetedUnitIds.Contains(adUnit.id)) { mediumSquareTargetedUnitIds.Add(adUnit.id); } } else if (size.width == 120 && size.height == 600) { if (!skyscraperTargetedUnitIds.Contains(adUnit.id)) { skyscraperTargetedUnitIds.Add(adUnit.id); } } else if (size.width == 468 && size.height == 60) { if (!bannerTargetedUnitIds.Contains(adUnit.id)) { bannerTargetedUnitIds.Add(adUnit.id); } } } } } } mediumSquareAdUnitPlacement.targetedAdUnitIds = mediumSquareTargetedUnitIds.ToArray(); skyscraperAdUnitPlacement.targetedAdUnitIds = skyscraperTargetedUnitIds.ToArray(); bannerAdUnitPlacement.targetedAdUnitIds = bannerTargetedUnitIds.ToArray(); // Only create placements with one or more ad unit. if (mediumSquareAdUnitPlacement.targetedAdUnitIds.Length != 0) { placementList.Add(mediumSquareAdUnitPlacement); } if (skyscraperAdUnitPlacement.targetedAdUnitIds.Length != 0) { placementList.Add(skyscraperAdUnitPlacement); } if (bannerAdUnitPlacement.targetedAdUnitIds.Length != 0) { placementList.Add(bannerAdUnitPlacement); } Placement[] placements = placementService.createPlacements(placementList.ToArray()); // Display results. if (placements != null) { foreach (Placement placement in placements) { Console.Write("A placement with ID = '{0}', name ='{1}', and containing " + "ad units {{", placement.id, placement.name); foreach (string adUnitId in placement.targetedAdUnitIds) { Console.Write("{0}, ", adUnitId); } Console.WriteLine("} was created."); } } else { Console.WriteLine("No placements created."); } } catch (Exception e) { Console.WriteLine("Failed to create placements. Exception says \"{0}\"", e.Message); } }
/// <summary> /// Run the code example. /// </summary> /// <param name="user">The DFP user object running the code example.</param> public override void Run(DfpUser user) { // Get the LabelService. LabelService labelService = (LabelService)user.GetService(DfpService.v201508.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(AdManagerUser user) { using (PublisherQueryLanguageService pqlService = user.GetService <PublisherQueryLanguageService>()) { // Create statement to select recent changes. Change_History only supports ordering // by descending ChangeDateTime. Offset is not supported. To page, use the change ID // of the earliest change as a pagination token. A date time range is required when // querying this table. System.DateTime endDateTime = System.DateTime.Now; System.DateTime startDateTime = endDateTime.AddDays(-1); StatementBuilder statementBuilder = new StatementBuilder() .Select("Id, ChangeDateTime, EntityId, EntityType, Operation, UserId") .From("Change_History") .Where("ChangeDateTime < :endDateTime AND ChangeDateTime > :startDateTime") .OrderBy("ChangeDateTime DESC") .AddValue("startDateTime", DateTimeUtilities.FromDateTime(startDateTime, "America/New_York")) .AddValue("endDateTime", DateTimeUtilities.FromDateTime(endDateTime, "America/New_York")) .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); int resultSetSize = 0; List <Row> allRows = new List <Row>(); ResultSet resultSet; do { resultSet = pqlService.select(statementBuilder.ToStatement()); if (resultSet.rows != null && resultSet.rows.Length > 0) { // Get the earliest change ID in the result set. Row lastRow = resultSet.rows[resultSet.rows.Length - 1]; string lastId = (string)PqlUtilities.GetValue(lastRow.values[0]); // Collect all changes from each page. allRows.AddRange(resultSet.rows); // Display results. Console.WriteLine(PqlUtilities.ResultSetToString(resultSet)); // Use the earliest change ID in the result set to page. statementBuilder .Where("Id < :id AND ChangeDateTime < :endDateTime AND " + "ChangeDateTime > :startDateTime").AddValue("id", lastId); } resultSetSize = resultSet.rows == null ? 0 : resultSet.rows.Length; } while (resultSetSize == StatementBuilder.SUGGESTED_PAGE_LIMIT); Console.WriteLine("Number of results found: " + allRows.Count); // Optionally, save all rows to a CSV. // Get a string array representation of the data rows. resultSet.rows = allRows.ToArray(); List <String[]> rows = PqlUtilities.ResultSetToStringArrayList(resultSet); // Write the contents to a csv file. CsvFile file = new CsvFile(); file.Headers.AddRange(rows[0]); file.Records.AddRange(rows.GetRange(1, rows.Count - 1).ToArray()); file.Write("recent_changes_" + this.GetTimeStamp() + ".csv"); } }
/// <summary> /// Run the code example. /// </summary> public void Run(DfpUser user) { ReportService reportService = (ReportService)user.GetService( DfpService.v201602.ReportService); // Get the NetworkService. NetworkService networkService = (NetworkService)user.GetService( DfpService.v201602.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, long productId) { // Get the ProductService. ProductService productService = (ProductService)user.GetService(DfpService.v201611.ProductService); // Create statement to select a product template by ID. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .AddValue("id", productId); // Set default for page. ProductPage page = new ProductPage(); List <long> productIds = new List <long>(); try { do { // Get products by statement. page = productService.getProductsByStatement( statementBuilder.ToStatement()); if (page.results != null) { int i = page.startIndex; foreach (Product product in page.results) { Console.WriteLine("{0}) Product with ID ='{1}' will be published.", i++, product.id); productIds.Add(product.id); } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of products to be published: {0}", productIds.Count); if (productIds.Count > 0) { // Modify statement. statementBuilder.RemoveLimitAndOffset(); // Create action. Google.Api.Ads.Dfp.v201611.PublishProducts action = new Google.Api.Ads.Dfp.v201611.PublishProducts(); // Perform action. UpdateResult result = productService.performProductAction(action, statementBuilder.ToStatement()); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of products published: {0}", result.numChanges); } else { Console.WriteLine("No products were published."); } } } catch (Exception e) { Console.WriteLine("Failed to publish products. Exception says \"{0}\"", e.Message); } }
/// <summary> /// Run the code example. /// </summary> public void Run(DfpUser user) { ReportService reportService = (ReportService)user.GetService( DfpService.v201705.ReportService); // Set the file path where the report will be saved. String filePath = _T("INSERT_FILE_PATH_HERE"); long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE")); // [START report_guide_include_1] MOE:strip_line // Create report job. ReportJob reportJob = new ReportJob(); reportJob.reportQuery = new ReportQuery(); reportJob.reportQuery.dimensions = new Dimension[] { Dimension.ORDER_ID, Dimension.ORDER_NAME }; reportJob.reportQuery.dimensionAttributes = new DimensionAttribute[] { DimensionAttribute.ORDER_TRAFFICKER, DimensionAttribute.ORDER_START_DATE_TIME, DimensionAttribute.ORDER_END_DATE_TIME }; reportJob.reportQuery.columns = new Column[] { Column.AD_SERVER_IMPRESSIONS, Column.AD_SERVER_CLICKS, Column.AD_SERVER_CTR, Column.AD_SERVER_CPM_AND_CPC_REVENUE, Column.AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM }; // Set a custom date range for the last 8 days reportJob.reportQuery.dateRangeType = DateRangeType.CUSTOM_DATE; System.DateTime endDateTime = System.DateTime.Now; reportJob.reportQuery.startDate = DateTimeUtilities.FromDateTime(endDateTime.AddDays(-8), "America/New_York").date; reportJob.reportQuery.endDate = DateTimeUtilities.FromDateTime(endDateTime, "America/New_York").date; // Create statement object to filter for an order. StatementBuilder statementBuilder = new StatementBuilder() .Where("ORDER_ID = :id") .AddValue("id", orderId); reportJob.reportQuery.statement = statementBuilder.ToStatement(); // [END report_guide_include_1] MOE:strip_line try { // [START report_guide_include_2] MOE:strip_line // Run report job. reportJob = reportService.runReportJob(reportJob); // [END report_guide_include_2] MOE:strip_line // [START report_guide_include_3] MOE:strip_line ReportUtilities reportUtilities = new ReportUtilities(reportService, reportJob.id); // Set download options. ReportDownloadOptions options = new ReportDownloadOptions(); options.exportFormat = ExportFormat.CSV_DUMP; options.useGzipCompression = true; reportUtilities.reportDownloadOptions = options; // Download the report. using (ReportResponse reportResponse = reportUtilities.GetResponse()) { reportResponse.Save(filePath); } Console.WriteLine("Report saved to \"{0}\".", filePath); // [END report_guide_include_3] MOE:strip_line } catch (Exception e) { Console.WriteLine("Failed to run delivery report. Exception says \"{0}\"", e.Message); } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (BaseRateService baseRateService = user.GetService <BaseRateService>()) { long baseRateId = long.Parse(_T("INSERT_BASE_RATE_ID_HERE")); // Create a statement to get the baseRate. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", baseRateId); try { // Get base rates by statement. BaseRatePage page = baseRateService.getBaseRatesByStatement(statementBuilder.ToStatement()); BaseRate baseRate = page.results[0]; // Update base rate value to $3 USD. Money newRate = new Money() { currencyCode = "USD", microAmount = 3000000L }; if (baseRate is ProductTemplateBaseRate) { ((ProductTemplateBaseRate)baseRate).rate = newRate; } else if (baseRate is ProductBaseRate) { ((ProductBaseRate)baseRate).rate = newRate; } // Update the base rates on the server. BaseRate[] baseRates = baseRateService.updateBaseRates(new BaseRate[] { baseRate }); if (baseRates != null) { foreach (BaseRate updatedBaseRate in baseRates) { Console.WriteLine( "Base rate with ID ='{0}' and type '{1}' belonging to rate card " + "'{2}' was updated.", baseRate.id, baseRate.GetType().Name, baseRate.rateCardId); } } else { Console.WriteLine("No base rates updated."); } } catch (Exception e) { Console.WriteLine("Failed to update base rates. 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, long proposalId) { // Get the ProposalService. ProposalService proposalService = (ProposalService)user.GetService(DfpService.v201608.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.v201608.RequestBuyerAcceptance action = new Google.Api.Ads.Dfp.v201608.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); } }
private void ProcessTokenSpan(SnapshotSpan tokenSpan, TokenBuilder tokenBuilder, StatementBuilder statementBuilder) { var tokenTags = ProcessToken(tokenSpan); tokenBuilder.Position += tokenTags.Consumed; // Track preprocessors, but don't process them in our statements if (tokenTags.ClassifierTagSpan != null && tokenTags.ClassifierTagSpan.Tag.TokenType.IsPreprocessor()) { var preprocessorTagSpan = new TagSpan <IGLSLTag>(tokenTags.ClassifierTagSpan.Span, tokenTags.ClassifierTagSpan.Tag); _statements.Append(preprocessorTagSpan); } else { var token = tokenSpan.GetText(); statementBuilder.AppendTokenTags(tokenTags); // Process the statement once we encounter either a ';' or '{' character if ((tokenTags.ClassifierTagSpan != null && tokenTags.ClassifierTagSpan.Tag.TokenType == GLSLTokenTypes.Semicolon) || token == "{") { var statement = statementBuilder.ProcessStatement(_bracketTagger, _functionTagger, _variableTagger); _statements.Append(statement); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (InventoryService inventoryService = user.GetService <InventoryService>()) { // Set the ID of the ad unit to deactivate. int adUnitId = int.Parse(_T("INSERT_AD_UNIT_ID_HERE")); // Create a statement to select the ad unit. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", adUnitId); // Set default for page. AdUnitPage page = new AdUnitPage(); List <string> adUnitIds = new List <string>(); try { do { // Get ad units by statement. page = inventoryService.getAdUnitsByStatement( statementBuilder.ToStatement()); if (page.results != null) { int i = page.startIndex; foreach (AdUnit adUnit in page.results) { Console.WriteLine( "{0}) Ad unit with ID ='{1}', name = {2} and status = {3} " + "will be deactivated.", i, adUnit.id, adUnit.name, adUnit.status); adUnitIds.Add(adUnit.id); i++; } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of ad units to be deactivated: {0}", adUnitIds.Count); // Modify statement for action. statementBuilder.RemoveLimitAndOffset(); // Create action. DeactivateAdUnits action = new DeactivateAdUnits(); // Perform action. UpdateResult result = inventoryService.performAdUnitAction(action, statementBuilder.ToStatement()); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of ad units deactivated: {0}", result.numChanges); } else { Console.WriteLine("No ad units were deactivated."); } } catch (Exception e) { Console.WriteLine("Failed to deactivate ad units. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the sample code. /// </summary> public void Run(AdManagerUser user, long adUnitId) { using (InventoryService inventoryService = user.GetService <InventoryService>()) { // Create a statement to get the ad unit. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", adUnitId); try { // Get ad units by statement. AdUnitPage page = inventoryService.getAdUnitsByStatement(statementBuilder.ToStatement()); // Create a 480x60 web ad unit size. AdUnitSize adUnitSize = new AdUnitSize() { size = new Size() { width = 480, height = 60 }, environmentType = EnvironmentType.BROWSER }; AdUnit adUnit = page.results[0]; adUnit.adUnitSizes = new AdUnitSize[] { adUnitSize }; // Update the ad units on the server. AdUnit[] updatedAdUnits = inventoryService.updateAdUnits(new AdUnit[] { adUnit }); foreach (AdUnit updatedAdUnit in updatedAdUnits) { List <string> adUnitSizeStrings = new List <string>(); foreach (AdUnitSize size in updatedAdUnit.adUnitSizes) { adUnitSizeStrings.Add(size.fullDisplayString); } Console.WriteLine( "Ad unit with ID \"{0}\", name \"{1}\", and sizes [{2}] was " + "updated.", updatedAdUnit.id, updatedAdUnit.name, String.Join(",", adUnitSizeStrings)); } } catch (Exception e) { Console.WriteLine("Failed to update ad units. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> /// <param name="user">The DFP user object running the code example.</param> public override void Run(DfpUser user) { // Get the LineItemService. LineItemService lineItemService = (LineItemService)user.GetService(DfpService.v201311.LineItemService); // Set the ID of the order to get line items from. long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE")); // Create Statement text to select approved line items from a given order. string statementText = "WHERE orderId = :orderId and status = :status LIMIT 500"; Statement statement = new StatementBuilder("").AddValue("orderId", orderId). AddValue("status", ComputedStatus.NEEDS_CREATIVES.ToString()).ToStatement(); // Set defaults for page and offset. LineItemPage page = new LineItemPage(); int offset = 0; int i = 0; List <string> lineItemIds = new List <string>(); try { do { // Create a Statement to page through approved line items. statement.query = string.Format("{0} OFFSET {1}", statementText, offset); // Get line items by Statement. page = lineItemService.getLineItemsByStatement(statement); if (page.results != null && page.results.Length > 0) { foreach (LineItemSummary lineItem in page.results) { // Archived line items cannot be activated. if (!lineItem.isArchived) { Console.WriteLine("{0}) Line item with ID ='{1}', belonging to order ID ='{2}' " + "and name ='{2}' will be activated.", i, lineItem.id, lineItem.orderId, lineItem.name); lineItemIds.Add(lineItem.id.ToString()); i++; } } } offset += 500; } while (offset < page.totalResultSetSize); Console.WriteLine("Number of line items to be activated: {0}", lineItemIds.Count); if (lineItemIds.Count > 0) { // Create action Statement. statement = new StatementBuilder( string.Format("WHERE id IN ({0})", string.Join(",", lineItemIds.ToArray()))). ToStatement(); // Create action. ActivateLineItems action = new ActivateLineItems(); // Perform action. UpdateResult result = lineItemService.performLineItemAction(action, statement); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of line items activated: {0}", result.numChanges); } else { Console.WriteLine("No line items were activated."); } } } catch (Exception ex) { Console.WriteLine("Failed to activate line items. Exception says \"{0}\"", ex.Message); } }
/// <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 SuggestedAdUnitService. SuggestedAdUnitService suggestedAdUnitService = (SuggestedAdUnitService)user.GetService( DfpService.v201602.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.v201602.ApproveSuggestedAdUnits action = new Google.Api.Ads.Dfp.v201602.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(AdManagerUser user, long savedQueryId) { using (ReportService reportService = user.GetService <ReportService>()) { // Set the file path where the report will be saved. String filePath = _T("INSERT_FILE_PATH_HERE"); // Create statement to retrieve the saved query. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", savedQueryId); SavedQueryPage page = reportService.getSavedQueriesByStatement(statementBuilder.ToStatement()); SavedQuery savedQuery = page.results[0]; if (!savedQuery.isCompatibleWithApiVersion) { throw new InvalidOperationException("Saved query is not compatible with this " + "API version"); } // Optionally modify the query. ReportQuery reportQuery = savedQuery.reportQuery; reportQuery.adUnitView = ReportQueryAdUnitView.HIERARCHICAL; // Create a report job using the saved query. 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 saved query. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (UserTeamAssociationService userTeamAssociationService = user.GetService <UserTeamAssociationService>()) { // Set the user to remove from its teams. long userId = long.Parse(_T("INSERT_USER_ID_HERE")); // Create filter text to select user team associations by the user ID. StatementBuilder statementBuilder = new StatementBuilder() .Where("userId = :userId") .OrderBy("userId ASC, teamId ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .AddValue("userId", userId); // Set default for page. UserTeamAssociationPage page = new UserTeamAssociationPage(); try { do { // Get user team associations by statement. page = userTeamAssociationService.getUserTeamAssociationsByStatement( statementBuilder.ToStatement()); if (page.results != null) { int i = page.startIndex; foreach (UserTeamAssociation userTeamAssociation in page.results) { Console.WriteLine( "{0}) User team association between user with ID \"{1}\" and " + "team with ID \"{2}\" will be deleted.", i, userTeamAssociation.userId, userTeamAssociation.teamId); i++; } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of teams that the user will be removed from: " + page.totalResultSetSize); if (page.totalResultSetSize > 0) { // Modify statement for action. statementBuilder.RemoveLimitAndOffset(); // Create action. DeleteUserTeamAssociations action = new DeleteUserTeamAssociations(); // Perform action. UpdateResult result = userTeamAssociationService.performUserTeamAssociationAction(action, statementBuilder.ToStatement()); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of teams that the user was removed from: " + result.numChanges); } else { Console.WriteLine("No user team associations were deleted."); } } } catch (Exception e) { Console.WriteLine( "Failed to delete user team associations. 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 WorkflowRequestService. WorkflowRequestService workflowRequestService = (WorkflowRequestService)user.GetService(DfpService.v201605.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 && page.results.Length > 0) { 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.v201605.ApproveWorkflowApprovalRequests action = new Google.Api.Ads.Dfp.v201605.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); } }
/// <summary> /// Run the code example. /// </summary> public void Run(DfpUser user) { // Get the LineItemService. LineItemService lineItemService = (LineItemService)user.GetService(DfpService.v201608.LineItemService); // Set the ID of the order to get line items from. long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE")); // Create statement to select approved line items from a given order. StatementBuilder statementBuilder = new StatementBuilder() .Where("orderId = :orderId and status = :status") .AddValue("orderId", orderId) .AddValue("status", ComputedStatus.INACTIVE.ToString()); // Set default for page. LineItemPage page = new LineItemPage(); List <string> lineItemIds = new List <string>(); try { do { // Get line items by statement. page = lineItemService.getLineItemsByStatement(statementBuilder.ToStatement()); if (page.results != null) { int i = page.startIndex; foreach (LineItemSummary lineItem in page.results) { // Archived line items cannot be activated. if (!lineItem.isArchived) { Console.WriteLine("{0}) Line item with ID ='{1}', belonging to order ID ='{2}' " + "and name ='{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 e) { Console.WriteLine("Failed to activate line items. Exception says \"{0}\"", e.Message); } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (CustomFieldService customFieldService = user.GetService <CustomFieldService>()) { // Get the LineItemService. LineItemService lineItemService = user.GetService <LineItemService>(); // Set the IDs of the custom fields, custom field option, and line item. long customFieldId = long.Parse(_T("INSERT_STRING_CUSTOM_FIELD_ID_HERE")); long customFieldOptionId = long.Parse(_T("INSERT_CUSTOM_FIELD_OPTION_ID_HERE")); long lineItemId = long.Parse(_T("INSERT_LINE_ITEM_ID_HERE")); try { // Get the drop-down custom field id. long dropDownCustomFieldId = customFieldService .getCustomFieldOption(customFieldOptionId).customFieldId; StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", lineItemId); // Get the line item. LineItemPage lineItemPage = lineItemService.getLineItemsByStatement(statementBuilder.ToStatement()); LineItem lineItem = lineItemPage.results[0]; // Create custom field values. List <BaseCustomFieldValue> customFieldValues = new List <BaseCustomFieldValue>(); TextValue textValue = new TextValue(); textValue.value = "Custom field value"; CustomFieldValue customFieldValue = new CustomFieldValue(); customFieldValue.customFieldId = customFieldId; customFieldValue.value = textValue; customFieldValues.Add(customFieldValue); DropDownCustomFieldValue dropDownCustomFieldValue = new DropDownCustomFieldValue(); dropDownCustomFieldValue.customFieldId = dropDownCustomFieldId; dropDownCustomFieldValue.customFieldOptionId = customFieldOptionId; customFieldValues.Add(dropDownCustomFieldValue); // Only add existing custom field values for different custom fields than // the ones you are setting. if (lineItem.customFieldValues != null) { foreach (BaseCustomFieldValue oldCustomFieldValue in lineItem .customFieldValues) { if (!(oldCustomFieldValue.customFieldId == customFieldId) && !(oldCustomFieldValue.customFieldId == dropDownCustomFieldId)) { customFieldValues.Add(oldCustomFieldValue); } } } lineItem.customFieldValues = customFieldValues.ToArray(); // Update the line item on the server. LineItem[] lineItems = lineItemService.updateLineItems(new LineItem[] { lineItem }); if (lineItems != null) { foreach (LineItem updatedLineItem in lineItems) { List <String> customFieldValueStrings = new List <String>(); foreach (BaseCustomFieldValue baseCustomFieldValue in lineItem .customFieldValues) { if (baseCustomFieldValue is CustomFieldValue && ((CustomFieldValue)baseCustomFieldValue).value is TextValue) { customFieldValueStrings.Add("{ID: '" + baseCustomFieldValue.customFieldId + "', value: '" + ((TextValue)((CustomFieldValue)baseCustomFieldValue) .value).value + "'}"); } else if (baseCustomFieldValue is DropDownCustomFieldValue) { customFieldValueStrings.Add("{ID: '" + baseCustomFieldValue.customFieldId + "', custom field option ID: '" + ((DropDownCustomFieldValue)baseCustomFieldValue) .customFieldOptionId + "'}"); } } Console.WriteLine( "A line item with ID \"{0}\" set with custom field values " + "\"{1}\".", updatedLineItem.id, string.Join(", ", customFieldValueStrings.ToArray())); } } else { Console.WriteLine("No line items were updated."); } } catch (Exception e) { Console.WriteLine("Failed to update line items. Exception says \"{0}\"", e.Message); } } }
/// <summary> /// Run the code example. /// </summary> /// <param name="user">The DFP user object running the code example.</param> public override void Run(DfpUser user) { // Get the ContentService. ContentService contentService = (ContentService)user.GetService(DfpService.v201405.ContentService); // Get the NetworkService. NetworkService networkService = (NetworkService)user.GetService( DfpService.v201405.NetworkService); // Get the CustomTargetingService. CustomTargetingService customTargetingService = (CustomTargetingService)user.GetService( DfpService.v201405.CustomTargetingService); try { // Get content browse custom targeting key ID. long contentBrowseCustomTargetingKeyId = networkService.getCurrentNetwork().contentBrowseCustomTargetingKeyId; // Create a statement to select the categories matching the name comedy. Statement categoryFilterStatement = new StatementBuilder() .Where("customTargetingKeyId = :contentBrowseCustomTargetingKeyId " + " and name = :category") .OrderBy("id ASC") .Limit(1) .AddValue("contentBrowseCustomTargetingKeyId", contentBrowseCustomTargetingKeyId) .AddValue("category", "comedy") .ToStatement(); // Get categories matching the filter statement. CustomTargetingValuePage customTargetingValuePage = customTargetingService.getCustomTargetingValuesByStatement(categoryFilterStatement); if (customTargetingValuePage.results != null) { // Get the custom targeting value ID for the comedy category. long categoryCustomTargetingValueId = customTargetingValuePage.results[0].id; // Create a statement to get all active content. StatementBuilder statementBuilder = new StatementBuilder() .Where("status = :status") .OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .AddValue("status", "ACTIVE"); // Set defaults for page and filterStatement. ContentPage page = new ContentPage(); do { // Get content by statement. page = contentService.getContentByStatementAndCustomTargetingValue( statementBuilder.ToStatement(), categoryCustomTargetingValueId); if (page.results != null) { int i = page.startIndex; foreach (Content content in page.results) { Console.WriteLine("{0}) Content with ID \"{1}\", name \"{2}\", and status " + "\"{3}\" was found.", i, content.id, content.name, content.status); i++; } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of results found: " + page.totalResultSetSize); } } catch (Exception ex) { Console.WriteLine("Failed to get content by category. Exception says \"{0}\"", ex.Message); } }
/// <summary> /// Run the code example. /// </summary> public void Run(DfpUser user) { // Get the PlacementService. PlacementService placementService = (PlacementService)user.GetService(DfpService.v201608.PlacementService); // Create statement to select active placements. StatementBuilder statementBuilder = new StatementBuilder() .Where("status = :status") .OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .AddValue("status", InventoryStatus.ACTIVE.ToString()); // Sets default for page. PlacementPage page = new PlacementPage(); List <string> placementIds = new List <string>(); try { do { // Get placements by statement. page = placementService.getPlacementsByStatement(statementBuilder.ToStatement()); if (page.results != null) { int i = page.startIndex; foreach (Placement placement in page.results) { Console.WriteLine("{0}) Placement with ID ='{1}', name ='{2}', and status ='{3}'" + " will be deactivated.", i, placement.id, placement.name, placement.status); placementIds.Add(placement.id.ToString()); i++; } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of placements to be deactivated: {0}", placementIds.Count); if (placementIds.Count > 0) { // Modify statement for action. statementBuilder.RemoveLimitAndOffset(); // Create action. DeactivatePlacements action = new DeactivatePlacements(); // Perform action. UpdateResult result = placementService.performPlacementAction(action, statementBuilder.ToStatement()); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of placements deactivated: {0}", result.numChanges); } else { Console.WriteLine("No placements were deactivated."); } } } catch (Exception e) { Console.WriteLine("Failed to deactivate placements. Exception says \"{0}\"", e.Message); } }
/// <summary> /// Run the code example. /// </summary> /// <param name="user">The DFP user object running the code example.</param> public override void Run(DfpUser user) { // Get the CustomTargetingService. CustomTargetingService customTargetingService = (CustomTargetingService)user.GetService(DfpService.v201408.CustomTargetingService); // Create a statement to get all custom targeting keys. StatementBuilder keyStatementBuilder = new StatementBuilder() .OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); // Set default for page. CustomTargetingKeyPage keyPage = new CustomTargetingKeyPage(); try { do { // Get custom targeting keys by statement. keyPage = customTargetingService.getCustomTargetingKeysByStatement( keyStatementBuilder.ToStatement()); if (keyPage.results != null) { int i = keyPage.startIndex; foreach (CustomTargetingKey key in keyPage.results) { Console.WriteLine("{0}) Custom targeting key with ID \"{1}\", name \"{2}\", " + "display name \"{3}\", and type \"{4}\" was found.", i, key.id, key.name, key.displayName, key.type); // Create a statement to get all custom targeting values for a // custom targeting key (required) by its ID. StatementBuilder valueStatementBuilder = new StatementBuilder() .Where("customTargetingKeyId = :customTargetingKeyId") .OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .AddValue("customTargetingKeyId", key.id); // Set default for page. CustomTargetingValuePage valuePage = new CustomTargetingValuePage(); do { // Get custom targeting values by statement. valuePage = customTargetingService.getCustomTargetingValuesByStatement( valueStatementBuilder.ToStatement()); if (valuePage.results != null) { int j = valuePage.startIndex; foreach (CustomTargetingValue value in valuePage.results) { Console.WriteLine("\t{0}) Custom targeting value with ID \"{1}\", name " + "\"{2}\", and display name \"{3}\" was found.", j, value.id, value.name, value.displayName); j++; } } valueStatementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (valueStatementBuilder.GetOffset() < valuePage.totalResultSetSize); i++; } } keyStatementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (keyStatementBuilder.GetOffset() < keyPage.totalResultSetSize); Console.WriteLine("Number of results found: {0}", keyPage.totalResultSetSize); } catch (Exception ex) { Console.WriteLine("Failed to get custom targeting keys and the values. Exception " + "says \"{0}\"", ex.Message); } }
/// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (LineItemCreativeAssociationService licaService = user.GetService <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 ProposalLineItemService. ProposalLineItemService proposalLineItemService = (ProposalLineItemService)user.GetService(DfpService.v201502.ProposalLineItemService); // Set the ID of the proposal line item to archive. long proposalLineItemId = long.Parse(_T("INSERT_PROPOSAL_LINE_ITEM_ID_HERE")); // Create statement to select a proposal line item by ID. StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .AddValue("id", proposalLineItemId); // Set default for page. ProposalLineItemPage page = new ProposalLineItemPage(); List <string> proposalLineItemIds = new List <string>(); try { do { // Get proposal line items by statement. page = proposalLineItemService.getProposalLineItemsByStatement( statementBuilder.ToStatement()); if (page.results != null && page.results.Length > 0) { int i = page.startIndex; foreach (ProposalLineItem proposalLineItem in page.results) { Console.WriteLine("{0}) Proposal line item with ID ='{1}' will be archived.", i++, proposalLineItem.id); proposalLineItemIds.Add(proposalLineItem.id.ToString()); } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of proposal line items to be archived: {0}", proposalLineItemIds.Count); if (proposalLineItemIds.Count > 0) { // Modify statement. statementBuilder.RemoveLimitAndOffset(); // Create action. Google.Api.Ads.Dfp.v201502.ArchiveProposalLineItems action = new Google.Api.Ads.Dfp.v201502.ArchiveProposalLineItems(); // Perform action. UpdateResult result = proposalLineItemService.performProposalLineItemAction(action, statementBuilder.ToStatement()); // Display results. if (result != null && result.numChanges > 0) { Console.WriteLine("Number of proposal line items archived: {0}", result.numChanges); } else { Console.WriteLine("No proposal line items were archived."); } } } catch (Exception ex) { Console.WriteLine("Failed to archive proposal line items. Exception says \"{0}\"", ex.Message); } }