コード例 #1
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (ForecastService forecastService = user.GetService <ForecastService>())
                using (NetworkService networkService = user.GetService <NetworkService>())
                {
                    // 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"));

                    String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;

                    System.DateTime tomorrow = System.DateTime.Now.AddDays(1);

                    // Create prospective line item.
                    LineItem lineItem = new LineItem()
                    {
                        targeting = new Targeting()
                        {
                            inventoryTargeting = new InventoryTargeting()
                            {
                                targetedAdUnits = new AdUnitTargeting[] {
                                    new AdUnitTargeting()
                                    {
                                        adUnitId           = rootAdUnitId,
                                        includeDescendants = true
                                    }
                                }
                            }
                        },
                        creativePlaceholders = new CreativePlaceholder[] {
                            new CreativePlaceholder()
                            {
                                size = new Size()
                                {
                                    width  = 300,
                                    height = 250
                                }
                            }
                        },
                        lineItemType = LineItemType.SPONSORSHIP,
                        // Set the line item to run for 5 days.
                        startDateTime = DateTimeUtilities.FromDateTime(
                            tomorrow, "America/New_York"),
                        endDateTime = DateTimeUtilities.FromDateTime(
                            tomorrow.AddDays(5), "America/New_York"),
                        // Set the cost type to match the unit type.
                        costType    = CostType.CPM,
                        primaryGoal = new Goal()
                        {
                            goalType = GoalType.DAILY,
                            unitType = UnitType.IMPRESSIONS,
                            units    = 50L
                        }
                    };

                    try
                    {
                        // Get availability forecast.
                        AvailabilityForecastOptions options = new AvailabilityForecastOptions()
                        {
                            includeContendingLineItems = true,
                            // Targeting criteria breakdown can only be included if breakdowns
                            // are not speficied.
                            includeTargetingCriteriaBreakdown = false,
                            breakdown = new ForecastBreakdownOptions
                            {
                                timeWindows = new DateTime[] {
                                    lineItem.startDateTime,
                                    DateTimeUtilities.FromDateTime(tomorrow.AddDays(1),
                                                                   "America/New_York"),
                                    DateTimeUtilities.FromDateTime(tomorrow.AddDays(2),
                                                                   "America/New_York"),
                                    DateTimeUtilities.FromDateTime(tomorrow.AddDays(3),
                                                                   "America/New_York"),
                                    DateTimeUtilities.FromDateTime(tomorrow.AddDays(4),
                                                                   "America/New_York"),
                                    lineItem.endDateTime
                                },
                                targets = new ForecastBreakdownTarget[] {
                                    new ForecastBreakdownTarget()
                                    {
                                        // Optional name field to identify this breakdown
                                        // in the response.
                                        name      = "United States",
                                        targeting = new Targeting()
                                        {
                                            inventoryTargeting = new InventoryTargeting()
                                            {
                                                targetedAdUnits = new AdUnitTargeting[] {
                                                    new AdUnitTargeting()
                                                    {
                                                        adUnitId           = rootAdUnitId,
                                                        includeDescendants = true
                                                    }
                                                }
                                            },
                                            geoTargeting = new GeoTargeting()
                                            {
                                                targetedLocations = new Location[] {
                                                    new Location()
                                                    {
                                                        id = 2840L
                                                    }
                                                }
                                            }
                                        }
                                    }, new ForecastBreakdownTarget()
                                    {
                                        // Optional name field to identify this breakdown
                                        // in the response.
                                        name      = "Geneva",
                                        targeting = new Targeting()
                                        {
                                            inventoryTargeting = new InventoryTargeting()
                                            {
                                                targetedAdUnits = new AdUnitTargeting[] {
                                                    new AdUnitTargeting()
                                                    {
                                                        adUnitId           = rootAdUnitId,
                                                        includeDescendants = true
                                                    }
                                                }
                                            },
                                            geoTargeting = new GeoTargeting()
                                            {
                                                targetedLocations = new Location[] {
                                                    new Location()
                                                    {
                                                        id = 20133L
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        };
                        ProspectiveLineItem prospectiveLineItem = new ProspectiveLineItem()
                        {
                            advertiserId = advertiserId,
                            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($"{matched} {unitType} matched.");
                        Console.WriteLine($"{availablePercent}% {unitType} available.");

                        if (forecast.possibleUnitsSpecified)
                        {
                            double possiblePercent =
                                (double)(forecast.possibleUnits / (matched * 1.0)) * 100;
                            Console.WriteLine($"{possiblePercent}% {unitType} possible.");
                        }
                        var contendingLineItems =
                            forecast.contendingLineItems ?? new ContendingLineItem[] { };
                        Console.WriteLine($"{contendingLineItems.Length} contending line items.");

                        if (forecast.breakdowns != null)
                        {
                            foreach (ForecastBreakdown breakdown in forecast.breakdowns)
                            {
                                Console.WriteLine("Forecast breakdown for {0} to {1}",
                                                  DateTimeUtilities.ToString(breakdown.startTime, "yyyy-MM-dd"),
                                                  DateTimeUtilities.ToString(breakdown.endTime, "yyyy-MM-dd"));
                                foreach (ForecastBreakdownEntry entry in breakdown.breakdownEntries)
                                {
                                    Console.WriteLine($"\t{entry.name}");
                                    long breakdownMatched = entry.forecast.matched;
                                    Console.WriteLine($"\t\t{breakdownMatched} {unitType} matched.");
                                    if (breakdownMatched > 0)
                                    {
                                        long   breakdownAvailable        = entry.forecast.available;
                                        double breakdownAvailablePercent =
                                            (double)(breakdownAvailable / (breakdownMatched * 1.0)) * 100;
                                        Console.WriteLine(
                                            $"\t\t{breakdownAvailablePercent}% {unitType} available");
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Failed to get forecast. Exception says \"{0}\"", e.Message);
                    }
                }
        }
コード例 #2
0
        /// <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);
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (ActivityGroupService activityGroupService =
                       user.GetService <ActivityGroupService>())
            {
                // Set the ID of the advertiser company this activity group is associated
                // with.
                long advertiserCompanyId = long.Parse(_T("INSERT_ADVERTISER_COMPANY_ID_HERE"));

                // Create a short-term activity group.
                ActivityGroup shortTermActivityGroup = new ActivityGroup();
                shortTermActivityGroup.name       = "Short-term activity group #" + GetTimeStamp();
                shortTermActivityGroup.companyIds = new long[]
                {
                    advertiserCompanyId
                };
                shortTermActivityGroup.clicksLookback      = 1;
                shortTermActivityGroup.impressionsLookback = 1;

                // Create a long-term activity group.
                ActivityGroup longTermActivityGroup = new ActivityGroup();
                longTermActivityGroup.name       = "Long-term activity group #" + GetTimeStamp();
                longTermActivityGroup.companyIds = new long[]
                {
                    advertiserCompanyId
                };
                longTermActivityGroup.clicksLookback      = 30;
                longTermActivityGroup.impressionsLookback = 30;

                try
                {
                    // Create the activity groups on the server.
                    ActivityGroup[] activityGroups = activityGroupService.createActivityGroups(
                        new ActivityGroup[]
                    {
                        shortTermActivityGroup,
                        longTermActivityGroup
                    });

                    // Display results.
                    if (activityGroups != null)
                    {
                        foreach (ActivityGroup activityGroup in activityGroups)
                        {
                            Console.WriteLine(
                                "An activity group with ID \"{0}\" and name \"{1}\" was created.",
                                activityGroup.id, activityGroup.name);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No activity groups were created.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to create activity groups. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
コード例 #4
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (LabelService labelService = user.GetService <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);
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (SuggestedAdUnitService suggestedAdUnitService =
                       user.GetService <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.AdManager.v201902.ApproveSuggestedAdUnits action =
                        new Google.Api.Ads.AdManager.v201902.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);
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (AudienceSegmentService audienceSegmentService =
                       user.GetService <AudienceSegmentService>())
            {
                // Get the NetworkService.
                NetworkService networkService =
                    user.GetService <NetworkService>();

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

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

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

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

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

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

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

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

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

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

                    foreach (AudienceSegment createdAudienceSegment in audienceSegments)
                    {
                        Console.WriteLine(
                            "An audience segment with ID \"{0}\", name \"{1}\", and " +
                            "type \"{2}\" was created.", createdAudienceSegment.id,
                            createdAudienceSegment.name, createdAudienceSegment.type);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to get audience segment. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
コード例 #7
0
        /// <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);
                }
            }
        }
コード例 #8
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (ForecastService forecastService = user.GetService <ForecastService>())
                using (NetworkService networkService = user.GetService <NetworkService>())
                {
                    String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;

                    // Set the date range to include
                    System.DateTime startDate = System.DateTime.Today.AddDays(-7);
                    System.DateTime endDate   = System.DateTime.Today.AddDays(7);

                    TrafficDataRequest trafficDataRequest = new TrafficDataRequest()
                    {
                        requestedDateRange = new DateRange()
                        {
                            startDate =
                                DateTimeUtilities.FromDateTime(startDate, "America/New_York").date,
                            endDate = DateTimeUtilities.FromDateTime(endDate, "America/New_York").date
                        },
                        targeting = new Targeting()
                        {
                            inventoryTargeting = new InventoryTargeting()
                            {
                                targetedAdUnits = new AdUnitTargeting[] {
                                    new AdUnitTargeting()
                                    {
                                        adUnitId           = rootAdUnitId,
                                        includeDescendants = true
                                    }
                                }
                            }
                        }
                    };

                    try
                    {
                        TrafficDataResponse trafficData =
                            forecastService.getTrafficData(trafficDataRequest);

                        TimeSeries historicalTimeSeries = trafficData.historicalTimeSeries;
                        if (historicalTimeSeries != null)
                        {
                            Date historicalStartDate =
                                historicalTimeSeries.timeSeriesDateRange.startDate;
                            System.DateTime startDateTime = new System.DateTime(
                                historicalStartDate.year,
                                historicalStartDate.month,
                                historicalStartDate.day);
                            for (int i = 0; i < historicalTimeSeries.values.Length; i++)
                            {
                                Console.WriteLine("{0}: {1} historical ad opportunities",
                                                  startDateTime.AddDays(i).ToString("yyyy-MM-dd"),
                                                  historicalTimeSeries.values[i]);
                            }
                        }

                        TimeSeries forecastedTimeSeries = trafficData.forecastedTimeSeries;
                        if (forecastedTimeSeries != null)
                        {
                            Date forecastedStartDate =
                                forecastedTimeSeries.timeSeriesDateRange.startDate;
                            System.DateTime startDateTime = new System.DateTime(
                                forecastedStartDate.year,
                                forecastedStartDate.month,
                                forecastedStartDate.day);
                            for (int i = 0; i < forecastedTimeSeries.values.Length; i++)
                            {
                                Console.WriteLine("{0}: {1} forecasted ad opportunities",
                                                  startDateTime.AddDays(i).ToString("yyyy-MM-dd"),
                                                  forecastedTimeSeries.values[i]);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Failed to get traffic data. Exception says \"{0}\"",
                                          e.Message);
                    }
                }
        }
コード例 #9
0
        /// <summary>
        /// Run the code examples.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (ProductTemplateService productTemplateService =
                       user.GetService <ProductTemplateService>())

                using (NetworkService networkService = user.GetService <NetworkService>())
                {
                    // Create a product template.
                    ProductTemplate productTemplate = new ProductTemplate();
                    productTemplate.name        = "Product template #" + new Random().Next(int.MaxValue);
                    productTemplate.description = "This product template creates standard " +
                                                  "proposal line items targeting Chrome browsers with product segmentation " +
                                                  "on ad units and geo targeting.";

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

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

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

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

                    // Create the master creative placeholder.
                    CreativePlaceholder creativeMasterPlaceholder = new CreativePlaceholder();
                    creativeMasterPlaceholder.size = new Size()
                    {
                        width         = 728,
                        height        = 90,
                        isAspectRatio = false
                    };

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

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

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

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

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

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

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

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

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

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

                    TechnologyTargeting technologyTargeting = new TechnologyTargeting();
                    technologyTargeting.browserTargeting = browserTargeting;

                    Targeting productTemplateTargeting = new Targeting();
                    productTemplateTargeting.technologyTargeting = technologyTargeting;

                    productTemplate.builtInTargeting = productTemplateTargeting;

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

                    // Add inventory and geo targeting as product segmentation.
                    ProductSegmentation productSegmentation = new ProductSegmentation();
                    productSegmentation.adUnitSegments = new AdUnitTargeting[]
                    {
                        adUnitTargeting
                    };
                    productSegmentation.geoSegment = geoTargeting;

                    productTemplate.productSegmentation = productSegmentation;

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

                        foreach (ProductTemplate createdProductTemplate in productTemplates)
                        {
                            Console.WriteLine(
                                "A product template with ID \"{0}\" and name \"{1}\" was created.",
                                createdProductTemplate.id, createdProductTemplate.name);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(
                            "Failed to create product templates. Exception says \"{0}\"",
                            e.Message);
                    }
                }
        }
コード例 #10
0
        /// <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);
                }
            }
        }
コード例 #11
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (UserService userService = user.GetService <UserService>())
            {
                // Set the ID of the user to deactivate
                long userId = long.Parse(_T("INSERT_USER_ID_HERE"));

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

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

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

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

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

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

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

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

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

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine(
                                "Number of users deactivated: {0}" + result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No users were deactivated.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to deactivate users. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
コード例 #12
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (CreativeService creativeService = user.GetService <CreativeService>())
            {
                long creativeId = long.Parse(_T("INSERT_IMAGE_CREATIVE_ID_HERE"));

                // Create a statement to get the image creative.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :id")
                                                    .OrderBy("id ASC")
                                                    .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                    .AddValue("id", creativeId);

                try
                {
                    // Get the creative.
                    CreativePage page =
                        creativeService.getCreativesByStatement(statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        ImageCreative imageCreative = (ImageCreative)page.results[0];
                        // Since we cannot set id to null, we mark it as not specified.
                        imageCreative.idSpecified = false;

                        imageCreative.advertiserId = imageCreative.advertiserId;
                        imageCreative.name         = imageCreative.name + " (Copy #" + GetTimeStamp() + ")";

                        // Create image asset.
                        CreativeAsset creativeAsset = new CreativeAsset();
                        creativeAsset.fileName       = "image.jpg";
                        creativeAsset.assetByteArray =
                            MediaUtilities.GetAssetDataFromUrl(
                                imageCreative.primaryImageAsset.assetUrl, user.Config);

                        creativeAsset.size = imageCreative.primaryImageAsset.size;
                        imageCreative.primaryImageAsset = creativeAsset;

                        // Create the copied creative.
                        Creative[] creatives = creativeService.createCreatives(new Creative[]
                        {
                            imageCreative
                        });

                        // Display copied creatives.
                        foreach (Creative copiedCreative in creatives)
                        {
                            Console.WriteLine(
                                "Image creative with ID \"{0}\", name \"{1}\", and type \"{2}\" " +
                                "was created and can be previewed at {3}", copiedCreative.id,
                                copiedCreative.name, copiedCreative.GetType().Name,
                                copiedCreative.previewUrl);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No creatives were copied.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to copy creatives. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
コード例 #13
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (PlacementService placementService = user.GetService <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);
                }
            }
        }
コード例 #14
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (CreativeService creativeService = user.GetService <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("https://goo.gl/3b9Wfh", user.Config);
                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);
                }
            }
        }
コード例 #15
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (LineItemService lineItemService = user.GetService <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);
                }
            }
        }
コード例 #16
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (CdnConfigurationService cdnConfigurationService =
                       user.GetService <CdnConfigurationService>())
            {
                // Make CND configuration objects.
                // Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API.
                // Basic example with no security policies.
                SecurityPolicySettings noSecurityPolicy = new SecurityPolicySettings()
                {
                    securityPolicyType = SecurityPolicyType.NONE
                };
                CdnConfiguration cdnConfigurationWithoutSecurityPolicy = new CdnConfiguration()
                {
                    name = "ApiConfig1",
                    cdnConfigurationType       = CdnConfigurationType.LIVE_STREAM_SOURCE_CONTENT,
                    sourceContentConfiguration = new SourceContentConfiguration()
                    {
                        ingestSettings = new MediaLocationSettings()
                        {
                            urlPrefix      = "example.google.com",
                            securityPolicy = noSecurityPolicy
                        },
                        defaultDeliverySettings = new MediaLocationSettings()
                        {
                            urlPrefix      = "example.google.com",
                            securityPolicy = noSecurityPolicy
                        }
                    }
                };

                // Complex example with security policies.
                CdnConfiguration cdnConfigurationWithSecurityPolicy = new CdnConfiguration()
                {
                    name = "ApiConfig2",
                    cdnConfigurationType       = CdnConfigurationType.LIVE_STREAM_SOURCE_CONTENT,
                    sourceContentConfiguration = new SourceContentConfiguration()
                    {
                        ingestSettings = new MediaLocationSettings()
                        {
                            urlPrefix      = "example.google.com",
                            securityPolicy = new SecurityPolicySettings()
                            {
                                securityPolicyType          = SecurityPolicyType.AKAMAI,
                                disableServerSideUrlSigning = false,
                                tokenAuthenticationKey      = "abc123"
                            }
                        },
                        defaultDeliverySettings = new MediaLocationSettings()
                        {
                            urlPrefix      = "example.google.com",
                            securityPolicy = new SecurityPolicySettings()
                            {
                                securityPolicyType          = SecurityPolicyType.AKAMAI,
                                disableServerSideUrlSigning = false,
                                originForwardingType        = OriginForwardingType.CONVENTIONAL,
                                originPathPrefix            = "/path/to/my/origin"
                            }
                        }
                    }
                };

                try
                {
                    // Create the CDN configurations on the server.
                    CdnConfiguration[] cdnConfigurations =
                        cdnConfigurationService.createCdnConfigurations(new CdnConfiguration[]
                    {
                        cdnConfigurationWithoutSecurityPolicy,
                        cdnConfigurationWithSecurityPolicy
                    });

                    foreach (CdnConfiguration createdCdnConfiguration in cdnConfigurations)
                    {
                        Console.WriteLine(
                            "A CDN configuration with ID \"{0}\" and name \"{1}\" was created.",
                            createdCdnConfiguration.id, createdCdnConfiguration.name);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to create company. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
コード例 #17
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (NativeStyleService nativeStyleService = user.GetService <NativeStyleService>())
            {
                // This value is typically loaded from a file or other resource.
                string htmlSnippet = @"<div id=""adunit"" style=""overflow: hidden;"">
  <img src=""[%Thirdpartyimpressiontracker%]"" style=""display:none"">
  <div class=""attribution"">Ad</div>
  <div class=""image"">
    <a class=""image-link""
        href=""%%CLICK_URL_UNESC%%[%Thirdpartyclicktracker%]%%DEST_URL%%""
        target=""_top"">
      <img src=""[%Image%]"">
    </a>
  </div>
  <div class=""app-icon""><img src=""[%Appicon%]""/></div>
  <div class=""title"">
    <a class=""title-link""
        href=""%%CLICK_URL_UNESC%%[%Thirdpartyclicktracker%]%%DEST_URL%%""
        target=""_top"">[%Headline%]</a>
  </div>
  <div class=""reviews""></div>
  <div class=""body"">
    <a class=""body-link""
        href=""%%CLICK_URL_UNESC%%[%Thirdpartyclicktracker%]%%DEST_URL%%""
        target=""_top"">[%Body%]</a>
  </div>
  <div class=""price"">[%Price%]</div>
  <div class=""button"">
    <a class=""button-link""
        href=""%%CLICK_URL_UNESC%%[%Thirdpartyclicktracker%]%%DEST_URL%%""
        target=""_top"">[%Calltoaction%]</a>
  </div>
</div>";

                string cssSnippet = @"body {
    background-color: rgba(255, 255, 255, 1);
    font-family: ""Roboto - Regular"", sans-serif;
    font - weight: normal;
      font - size: 12px;
      line - height: 14px;
    }
.attribution {
    background-color: rgba(236, 182, 0, 1);
    color: rgba(255, 255, 255, 1);
    font-size: 13px;
    display: table;
    margin: 4px 8px;
    padding: 0 3px;
    border-radius: 2px;
}
.image {
    text-align: center;
    margin: 8px;
}
.image img,
.image-link {
    width: 100%;
}
.app-icon {
    float: left;
    margin: 0 8px 4px 8px;
    height: 40px;
    width: 40px;
    background-color: transparent;
}
.app-icon img {
  height: 100%;
  width: 100%;
  border-radius: 20%;
}
.title {
    font-weight: bold;
    font-size: 14px;
    line-height: 20px;
    margin: 8px 8px 4px 8px;
}
.title a {
    color: rgba(112, 112, 112, 1);
text-decoration: none;
}
.reviews {
    float: left;
}
.reviews svg {
  fill: rgba(0, 0, 0, 0.7);
}
.body {
    clear: left;
    margin: 8px;
}
.body a {
  color: rgba(110, 110, 110, 1);
  text-decoration: none;
}
.price {
    display: none;
}
.button {
    font-size: 14px;
    font-weight: bold;
    float: right;
    margin: 0px 16px 16px 0px;
    white-space: nowrap;
}
.button a {
  color: #2196F3;
    text-decoration: none;
}
.button svg {
  display: none;
}";

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

                // Create a native style.
                NativeStyle nativeStyle = new NativeStyle();
                nativeStyle.name        = string.Format("Native style #{0}", new Random().Next());
                nativeStyle.size        = size;
                nativeStyle.htmlSnippet = htmlSnippet;
                nativeStyle.cssSnippet  = cssSnippet;

                // This is the creative template ID for the system-defined native app
                // install ad format, which we will create the native style from. Use
                // CreativeTemplateService.getCreativeTemplatesByStatement() and
                // CreativeTemplate.isNativeEligible to get other native ad formats
                // availablein your network.
                nativeStyle.creativeTemplateId = 10004400;

                try
                {
                    // Create the native styles on the server.
                    NativeStyle[] nativeStyles = nativeStyleService.createNativeStyles(
                        new NativeStyle[]
                    {
                        nativeStyle
                    });

                    if (nativeStyles != null)
                    {
                        foreach (NativeStyle createdNativeStyle in nativeStyles)
                        {
                            // Print out some information for each created native style.
                            Console.WriteLine(
                                "A native style with ID ='{0}' and name='{1}' was created.",
                                createdNativeStyle.id, createdNativeStyle.name);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to create native styles. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
コード例 #18
0
        /// <summary>
        /// Handles the Click event of the btnGetUsers control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing
        /// the event data.</param>
        protected void OnGetUsersButtonClick(object sender, EventArgs eventArgs)
        {
            ConfigureUserForOAuth();

            try
            {
                // Get the UserService.
                UserService userService = user.GetService <UserService>();

                // Create a Statement to get all users.
                StatementBuilder statementBuilder = new StatementBuilder().OrderBy("id ASC")
                                                    .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

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

                DataTable dataTable = new DataTable();
                dataTable.Columns.AddRange(new DataColumn[]
                {
                    new DataColumn("Serial No.", typeof(int)),
                    new DataColumn("User Id", typeof(long)),
                    new DataColumn("Email", typeof(string)),
                    new DataColumn("Role", typeof(string))
                });
                do
                {
                    // Get users by Statement.
                    page = userService.getUsersByStatement(statementBuilder.ToStatement());

                    if (page.results != null && page.results.Length > 0)
                    {
                        int i = page.startIndex;
                        foreach (User usr in page.results)
                        {
                            DataRow dataRow = dataTable.NewRow();
                            dataRow.ItemArray = new object[]
                            {
                                i + 1,
                                usr.id,
                                usr.email,
                                usr.roleName
                            };
                            dataTable.Rows.Add(dataRow);
                            i++;
                        }
                    }

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

                if (dataTable.Rows.Count > 0)
                {
                    UserGrid.DataSource = dataTable;
                    UserGrid.DataBind();
                }
                else
                {
                    Response.Write("No users were found.");
                }
            }
            catch (Exception e)
            {
                Response.Write(string.Format("Failed to get users. Exception says \"{0}\"",
                                             e.Message));
            }
        }
コード例 #19
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (CustomFieldService customFieldService = user.GetService <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.AdManager.v201908.DeactivateCustomFields action =
                            new Google.Api.Ads.AdManager.v201908.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);
                }
            }
        }
コード例 #20
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (CustomTargetingService customTargetingService =
                       user.GetService <CustomTargetingService>())
            {
                // Create predefined key.
                CustomTargetingKey genderKey = new CustomTargetingKey();
                genderKey.displayName = "gender";
                genderKey.name        = "g";
                genderKey.type        = CustomTargetingKeyType.PREDEFINED;

                // Create predefined key that may be used for content targeting.
                CustomTargetingKey genreKey = new CustomTargetingKey();
                genreKey.displayName = "genre";
                genreKey.name        = "genre";
                genreKey.type        = CustomTargetingKeyType.PREDEFINED;

                // Create free-form key.
                CustomTargetingKey carModelKey = new CustomTargetingKey();
                carModelKey.displayName = "car model";
                carModelKey.name        = "c";
                carModelKey.type        = CustomTargetingKeyType.FREEFORM;

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

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

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

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

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

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

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

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

                    if (returnValues != null)
                    {
                        foreach (CustomTargetingValue value in returnValues)
                        {
                            Console.WriteLine(
                                "A custom targeting value with ID \"{0}\", belonging to key " +
                                "with ID \"{1}\", name \"{2}\", and display name \"{3}\" " +
                                "was created.",
                                value.id, value.customTargetingKeyId, value.name,
                                value.displayName);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No values were created.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(
                        "Failed to create custom targeting keys and values. Exception " +
                        "says \"{0}\"", e.Message);
                }
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (WorkflowRequestService proposalLineItemService =
                       user.GetService <WorkflowRequestService>())
            {
                // Set the ID of the proposal to trigger workflow external conditions for.c
                long proposalId = long.Parse(_T("INSERT_PROPOSAL_ID_HERE"));

                // Create a statement to select workflow external condition requests for a proposal.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .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_EXTERNAL_CONDITION_REQUEST.ToString());

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

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

                        if (page.results != null)
                        {
                            int i = page.startIndex;
                            foreach (WorkflowRequest workflowRequest in page.results)
                            {
                                Console.WriteLine(
                                    "{0}) Workflow external condition request with ID '{1}'" +
                                    " for {2} with ID '{3}' will be triggered.", i++,
                                    workflowRequest.id, workflowRequest.entityType.ToString(),
                                    workflowRequest.entityId);
                                workflowRequestIds.Add(workflowRequest.id);
                            }
                        }

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

                    Console.WriteLine(
                        "Number of workflow external condition requests to be triggered: {0}",
                        workflowRequestIds.Count);

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

                        // Create action.
                        Google.Api.Ads.AdManager.v201902.TriggerWorkflowExternalConditionRequests action =
                            new Google.Api.Ads.AdManager.v201902.
                            TriggerWorkflowExternalConditionRequests();

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

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine(
                                "Number of workflow external condition requests triggered: {0}",
                                result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine(
                                "No workflow external condition requests were triggered.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(
                        "Failed to tirgger workflow external condition requests. Exception " +
                        "says \"{0}\"", e.Message);
                }
            }
        }
コード例 #22
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (ProposalLineItemService proposalLineItemService =
                       user.GetService <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)
                        {
                            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.AdManager.v202102.ArchiveProposalLineItems action =
                            new Google.Api.Ads.AdManager.v202102.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 e)
                {
                    Console.WriteLine(
                        "Failed to archive proposal line items. Exception says \"{0}\"", e.Message);
                }
            }
        }
コード例 #23
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (CreativeService creativeService = user.GetService <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.
                var imageUrl = "https://lh4.ggpht.com/" +
                               "GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZOPYnTdOQGaSpGSEZflIFs0iw=h300";
                templateVariables.Add(new AssetCreativeTemplateVariableValue()
                {
                    uniqueName = "Image",
                    asset      = new CreativeAsset()
                    {
                        fileName       = String.Format("image{0}.png", this.GetTimeStamp()),
                        assetByteArray =
                            MediaUtilities.GetAssetDataFromUrl(
                                imageUrl,
                                user.Config)
                    }
                });

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

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

                // 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);
                }
            }
        }
コード例 #24
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (OrderService orderService = user.GetService <OrderService>())
            {
                // Set the ID of the order.
                long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

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

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

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

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

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

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

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

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

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

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine("Number of orders approved: {0}", result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No orders were approved.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to approve orders. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
        /// <summary>
        /// Run the code examples.
        /// </summary>
        public void Run(AdManagerUser user, long proposalId, long rateCardId, long productId)
        {
            using (ProposalLineItemService proposalLineItemService =
                       user.GetService <ProposalLineItemService>())
            {
                // Create a proposal line item.
                ProposalLineItem proposalLineItem = new ProposalLineItem();
                proposalLineItem.name = "Programmatic proposal line item #" +
                                        new Random().Next(int.MaxValue);
                proposalLineItem.proposalId = proposalId;
                proposalLineItem.rateCardId = rateCardId;
                proposalLineItem.productId  = productId;

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

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

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

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

                    foreach (ProposalLineItem createdProposalLineItem in proposalLineItems)
                    {
                        Console.WriteLine(
                            "A programmatic proposal line item with ID \"{0}\" " +
                            "and name \"{1}\" was created.", createdProposalLineItem.id,
                            createdProposalLineItem.name);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(
                        "Failed to create proposal line items. Exception says \"{0}\"", e.Message);
                }
            }
        }
コード例 #26
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (UserTeamAssociationService userTeamAssociationService =
                       user.GetService <UserTeamAssociationService>())
            {
                // Set the user id of the user team association to update.
                long userId = long.Parse(_T("INSERT_USER_ID_HERE"));

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

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

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

                    UserTeamAssociation userTeamAssociation = page.results[0];

                    userTeamAssociation.overriddenTeamAccessType = TeamAccessType.READ_ONLY;

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

                    if (userTeamAssociations != null)
                    {
                        foreach (UserTeamAssociation updatedUserTeamAssociation in
                                 userTeamAssociations)
                        {
                            Console.WriteLine(
                                "User team association between user with ID \"{0}\" and team " +
                                "with ID \"{1}\" was updated to access type \"{2}\".",
                                updatedUserTeamAssociation.userId,
                                updatedUserTeamAssociation.teamId,
                                updatedUserTeamAssociation.overriddenTeamAccessType);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No user team associations updated.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(
                        "Failed to update user team associations. Exception says \"{0}\"",
                        e.Message);
                }
            }
        }
コード例 #27
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user, long proposalId)
        {
            using (ProposalService proposalService = user.GetService <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.AdManager.v202005.RequestBuyerAcceptance action =
                            new Google.Api.Ads.AdManager.v202005.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);
                }
            }
        }
コード例 #28
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (InventoryService inventoryService = user.GetService <InventoryService>())
            {
                // Get the NetworkService.
                NetworkService networkService = user.GetService <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);
                }
            }
        }
コード例 #29
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (CreativeService creativeService = user.GetService <CreativeService>())
            {
                // Set the ID of the advertiser (company) that all creatives will be
                // assigned to.
                long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE"));

                // Create the local custom creative object.
                CustomCreative customCreative = new CustomCreative();
                customCreative.name           = "Custom creative " + GetTimeStamp();
                customCreative.advertiserId   = advertiserId;
                customCreative.destinationUrl = "http://google.com";

                // Set the custom creative image asset.
                CustomCreativeAsset customCreativeAsset = new CustomCreativeAsset();
                customCreativeAsset.macroName = "IMAGE_ASSET";
                CreativeAsset asset = new CreativeAsset();
                asset.fileName       = string.Format("inline{0}.jpg", GetTimeStamp());
                asset.assetByteArray =
                    MediaUtilities.GetAssetDataFromUrl("https://goo.gl/3b9Wfh", user.Config);
                customCreativeAsset.asset = asset;

                customCreative.customCreativeAssets = new CustomCreativeAsset[]
                {
                    customCreativeAsset
                };

                // Set the HTML snippet using the custom creative asset macro.
                customCreative.htmlSnippet = "<a href='%%CLICK_URL_UNESC%%%%DEST_URL%%'>" +
                                             "<img src='%%FILE:" + customCreativeAsset.macroName + "%%'/>" +
                                             "</a><br>Click above for great deals!";

                // Set the creative size.
                Size size = new Size();
                size.width         = 300;
                size.height        = 250;
                size.isAspectRatio = false;

                customCreative.size = size;

                try
                {
                    // Create the custom creative on the server.
                    Creative[] createdCreatives = creativeService.createCreatives(new Creative[]
                    {
                        customCreative
                    });

                    foreach (Creative createdCreative in createdCreatives)
                    {
                        Console.WriteLine(
                            "A custom creative with ID \"{0}\", name \"{1}\", and size ({2}, " +
                            "{3}) was created and can be previewed at {4}", createdCreative.id,
                            createdCreative.name, createdCreative.size.width,
                            createdCreative.size.height, createdCreative.previewUrl);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to create custom creatives. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
コード例 #30
0
        /// <summary>
        /// Run the code examples.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (ProductTemplateService productTemplateService =
                       user.GetService <ProductTemplateService>())

                using (NetworkService networkService =
                           user.GetService <NetworkService>())
                {
                    // Create a product template.
                    ProductTemplate productTemplate = new ProductTemplate();
                    productTemplate.name = "Programmatic product template #" +
                                           new Random().Next(int.MaxValue);
                    productTemplate.description =
                        "This product template creates programmatic proposal line " +
                        "items targeting all ad units with product segmentation on 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 required Marketplace information.
                    productTemplate.productTemplateMarketplaceInfo =
                        new ProductTemplateMarketplaceInfo()
                    {
                        adExchangeEnvironment = AdExchangeEnvironment.DISPLAY,
                    };

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

                    // Create the creative placeholder.
                    CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
                    creativePlaceholder.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[]
                    {
                        creativePlaceholder
                    };

                    // 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 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 programmatic 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);
                    }
                }
        }