internal override void ProcessMappingsFromRowValues(RowValues values)
        {
            NegativeCampaignCriterion = new NegativeCampaignCriterion()
            {
                Criterion = new StoreCriterion()
                {
                    Type = typeof(StoreCriterion).Name,
                },
                Type = typeof(NegativeCampaignCriterion).Name
            };

            values.ConvertToEntity(this, Mappings);
        }
        internal override void ProcessMappingsFromRowValues(RowValues values)
        {
            NegativeCampaignCriterion = new NegativeCampaignCriterion()
            {
                Criterion = new Webpage()
                {
                    Parameter = new WebpageParameter(),
                    Type      = typeof(Webpage).Name,
                },
                Type = typeof(NegativeCampaignCriterion).Name
            };

            values.ConvertToEntity(this, Mappings);
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign to which targeting criteria
    /// are added.</param>
    public void Run(AdWordsUser user, long campaignId) {
      // Get the CampaignCriterionService.
      CampaignCriterionService campaignCriterionService =
          (CampaignCriterionService) user.GetService(
              AdWordsService.v201506.CampaignCriterionService);

      // Create language criteria.
      // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html
      // for a detailed list of language codes.
      Language language1 = new Language();
      language1.id = 1002; // French
      CampaignCriterion languageCriterion1 = new CampaignCriterion();
      languageCriterion1.campaignId = campaignId;
      languageCriterion1.criterion = language1;

      Language language2 = new Language();
      language2.id = 1005; // Japanese
      CampaignCriterion languageCriterion2 = new CampaignCriterion();
      languageCriterion2.campaignId = campaignId;
      languageCriterion2.criterion = language2;

      // Create location criteria.
      // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
      // for a detailed list of country codes.
      Location location1 = new Location();
      location1.id = 2840; // USA
      CampaignCriterion locationCriterion1 = new CampaignCriterion();
      locationCriterion1.campaignId = campaignId;
      locationCriterion1.criterion = location1;

      Location location2 = new Location();
      location2.id = 2392; // Japan
      CampaignCriterion locationCriterion2 = new CampaignCriterion();
      locationCriterion2.campaignId = campaignId;
      locationCriterion2.criterion = location2;

      // Add a negative campaign placement.
      NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();
      negativeCriterion.campaignId = campaignId;

      Placement placement = new Placement();
      placement.url = "http://mars.google.com";

      negativeCriterion.criterion = placement;

      CampaignCriterion[] criteria = new CampaignCriterion[] {languageCriterion1,
          languageCriterion2, locationCriterion1, locationCriterion2, negativeCriterion};

      List<CampaignCriterionOperation> operations = new List<CampaignCriterionOperation>();

      foreach (CampaignCriterion criterion in criteria) {
        CampaignCriterionOperation operation = new CampaignCriterionOperation();
        operation.@operator = Operator.ADD;
        operation.operand = criterion;
        operations.Add(operation);
      }

      try {
        // Set the campaign targets.
        CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray());

        if (retVal != null && retVal.value != null) {
          // Display campaign targets.
          foreach (CampaignCriterion criterion in retVal.value) {
            Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
          }
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to set Campaign criteria.", e);
      }
    }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which targeting criteria
        /// are added.</param>
        /// <param name="feedId">ID of a feed that has been configured for location
        /// targeting, meaning it has an ENABLED FeedMapping with criterionType of
        /// 77. Feeds linked to a GMB account automatically have this FeedMapping.
        /// If you don't have such a feed, set this value to null.</param>
        public void Run(AdWordsUser user, long campaignId, long?feedId)
        {
            using (CampaignCriterionService campaignCriterionService =
                       (CampaignCriterionService)user.GetService(AdWordsService.v201802
                                                                 .CampaignCriterionService))
            {
                // Create locations. The IDs can be found in the documentation or
                // retrieved with the LocationCriterionService.
                Location california = new Location()
                {
                    id = 21137L
                };

                Location mexico = new Location()
                {
                    id = 2484L
                };

                // Create languages. The IDs can be found in the documentation or
                // retrieved with the ConstantDataService.
                Language english = new Language()
                {
                    id = 1000L
                };

                Language spanish = new Language()
                {
                    id = 1003L
                };

                List <Criterion> criteria = new List <Criterion>()
                {
                    california,
                    mexico,
                    english,
                    spanish
                };

                // Distance targeting. Area of 10 miles around the locations in the location feed.
                if (feedId != null)
                {
                    LocationGroups radiusLocationGroup = new LocationGroups()
                    {
                        feedId           = feedId.Value,
                        matchingFunction = new Function()
                        {
                            @operator  = FunctionOperator.IDENTITY,
                            lhsOperand = new FunctionArgumentOperand[]
                            {
                                new LocationExtensionOperand()
                                {
                                    radius = new ConstantOperand()
                                    {
                                        type        = ConstantOperandConstantType.DOUBLE,
                                        unit        = ConstantOperandUnit.MILES,
                                        doubleValue = 10
                                    }
                                }
                            }
                        }
                    };

                    criteria.Add(radiusLocationGroup);
                }

                // Create operations to add each of the criteria above.
                List <CampaignCriterionOperation>
                operations = new List <CampaignCriterionOperation>();
                foreach (Criterion criterion in criteria)
                {
                    CampaignCriterionOperation operation = new CampaignCriterionOperation()
                    {
                        operand = new CampaignCriterion()
                        {
                            campaignId = campaignId,
                            criterion  = criterion
                        },
                        @operator = Operator.ADD
                    };

                    operations.Add(operation);
                }

                // Add a negative campaign criterion.

                CampaignCriterion negativeCriterion = new NegativeCampaignCriterion()
                {
                    campaignId = campaignId,
                    criterion  = new Keyword()
                    {
                        text      = "jupiter cruise",
                        matchType = KeywordMatchType.BROAD
                    }
                };

                CampaignCriterionOperation negativeCriterionOperation =
                    new CampaignCriterionOperation()
                {
                    operand   = negativeCriterion,
                    @operator = Operator.ADD
                };

                operations.Add(negativeCriterionOperation);

                try
                {
                    // Set the campaign targets.
                    CampaignCriterionReturnValue retVal =
                        campaignCriterionService.mutate(operations.ToArray());

                    if (retVal != null && retVal.value != null)
                    {
                        // Display campaign targets.
                        foreach (CampaignCriterion criterion in retVal.value)
                        {
                            Console.WriteLine(
                                "Campaign criteria of type '{0}' was set to campaign with" +
                                " id = '{1}'.", criterion.criterion.CriterionType,
                                criterion.campaignId);
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to set Campaign criteria.", e);
                }
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which targeting criteria
        /// are added.</param>
        /// <param name="feedId">ID of a feed that has been configured for location
        /// targeting, meaning it has an ENABLED FeedMapping with criterionType of
        /// 77. Feeds linked to a GMB account automatically have this FeedMapping.
        /// If you don't have such a feed, set this value to null.</param>
        public void Run(AdWordsUser user, long campaignId, long?feedId)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionService campaignCriterionService =
                (CampaignCriterionService)user.GetService(
                    AdWordsService.v201506.CampaignCriterionService);

            // Create language criteria.
            // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html
            // for a detailed list of language codes.
            Language language1 = new Language();

            language1.id = 1002; // French
            CampaignCriterion languageCriterion1 = new CampaignCriterion();

            languageCriterion1.campaignId = campaignId;
            languageCriterion1.criterion  = language1;

            Language language2 = new Language();

            language2.id = 1005; // Japanese
            CampaignCriterion languageCriterion2 = new CampaignCriterion();

            languageCriterion2.campaignId = campaignId;
            languageCriterion2.criterion  = language2;

            // Target Tier 3 income group near Miami, Florida.
            LocationGroups incomeLocationGroups = new LocationGroups();

            IncomeOperand incomeOperand = new IncomeOperand();

            // Tiers are numbered 1-10, and represent 10% segments of earners.
            // For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc.
            // Tiers 6 through 10 are grouped into TIER_6_TO_10.
            incomeOperand.tier = IncomeTier.TIER_3;

            GeoTargetOperand geoTargetOperand1 = new GeoTargetOperand();

            geoTargetOperand1.locations = new long[] { 1015116 }; // Miami, FL.

            incomeLocationGroups.matchingFunction            = new Function();
            incomeLocationGroups.matchingFunction.lhsOperand =
                new FunctionArgumentOperand[] { incomeOperand };
            incomeLocationGroups.matchingFunction.@operator  = FunctionOperator.AND;
            incomeLocationGroups.matchingFunction.rhsOperand =
                new FunctionArgumentOperand[] { geoTargetOperand1 };

            CampaignCriterion locationGroupCriterion1 = new CampaignCriterion();

            locationGroupCriterion1.campaignId = campaignId;
            locationGroupCriterion1.criterion  = incomeLocationGroups;

            // Target places of interest near Downtown Miami, Florida.
            LocationGroups interestLocationGroups = new LocationGroups();

            PlacesOfInterestOperand placesOfInterestOperand = new PlacesOfInterestOperand();

            placesOfInterestOperand.category = PlacesOfInterestOperandCategory.DOWNTOWN;

            GeoTargetOperand geoTargetOperand2 = new GeoTargetOperand();

            geoTargetOperand2.locations = new long[] { 1015116 }; // Miami, FL.

            interestLocationGroups.matchingFunction            = new Function();
            interestLocationGroups.matchingFunction.lhsOperand =
                new FunctionArgumentOperand[] { placesOfInterestOperand };
            interestLocationGroups.matchingFunction.@operator  = FunctionOperator.AND;
            interestLocationGroups.matchingFunction.rhsOperand =
                new FunctionArgumentOperand[] { geoTargetOperand2 };

            CampaignCriterion locationGroupCriterion2 = new CampaignCriterion();

            locationGroupCriterion2.campaignId = campaignId;
            locationGroupCriterion2.criterion  = interestLocationGroups;

            CampaignCriterion locationGroupCriterion3 = new CampaignCriterion();

            if (feedId.HasValue)
            {
                // Distance targeting. Area of 10 miles around targets above.
                ConstantOperand radius = new ConstantOperand();
                radius.type        = ConstantOperandConstantType.DOUBLE;
                radius.unit        = ConstantOperandUnit.MILES;
                radius.doubleValue = 10.0;
                LocationExtensionOperand distance = new LocationExtensionOperand();
                distance.radius = radius;

                LocationGroups radiusLocationGroups = new LocationGroups();
                radiusLocationGroups.matchingFunction            = new Function();
                radiusLocationGroups.matchingFunction.@operator  = FunctionOperator.IDENTITY;
                radiusLocationGroups.matchingFunction.lhsOperand =
                    new FunctionArgumentOperand[] { distance };

                // FeedID should be the ID of a feed that has been configured for location
                // targeting, meaning it has an ENABLED FeedMapping with criterionType of
                // 77. Feeds linked to a GMB account automatically have this FeedMapping.
                radiusLocationGroups.feedId = feedId.Value;

                locationGroupCriterion3.campaignId = campaignId;
                locationGroupCriterion3.criterion  = radiusLocationGroups;
            }

            // Create location criteria.
            // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
            // for a detailed list of country codes.
            Location location1 = new Location();

            location1.id = 2840; // USA
            CampaignCriterion locationCriterion1 = new CampaignCriterion();

            locationCriterion1.campaignId = campaignId;
            locationCriterion1.criterion  = location1;

            Location location2 = new Location();

            location2.id = 2392; // Japan
            CampaignCriterion locationCriterion2 = new CampaignCriterion();

            locationCriterion2.campaignId = campaignId;
            locationCriterion2.criterion  = location2;

            // Add a negative campaign keyword.
            NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();

            negativeCriterion.campaignId = campaignId;

            Keyword keyword = new Keyword();

            keyword.matchType = KeywordMatchType.BROAD;
            keyword.text      = "jupiter cruise";

            negativeCriterion.criterion = keyword;

            List <CampaignCriterion> criteria = new List <CampaignCriterion>(
                new CampaignCriterion[] { languageCriterion1,
                                          languageCriterion2, locationCriterion1, locationCriterion2, negativeCriterion,
                                          locationGroupCriterion1, locationGroupCriterion2 });

            if (feedId.HasValue)
            {
                criteria.Add(locationGroupCriterion3);
            }

            List <CampaignCriterionOperation> operations = new List <CampaignCriterionOperation>();

            foreach (CampaignCriterion criterion in criteria)
            {
                CampaignCriterionOperation operation = new CampaignCriterionOperation();
                operation.@operator = Operator.ADD;
                operation.operand   = criterion;
                operations.Add(operation);
            }

            try {
                // Set the campaign targets.
                CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray());

                if (retVal != null && retVal.value != null)
                {
                    // Display campaign targets.
                    foreach (CampaignCriterion criterion in retVal.value)
                    {
                        Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                                          " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
                    }
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to set Campaign criteria.", ex);
            }
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign to which targeting criteria
    /// are added.</param>
    public void Run(AdWordsUser user, long campaignId) {
      // Get the CampaignCriterionService.
      CampaignCriterionService campaignCriterionService =
          (CampaignCriterionService) user.GetService(
              AdWordsService.v201502.CampaignCriterionService);

      // Create language criteria.
      // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html
      // for a detailed list of language codes.
      Language language1 = new Language();
      language1.id = 1002; // French
      CampaignCriterion languageCriterion1 = new CampaignCriterion();
      languageCriterion1.campaignId = campaignId;
      languageCriterion1.criterion = language1;

      Language language2 = new Language();
      language2.id = 1005; // Japanese
      CampaignCriterion languageCriterion2 = new CampaignCriterion();
      languageCriterion2.campaignId = campaignId;
      languageCriterion2.criterion = language2;

      // Target Tier 3 income group near Miami, Florida.
      LocationGroups incomeLocationGroups = new LocationGroups();

      IncomeOperand incomeOperand = new IncomeOperand();
      // Tiers are numbered 1-10, and represent 10% segments of earners.
      // For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc.
      // Tiers 6 through 10 are grouped into TIER_6_TO_10.
      incomeOperand.tier = IncomeTier.TIER_3;

      GeoTargetOperand geoTargetOperand1 = new GeoTargetOperand();
      geoTargetOperand1.locations = new long[] {1015116}; // Miami, FL.

      incomeLocationGroups.matchingFunction = new Function();
      incomeLocationGroups.matchingFunction.lhsOperand =
          new FunctionArgumentOperand[] {incomeOperand};
      incomeLocationGroups.matchingFunction.@operator = FunctionOperator.AND;
      incomeLocationGroups.matchingFunction.rhsOperand =
          new FunctionArgumentOperand[] {geoTargetOperand1};

      CampaignCriterion locationGroupCriterion1 = new CampaignCriterion();
      locationGroupCriterion1.campaignId = campaignId;
      locationGroupCriterion1.criterion = incomeLocationGroups;

      // Target places of interest near Downtown Miami, Florida.
      LocationGroups interestLocationGroups = new LocationGroups();

      PlacesOfInterestOperand placesOfInterestOperand = new PlacesOfInterestOperand();
      placesOfInterestOperand.category = PlacesOfInterestOperandCategory.DOWNTOWN;

      GeoTargetOperand geoTargetOperand2 = new GeoTargetOperand();
      geoTargetOperand2.locations = new long[] { 1015116 }; // Miami, FL.

      interestLocationGroups.matchingFunction = new Function();
      interestLocationGroups.matchingFunction.lhsOperand =
          new FunctionArgumentOperand[] {placesOfInterestOperand};
      interestLocationGroups.matchingFunction.@operator = FunctionOperator.AND;
      interestLocationGroups.matchingFunction.rhsOperand =
          new FunctionArgumentOperand[] {geoTargetOperand2};

      CampaignCriterion locationGroupCriterion2 = new CampaignCriterion();
      locationGroupCriterion2.campaignId = campaignId;
      locationGroupCriterion2.criterion = interestLocationGroups;

      // Distance targeting. Area of 10 miles around targets above.
      ConstantOperand radius = new ConstantOperand();
      radius.type = ConstantOperandConstantType.DOUBLE;
      radius.unit = ConstantOperandUnit.MILES;
      radius.doubleValue = 10.0;
      LocationExtensionOperand distance = new LocationExtensionOperand();
      distance.radius = radius;

      LocationGroups radiusLocationGroups = new LocationGroups();
      radiusLocationGroups.matchingFunction = new Function();
      radiusLocationGroups.matchingFunction.@operator = FunctionOperator.IDENTITY;
      radiusLocationGroups.matchingFunction.lhsOperand = new FunctionArgumentOperand[] { distance };

      CampaignCriterion locationGroupCriterion3 = new CampaignCriterion();
      locationGroupCriterion3.campaignId = campaignId;
      locationGroupCriterion3.criterion = radiusLocationGroups;

      // Create location criteria.
      // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
      // for a detailed list of country codes.
      Location location1 = new Location();
      location1.id = 2840; // USA
      CampaignCriterion locationCriterion1 = new CampaignCriterion();
      locationCriterion1.campaignId = campaignId;
      locationCriterion1.criterion = location1;

      Location location2 = new Location();
      location2.id = 2392; // Japan
      CampaignCriterion locationCriterion2 = new CampaignCriterion();
      locationCriterion2.campaignId = campaignId;
      locationCriterion2.criterion = location2;

      // Add a negative campaign keyword.
      NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();
      negativeCriterion.campaignId = campaignId;

      Keyword keyword = new Keyword();
      keyword.matchType = KeywordMatchType.BROAD;
      keyword.text = "jupiter cruise";

      negativeCriterion.criterion = keyword;

      CampaignCriterion[] criteria = new CampaignCriterion[] {languageCriterion1,
          languageCriterion2, locationCriterion1, locationCriterion2, negativeCriterion,
          locationGroupCriterion1, locationGroupCriterion2, locationGroupCriterion3};

      List<CampaignCriterionOperation> operations = new List<CampaignCriterionOperation>();

      foreach (CampaignCriterion criterion in criteria) {
        CampaignCriterionOperation operation = new CampaignCriterionOperation();
        operation.@operator = Operator.ADD;
        operation.operand = criterion;
        operations.Add(operation);
      }

      try {
        // Set the campaign targets.
        CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray());

        if (retVal != null && retVal.value != null) {
          // Display campaign targets.
          foreach (CampaignCriterion criterion in retVal.value) {
            Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
          }
        }
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to set Campaign criteria.", ex);
      }
    }
        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                AdInsightService = new ServiceClient <IAdInsightService>(authorizationData);
                CampaignService  = new ServiceClient <ICampaignManagementService>(authorizationData);

                // To get started with dynamic search ads, first you'll need to add a new Campaign
                // with its type set to DynamicSearchAds. When you create the campaign, you'll need to
                // include a DynamicSearchAdsSetting that specifies the target website domain and language.

                var campaigns = new[] {
                    new Campaign
                    {
                        CampaignType = CampaignType.DynamicSearchAds,
                        Settings     = new [] {
                            new DynamicSearchAdsSetting
                            {
                                DomainName = "contoso.com",
                                Language   = "English"
                            }
                        },

                        Name        = "Women's Shoes " + DateTime.UtcNow,
                        Description = "Red shoes line.",

                        // You must choose to set either the shared  budget ID or daily amount.
                        // You can set one or the other, but you may not set both.
                        BudgetId    = null,
                        DailyBudget = 50,
                        BudgetType  = Microsoft.BingAds.V10.CampaignManagement.BudgetLimitType.DailyBudgetStandard,

                        // You can set your campaign bid strategy to Enhanced CPC (EnhancedCpcBiddingScheme)
                        // and then, at any time, set an individual ad group bid strategy to
                        // Manual CPC (ManualCpcBiddingScheme).
                        BiddingScheme = new EnhancedCpcBiddingScheme {
                        },

                        TimeZone       = "PacificTimeUSCanadaTijuana",
                        DaylightSaving = true,

                        // Used with CustomParameters defined in lower level entities such as ads.
                        TrackingUrlTemplate =
                            "http://tracker.example.com/?season={_season}&promocode={_promocode}&u={lpurl}"
                    },
                };

                AddCampaignsResponse addCampaignsResponse = await AddCampaignsAsync(authorizationData.AccountId, campaigns);

                long?[] campaignIds = addCampaignsResponse.CampaignIds.ToArray();
                Microsoft.BingAds.V10.CampaignManagement.BatchError[] campaignErrors =
                    addCampaignsResponse.PartialErrors.ToArray();
                OutputCampaignsWithPartialErrors(campaigns, campaignIds, campaignErrors);

                // Next, create a new AdGroup within the dynamic search ads campaign.

                var adGroups = new[] {
                    new AdGroup
                    {
                        Name           = "Women's Red Shoe Sale",
                        AdDistribution = AdDistribution.Search,
                        BiddingModel   = BiddingModel.Keyword,
                        PricingModel   = PricingModel.Cpc,
                        StartDate      = null,
                        EndDate        = new Date {
                            Month = 12,
                            Day   = 31,
                            Year  = DateTime.UtcNow.Year + 1
                        },
                        SearchBid = new Bid {
                            Amount = 0.09
                        },
                        Language = "English",

                        // For ad groups you can use either of the InheritFromParentBiddingScheme or ManualCpcBiddingScheme objects.
                        // If you do not set this element, then InheritFromParentBiddingScheme is used by default.
                        BiddingScheme = new ManualCpcBiddingScheme {
                        },
                    }
                };

                AddAdGroupsResponse addAdGroupsResponse = await AddAdGroupsAsync((long)campaignIds[0], adGroups);

                long?[] adGroupIds = addAdGroupsResponse.AdGroupIds.ToArray();
                Microsoft.BingAds.V10.CampaignManagement.BatchError[] adGroupErrors =
                    addAdGroupsResponse.PartialErrors.ToArray();
                OutputAdGroupsWithPartialErrors(adGroups, adGroupIds, adGroupErrors);

                // You can add one or more Webpage criterion to each ad group that helps determine
                // whether or not to serve dynamic search ads.

                var adGroupCriterions = new List <AdGroupCriterion>();

                var adGroupWebpagePositivePageContent = new BiddableAdGroupCriterion
                {
                    AdGroupId    = (long)adGroupIds[0],
                    CriterionBid = new FixedBid
                    {
                        Bid = new Bid
                        {
                            Amount = 0.50
                        }
                    },
                    Criterion = new Webpage
                    {
                        Parameter = new WebpageParameter
                        {
                            Conditions = new[]
                            {
                                new WebpageCondition
                                {
                                    Argument = "flowers",
                                    Operand  = WebpageConditionOperand.PageContent,
                                }
                            },
                            CriterionName = "Ad Group Webpage Positive Page Content Criterion"
                        },
                    },
                    // DestinationUrl and FinalUrls are not supported with Webpage criterion.
                    // The Final URL is dynamically created at the ad level.
                    DestinationUrl = null,
                    FinalUrls      = null,

                    // You could use a tracking template which would override the campaign level
                    // tracking template. Tracking templates defined for lower level entities
                    // override those set for higher level entities.
                    // In this example we are using the campaign level tracking template.
                    TrackingUrlTemplate = null,

                    // Set custom parameters that are specific to this webpage criterion,
                    // and can be used by the criterion, ad group, campaign, or account level tracking template.
                    // In this example we are using the campaign level tracking template.
                    UrlCustomParameters = new CustomParameters
                    {
                        Parameters = new[] {
                            new CustomParameter()
                            {
                                Key   = "promoCode",
                                Value = "PROMO1"
                            },
                            new CustomParameter()
                            {
                                Key   = "season",
                                Value = "summer"
                            },
                        }
                    }
                };
                adGroupCriterions.Add(adGroupWebpagePositivePageContent);

                // To discover the categories that you can use for Webpage criterion (positive or negative),
                // use the GetDomainCategories operation with the Ad Insight service.

                var getDomainCategoriesResponse = await GetDomainCategoriesAsync(DOMAIN_NAME, LANGUAGE);

                var categories = getDomainCategoriesResponse.Categories;

                // If any categories are available let's use one as a condition.
                if (categories.Count > 0)
                {
                    var adGroupWebpagePositiveCategory = new BiddableAdGroupCriterion
                    {
                        AdGroupId    = (long)adGroupIds[0],
                        CriterionBid = new FixedBid
                        {
                            Bid = new Bid
                            {
                                Amount = 0.50
                            }
                        },
                        Criterion = new Webpage
                        {
                            Parameter = new WebpageParameter
                            {
                                Conditions = new[]
                                {
                                    new WebpageCondition
                                    {
                                        Argument = categories[0].CategoryName,
                                        Operand  = WebpageConditionOperand.Category,
                                    }
                                },
                                CriterionName = "Ad Group Webpage Positive Category Criterion"
                            },
                        }
                    };
                    adGroupCriterions.Add(adGroupWebpagePositiveCategory);
                }

                // If you want to exclude certain portions of your website, you can add negative Webpage
                // criterion at the campaign and ad group level.

                var adGroupWebpageNegativeUrl = new NegativeAdGroupCriterion
                {
                    AdGroupId = (long)adGroupIds[0],
                    Criterion = new Webpage
                    {
                        Parameter = new WebpageParameter
                        {
                            // You can choose whether you want the criterion argument to match partial URLs,
                            // page content, page title, or categories that Bing thinks applies to your website.
                            Conditions = new[]
                            {
                                new WebpageCondition
                                {
                                    Argument = DOMAIN_NAME,
                                    Operand  = WebpageConditionOperand.Url,
                                }
                            },
                            // If you do not specify any name, then it will be set to a concatenated list of conditions.
                            CriterionName = null
                        }
                    },
                };
                adGroupCriterions.Add(adGroupWebpageNegativeUrl);

                OutputStatusMessage("Adding Ad Group Webpage Criterion . . . \n");
                OutputAdGroupCriterions(adGroupCriterions);
                AddAdGroupCriterionsResponse addAdGroupCriterionsResponse =
                    await AddAdGroupCriterionsAsync(adGroupCriterions, CriterionType.Webpage);

                long?[] adGroupCriterionIds = addAdGroupCriterionsResponse.AdGroupCriterionIds.ToArray();
                OutputStatusMessage("New Ad Group Criterion Ids:\n");
                OutputIds(adGroupCriterionIds);
                BatchErrorCollection[] adGroupCriterionErrors =
                    addAdGroupCriterionsResponse.NestedPartialErrors.ToArray();
                OutputStatusMessage("\nAddAdGroupCriterions Errors:\n");
                OutputBatchErrorCollections(adGroupCriterionErrors);

                // The negative Webpage criterion at the campaign level applies to all ad groups
                // within the campaign; however, if you define ad group level negative Webpage criterion,
                // the campaign criterion is ignored for that ad group.

                var campaignCriterions      = new List <CampaignCriterion>();
                var campaignWebpageNegative = new NegativeCampaignCriterion
                {
                    CampaignId = (long)campaignIds[0],
                    Criterion  = new Webpage
                    {
                        Parameter = new WebpageParameter
                        {
                            Conditions = new[]
                            {
                                new WebpageCondition
                                {
                                    Argument = DOMAIN_NAME + "\\seattle",
                                    Operand  = WebpageConditionOperand.Url,
                                }
                            },
                            CriterionName = "Campaign Negative Webpage Url Criterion"
                        }
                    }
                };
                campaignCriterions.Add(campaignWebpageNegative);

                OutputStatusMessage("Adding Campaign Webpage Criterion . . . \n");
                OutputCampaignCriterions(campaignCriterions);
                AddCampaignCriterionsResponse addCampaignCriterionsResponse =
                    await AddCampaignCriterionsAsync(campaignCriterions, CampaignCriterionType.Webpage);

                long?[] campaignCriterionIds = addCampaignCriterionsResponse.CampaignCriterionIds.ToArray();
                OutputStatusMessage("\nNew Campaign Criterion Ids:\n");
                OutputIds(campaignCriterionIds);
                BatchErrorCollection[] campaignCriterionErrors =
                    addCampaignCriterionsResponse.NestedPartialErrors.ToArray();
                OutputStatusMessage("\nAddCampaignCriterions Errors:\n");
                OutputBatchErrorCollections(campaignCriterionErrors);


                // Finally you can add a DynamicSearchAd into the ad group. The ad title and display URL
                // are generated automatically based on the website domain and language that you want to target.

                var ads = new Ad[] {
                    new DynamicSearchAd
                    {
                        Text  = "Find New Customers & Increase Sales! Start Advertising on Contoso Today.",
                        Path1 = "seattle",
                        Path2 = "shoe sale",

                        // You cannot set FinalUrls. The Final URL will be a dynamically selected landing page.
                        // The final URL is distinct from the path that customers will see and click on in your ad.
                        FinalUrls = null,

                        // You could use a tracking template which would override the campaign level
                        // tracking template. Tracking templates defined for lower level entities
                        // override those set for higher level entities.
                        // In this example we are using the campaign level tracking template.
                        TrackingUrlTemplate = null,

                        // Set custom parameters that are specific to this ad,
                        // and can be used by the ad, webpage, ad group, campaign, or account level tracking template.
                        // In this example we are using the campaign level tracking template.
                        UrlCustomParameters = new CustomParameters {
                            Parameters = new[] {
                                new CustomParameter()
                                {
                                    Key   = "promoCode",
                                    Value = "PROMO1"
                                },
                                new CustomParameter()
                                {
                                    Key   = "season",
                                    Value = "summer"
                                },
                            }
                        }
                    },
                };

                AddAdsResponse addAdsResponse = await AddAdsAsync((long)adGroupIds[0], ads);

                long?[] adIds = addAdsResponse.AdIds.ToArray();
                Microsoft.BingAds.V10.CampaignManagement.BatchError[] adErrors =
                    addAdsResponse.PartialErrors.ToArray();
                OutputAdsWithPartialErrors(ads, adIds, adErrors);

                // Retrieve the Webpage criterion for the campaign.
                var getCampaignCriterionsByIdsResponse = await GetCampaignCriterionsByIdsAsync(
                    (long)campaignIds[0],
                    null,
                    CampaignCriterionType.Webpage
                    );

                OutputStatusMessage("Retrieving the Campaign Webpage Criterions that we added . . . \n");
                campaignCriterions = getCampaignCriterionsByIdsResponse.CampaignCriterions.ToList();
                OutputCampaignCriterions(campaignCriterions);

                // Retrieve the Webpage criterion for the ad group and then test some update scenarios.
                var getAdGroupCriterionsByIdsResponse = await GetAdGroupCriterionsByIdsAsync(
                    (long)adGroupIds[0],
                    null,
                    CriterionType.Webpage
                    );

                OutputStatusMessage("Retrieving the Ad Group Webpage Criterions that we added . . . \n");
                adGroupCriterions = getAdGroupCriterionsByIdsResponse.AdGroupCriterions.ToList();
                OutputAdGroupCriterions(adGroupCriterions);

                // You can update the bid for BiddableAdGroupCriterion

                var updateBid = new FixedBid
                {
                    Bid = new Bid
                    {
                        Amount = 0.75
                    }
                };

                // You can update the Webpage criterion name but cannot update the conditions.
                // To update the conditions you must delete the criterion and add a new criterion.
                // This update attempt will return an error.

                var updateCriterionAttemptFailure = new Webpage
                {
                    Parameter = new WebpageParameter
                    {
                        Conditions = new[]
                        {
                            new WebpageCondition
                            {
                                Argument = "Books",
                                Operand  = WebpageConditionOperand.PageContent,
                            }
                        },
                        CriterionName = "Update Attempt Failure"
                    },
                };

                var updateCriterionAttemptSuccess = new Webpage
                {
                    Parameter = new WebpageParameter
                    {
                        CriterionName = "Update Attempt Success"
                    },
                };

                foreach (var adGroupCriterion in adGroupCriterions)
                {
                    var biddableAdGroupCriterion = adGroupCriterion as BiddableAdGroupCriterion;
                    if (biddableAdGroupCriterion != null)
                    {
                        ((BiddableAdGroupCriterion)(adGroupCriterion)).CriterionBid = updateBid;
                        ((BiddableAdGroupCriterion)(adGroupCriterion)).Criterion    = updateCriterionAttemptSuccess;
                    }
                    else
                    {
                        var negativeAdGroupCriterion = adGroupCriterion as NegativeAdGroupCriterion;
                        if (negativeAdGroupCriterion != null)
                        {
                            ((NegativeAdGroupCriterion)(adGroupCriterion)).Criterion = updateCriterionAttemptFailure;
                        }
                    }
                }

                OutputStatusMessage("Updating Ad Group Webpage Criterion . . . \n");
                OutputAdGroupCriterions(adGroupCriterions);
                UpdateAdGroupCriterionsResponse updateAdGroupCriterionsResponse =
                    await UpdateAdGroupCriterionsAsync(adGroupCriterions, CriterionType.Webpage);

                adGroupCriterionErrors =
                    updateAdGroupCriterionsResponse.NestedPartialErrors.ToArray();
                OutputStatusMessage("UpdateAdGroupCriterions Errors:\n");
                OutputBatchErrorCollections(adGroupCriterionErrors);

                // Delete the campaign, ad group, criterion, and ad that were previously added.
                // You should remove this operation if you want to view the added entities in the
                // Bing Ads web application or another tool.

                await DeleteCampaignsAsync(authorizationData.AccountId, new[] { (long)campaignIds[0] });

                OutputStatusMessage(string.Format("\nDeleted Campaign Id {0}\n", campaignIds[0]));
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Campaign Management service exceptions
            catch (FaultException <Microsoft.BingAds.V10.CampaignManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException <Microsoft.BingAds.V10.CampaignManagement.ApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException <Microsoft.BingAds.V10.CampaignManagement.EditorialApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which targeting criteria
        /// are added.</param>
        /// <param name="feedId">ID of a feed that has been configured for location
        /// targeting, meaning it has an ENABLED FeedMapping with criterionType of
        /// 77. Feeds linked to a GMB account automatically have this FeedMapping.
        /// If you don't have such a feed, set this value to null.</param>
        public void Run(AdWordsUser user, long campaignId, long?feedId)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionService campaignCriterionService =
                (CampaignCriterionService)user.GetService(
                    AdWordsService.v201605.CampaignCriterionService);

            // Create locations. The IDs can be found in the documentation or
            // retrieved with the LocationCriterionService.
            Location california = new Location()
            {
                id = 21137L
            };

            Location mexico = new Location()
            {
                id = 2484L
            };

            // Create languages. The IDs can be found in the documentation or
            // retrieved with the ConstantDataService.
            Language english = new Language()
            {
                id = 1000L
            };

            Language spanish = new Language()
            {
                id = 1003L
            };

            // Location groups criteria. These represent targeting by household income
            // or places of interest. The IDs can be found in the documentation or
            // retrieved with the LocationCriterionService.
            LocationGroups locationGroupTier3    = new LocationGroups();
            Function       tier3MatchingFunction = new Function();

            tier3MatchingFunction.lhsOperand = new FunctionArgumentOperand[] {
                // Tiers are numbered 1-10, and represent 10% segments of earners.
                // For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc.
                // Tiers 6 through 10 are grouped into TIER_6_TO_10.
                new IncomeOperand()
                {
                    tier = IncomeTier.TIER_3
                }
            };
            tier3MatchingFunction.@operator  = FunctionOperator.AND;
            tier3MatchingFunction.rhsOperand = new FunctionArgumentOperand[] {
                new GeoTargetOperand()
                {
                    locations = new long[] { 1015116L } // Miami, FL
                }
            };

            locationGroupTier3.matchingFunction = tier3MatchingFunction;

            LocationGroups locationGroupDowntown = new LocationGroups()
            {
                matchingFunction = new Function()
                {
                    lhsOperand = new FunctionArgumentOperand[] {
                        new PlacesOfInterestOperand()
                        {
                            category = PlacesOfInterestOperandCategory.DOWNTOWN
                        }
                    },
                    @operator  = FunctionOperator.AND,
                    rhsOperand = new FunctionArgumentOperand[] {
                        new GeoTargetOperand()
                        {
                            locations = new long[] { 1015116L } // Miami, FL
                        }
                    }
                }
            };

            List <Criterion> criteria = new List <Criterion>()
            {
                california, mexico, english, spanish, locationGroupTier3
            };

            // Distance targeting. Area of 10 miles around the locations in the location feed.
            if (feedId != null)
            {
                LocationGroups radiusLocationGroup = new LocationGroups()
                {
                    feedId           = feedId.Value,
                    matchingFunction = new Function()
                    {
                        @operator  = FunctionOperator.IDENTITY,
                        lhsOperand = new FunctionArgumentOperand[] {
                            new LocationExtensionOperand()
                            {
                                radius = new ConstantOperand()
                                {
                                    type        = ConstantOperandConstantType.DOUBLE,
                                    unit        = ConstantOperandUnit.MILES,
                                    doubleValue = 10
                                }
                            }
                        }
                    }
                };

                criteria.Add(radiusLocationGroup);
            }

            // Create operations to add each of the criteria above.
            List <CampaignCriterionOperation> operations = new List <CampaignCriterionOperation>();

            foreach (Criterion criterion in criteria)
            {
                CampaignCriterionOperation operation = new CampaignCriterionOperation()
                {
                    operand = new CampaignCriterion()
                    {
                        campaignId = campaignId,
                        criterion  = criterion
                    },
                    @operator = Operator.ADD
                };

                operations.Add(operation);
            }

            // Add a negative campaign criterion.

            CampaignCriterion negativeCriterion = new NegativeCampaignCriterion()
            {
                campaignId = campaignId,
                criterion  = new Keyword()
                {
                    text      = "jupiter cruise",
                    matchType = KeywordMatchType.BROAD
                }
            };

            CampaignCriterionOperation negativeCriterionOperation = new CampaignCriterionOperation()
            {
                operand   = negativeCriterion,
                @operator = Operator.ADD
            };

            operations.Add(negativeCriterionOperation);

            try {
                // Set the campaign targets.
                CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray());

                if (retVal != null && retVal.value != null)
                {
                    // Display campaign targets.
                    foreach (CampaignCriterion criterion in retVal.value)
                    {
                        Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                                          " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
                    }
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to set Campaign criteria.", e);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which targeting criteria
        /// are added.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionService campaignCriterionService =
                (CampaignCriterionService)user.GetService(
                    AdWordsService.v201502.CampaignCriterionService);

            // Create language criteria.
            // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html
            // for a detailed list of language codes.
            Language language1 = new Language();

            language1.id = 1002; // French
            CampaignCriterion languageCriterion1 = new CampaignCriterion();

            languageCriterion1.campaignId = campaignId;
            languageCriterion1.criterion  = language1;

            Language language2 = new Language();

            language2.id = 1005; // Japanese
            CampaignCriterion languageCriterion2 = new CampaignCriterion();

            languageCriterion2.campaignId = campaignId;
            languageCriterion2.criterion  = language2;

            // Create location criteria.
            // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
            // for a detailed list of country codes.
            Location location1 = new Location();

            location1.id = 2840; // USA
            CampaignCriterion locationCriterion1 = new CampaignCriterion();

            locationCriterion1.campaignId = campaignId;
            locationCriterion1.criterion  = location1;

            Location location2 = new Location();

            location2.id = 2392; // Japan
            CampaignCriterion locationCriterion2 = new CampaignCriterion();

            locationCriterion2.campaignId = campaignId;
            locationCriterion2.criterion  = location2;

            // Add a negative campaign placement.
            NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();

            negativeCriterion.campaignId = campaignId;

            Placement placement = new Placement();

            placement.url = "http://mars.google.com";

            negativeCriterion.criterion = placement;

            CampaignCriterion[] criteria = new CampaignCriterion[] { languageCriterion1,
                                                                     languageCriterion2, locationCriterion1, locationCriterion2, negativeCriterion };

            List <CampaignCriterionOperation> operations = new List <CampaignCriterionOperation>();

            foreach (CampaignCriterion criterion in criteria)
            {
                CampaignCriterionOperation operation = new CampaignCriterionOperation();
                operation.@operator = Operator.ADD;
                operation.operand   = criterion;
                operations.Add(operation);
            }

            try {
                // Set the campaign targets.
                CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray());

                if (retVal != null && retVal.value != null)
                {
                    // Display campaign targets.
                    foreach (CampaignCriterion criterion in retVal.value)
                    {
                        Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                                          " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
                    }
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to set Campaign criteria.", e);
            }
        }
        internal override void ProcessMappingsFromRowValues(RowValues values)
        {
            NegativeCampaignCriterion = new NegativeCampaignCriterion()
            {
                Criterion = new Webpage()
                {
                    Parameter = new WebpageParameter(),
                    Type = typeof(Webpage).Name,
                },
                Type = typeof(NegativeCampaignCriterion).Name
            };

            values.ConvertToEntity(this, Mappings);
        }
        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;

                AdInsightExampleHelper AdInsightExampleHelper = new AdInsightExampleHelper(
                    OutputStatusMessageDefault: this.OutputStatusMessage);
                AdInsightExampleHelper.AdInsightService = new ServiceClient <IAdInsightService>(
                    authorizationData: authorizationData,
                    environment: environment);

                CampaignManagementExampleHelper CampaignManagementExampleHelper = new CampaignManagementExampleHelper(
                    OutputStatusMessageDefault: this.OutputStatusMessage);
                CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient <ICampaignManagementService>(
                    authorizationData: authorizationData,
                    environment: environment);

                // To get started with dynamic search ads, first you'll need to add a new Campaign
                // with its type set to DynamicSearchAds. When you create the campaign, you'll need to
                // include a DynamicSearchAdsSetting that specifies the target website domain and language.

                var campaigns = new[] {
                    new Campaign
                    {
                        BudgetType   = Microsoft.BingAds.V13.CampaignManagement.BudgetLimitType.DailyBudgetStandard,
                        DailyBudget  = 50,
                        CampaignType = CampaignType.DynamicSearchAds,
                        Languages    = new string[] { "All" },
                        Name         = "Women's Shoes " + DateTime.UtcNow,
                        TimeZone     = "PacificTimeUSCanadaTijuana",
                        Settings     = new [] {
                            new DynamicSearchAdsSetting
                            {
                                DomainName = "contoso.com",
                                Language   = "English"
                            }
                        },
                    },
                };

                OutputStatusMessage("-----\nAddCampaigns:");
                AddCampaignsResponse addCampaignsResponse = await CampaignManagementExampleHelper.AddCampaignsAsync(
                    accountId : authorizationData.AccountId,
                    campaigns : campaigns);

                long?[] campaignIds = addCampaignsResponse.CampaignIds.ToArray();
                Microsoft.BingAds.V13.CampaignManagement.BatchError[] campaignErrors = addCampaignsResponse.PartialErrors.ToArray();
                OutputStatusMessage("CampaignIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(campaignIds);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(campaignErrors);

                // Create a new ad group within the dynamic search ads campaign.

                var adGroups = new[] {
                    new AdGroup
                    {
                        Name      = "Women's Red Shoe Sale",
                        StartDate = null,
                        EndDate   = new Date {
                            Month = 12,
                            Day   = 31,
                            Year  = DateTime.UtcNow.Year + 1
                        },
                        CpcBid = new Bid {
                            Amount = 0.09
                        },
                    }
                };

                OutputStatusMessage("-----\nAddAdGroups:");
                AddAdGroupsResponse addAdGroupsResponse = await CampaignManagementExampleHelper.AddAdGroupsAsync(
                    campaignId : (long)campaignIds[0],
                    adGroups : adGroups,
                    returnInheritedBidStrategyTypes : false);

                long?[] adGroupIds = addAdGroupsResponse.AdGroupIds.ToArray();
                Microsoft.BingAds.V13.CampaignManagement.BatchError[] adGroupErrors = addAdGroupsResponse.PartialErrors.ToArray();
                OutputStatusMessage("AdGroupIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(adGroupIds);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(adGroupErrors);

                // You can add one or more Webpage criteria to each ad group that helps determine
                // whether or not to serve dynamic search ads.

                var adGroupCriterions = new List <AdGroupCriterion>();

                var adGroupWebpagePositivePageContent = new BiddableAdGroupCriterion
                {
                    AdGroupId    = (long)adGroupIds[0],
                    CriterionBid = new FixedBid
                    {
                        Amount = 0.50
                    },
                    Criterion = new Webpage
                    {
                        Parameter = new WebpageParameter
                        {
                            Conditions = new[]
                            {
                                new WebpageCondition
                                {
                                    Argument = "flowers",
                                    Operand  = WebpageConditionOperand.PageContent,
                                }
                            },
                            CriterionName = "Ad Group Webpage Positive Page Content Criterion"
                        },
                    },
                };
                adGroupCriterions.Add(adGroupWebpagePositivePageContent);

                // To discover the categories that you can use for Webpage criteria (positive or negative),
                // use the GetDomainCategories operation with the Ad Insight service.

                OutputStatusMessage("-----\nGetDomainCategories:");
                var getDomainCategoriesResponse = await AdInsightExampleHelper.GetDomainCategoriesAsync(
                    categoryName : null,
                    domainName : DOMAIN_NAME,
                    language : LANGUAGE);

                var categories = getDomainCategoriesResponse.Categories;
                OutputStatusMessage("Categories:");
                AdInsightExampleHelper.OutputArrayOfDomainCategory(categories);

                // If any categories are available let's use one as a condition.

                if (categories.Count > 0)
                {
                    var adGroupWebpagePositiveCategory = new BiddableAdGroupCriterion
                    {
                        AdGroupId    = (long)adGroupIds[0],
                        CriterionBid = new FixedBid
                        {
                            Amount = 0.50
                        },
                        Criterion = new Webpage
                        {
                            Parameter = new WebpageParameter
                            {
                                Conditions = new[]
                                {
                                    new WebpageCondition
                                    {
                                        Argument = categories[0].CategoryName,
                                        Operand  = WebpageConditionOperand.Category,
                                    }
                                },
                                CriterionName = "Ad Group Webpage Positive Category Criterion"
                            },
                        }
                    };
                    adGroupCriterions.Add(adGroupWebpagePositiveCategory);
                }

                // If you want to exclude certain portions of your website, you can add negative Webpage
                // criterion at the campaign and ad group level.

                var adGroupWebpageNegativeUrl = new NegativeAdGroupCriterion
                {
                    AdGroupId = (long)adGroupIds[0],
                    Criterion = new Webpage
                    {
                        Parameter = new WebpageParameter
                        {
                            // You can choose whether you want the criterion argument to match partial URLs,
                            // page content, page title, or categories that Bing thinks applies to your website.
                            Conditions = new[]
                            {
                                new WebpageCondition
                                {
                                    Argument = DOMAIN_NAME,
                                    Operand  = WebpageConditionOperand.Url,
                                }
                            },
                            // If you do not specify any name, then it will be set to a concatenated list of conditions.
                            CriterionName = null
                        }
                    },
                };
                adGroupCriterions.Add(adGroupWebpageNegativeUrl);

                OutputStatusMessage("-----\nAddAdGroupCriterions:");
                CampaignManagementExampleHelper.OutputArrayOfAdGroupCriterion(adGroupCriterions);
                AddAdGroupCriterionsResponse addAdGroupCriterionsResponse = await CampaignManagementExampleHelper.AddAdGroupCriterionsAsync(
                    adGroupCriterions : adGroupCriterions,
                    criterionType : AdGroupCriterionType.Webpage);

                long?[] adGroupCriterionIds = addAdGroupCriterionsResponse.AdGroupCriterionIds.ToArray();
                OutputStatusMessage("AdGroupCriterionIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(adGroupCriterionIds);
                BatchErrorCollection[] adGroupCriterionErrors =
                    addAdGroupCriterionsResponse.NestedPartialErrors.ToArray();
                OutputStatusMessage("NestedPartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchErrorCollection(adGroupCriterionErrors);

                // The negative Webpage criterion at the campaign level applies to all ad groups
                // within the campaign; however, if you define ad group level negative Webpage criterion,
                // the campaign criterion is ignored for that ad group.

                var campaignCriterions      = new List <CampaignCriterion>();
                var campaignWebpageNegative = new NegativeCampaignCriterion
                {
                    CampaignId = (long)campaignIds[0],
                    Criterion  = new Webpage
                    {
                        Parameter = new WebpageParameter
                        {
                            Conditions = new[]
                            {
                                new WebpageCondition
                                {
                                    Argument = DOMAIN_NAME + "\\seattle",
                                    Operand  = WebpageConditionOperand.Url,
                                }
                            },
                            CriterionName = "Campaign Negative Webpage Url Criterion"
                        }
                    }
                };
                campaignCriterions.Add(campaignWebpageNegative);

                OutputStatusMessage("-----\nAddCampaignCriterions:");
                CampaignManagementExampleHelper.OutputArrayOfCampaignCriterion(campaignCriterions);
                AddCampaignCriterionsResponse addCampaignCriterionsResponse = await CampaignManagementExampleHelper.AddCampaignCriterionsAsync(
                    campaignCriterions : campaignCriterions,
                    criterionType : CampaignCriterionType.Webpage);

                long?[] campaignCriterionIds = addCampaignCriterionsResponse.CampaignCriterionIds.ToArray();
                OutputStatusMessage("CampaignCriterionIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(campaignCriterionIds);
                BatchErrorCollection[] campaignCriterionErrors =
                    addCampaignCriterionsResponse.NestedPartialErrors.ToArray();
                OutputStatusMessage("NestedPartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchErrorCollection(campaignCriterionErrors);

                // Finally you must add at least one DynamicSearchAd into the ad group. The ad title and display URL
                // are generated automatically based on the website domain and language that you want to target.

                var ads = new Ad[] {
                    new DynamicSearchAd
                    {
                        Text  = "Find New Customers & Increase Sales! Start Advertising on Contoso Today.",
                        Path1 = "seattle",
                        Path2 = "shoe sale",
                        // You cannot set FinalUrls for dynamic search ads.
                        // The Final URL will be a dynamically selected landing page.
                        // The final URL is distinct from the path that customers will see and click on in your ad.
                        FinalUrls = null,
                    },
                };

                OutputStatusMessage("-----\nAddAds:");
                AddAdsResponse addAdsResponse = await CampaignManagementExampleHelper.AddAdsAsync(
                    adGroupId : (long)adGroupIds[0],
                    ads : ads);

                long?[] adIds = addAdsResponse.AdIds.ToArray();
                Microsoft.BingAds.V13.CampaignManagement.BatchError[] adErrors = addAdsResponse.PartialErrors.ToArray();
                OutputStatusMessage("AdIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(adIds);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(adErrors);

                // Delete the campaign and everything it contains e.g., ad groups and ads.

                OutputStatusMessage("-----\nDeleteCampaigns:");
                await CampaignManagementExampleHelper.DeleteCampaignsAsync(
                    accountId : authorizationData.AccountId,
                    campaignIds : new[] { (long)campaignIds[0] });

                OutputStatusMessage(string.Format("Deleted Campaign Id {0}", campaignIds[0]));
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Campaign Management service exceptions
            catch (FaultException <Microsoft.BingAds.V13.CampaignManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException <Microsoft.BingAds.V13.CampaignManagement.ApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException <Microsoft.BingAds.V13.CampaignManagement.EditorialApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which targeting criteria
        /// are added.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionService campaignCriterionService =
                (CampaignCriterionService)user.GetService(
                    AdWordsService.v201402.CampaignCriterionService);

            // Create language criteria.
            // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html
            // for a detailed list of language codes.
            Language language1 = new Language();

            language1.id = 1002; // French
            CampaignCriterion languageCriterion1 = new CampaignCriterion();

            languageCriterion1.campaignId = campaignId;
            languageCriterion1.criterion  = language1;

            Language language2 = new Language();

            language2.id = 1005; // Japanese
            CampaignCriterion languageCriterion2 = new CampaignCriterion();

            languageCriterion2.campaignId = campaignId;
            languageCriterion2.criterion  = language2;

            // Target Tier 3 income group near Miami, Florida.
            LocationGroups incomeLocationGroups = new LocationGroups();

            IncomeOperand incomeOperand = new IncomeOperand();

            // Tiers are numbered 1-10, and represent 10% segments of earners.
            // For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc.
            // Tiers 6 through 10 are grouped into TIER_6_TO_10.
            incomeOperand.tier = IncomeTier.TIER_3;

            GeoTargetOperand geoTargetOperand1 = new GeoTargetOperand();

            geoTargetOperand1.locations = new long[] { 1015116 }; // Miami, FL.

            incomeLocationGroups.matchingFunction            = new Function();
            incomeLocationGroups.matchingFunction.lhsOperand =
                new FunctionArgumentOperand[] { incomeOperand };
            incomeLocationGroups.matchingFunction.@operator  = FunctionOperator.AND;
            incomeLocationGroups.matchingFunction.rhsOperand =
                new FunctionArgumentOperand[] { geoTargetOperand1 };

            CampaignCriterion locationGroupCriterion1 = new CampaignCriterion();

            locationGroupCriterion1.campaignId = campaignId;
            locationGroupCriterion1.criterion  = incomeLocationGroups;

            // Target places of interest near Downtown Miami, Florida.
            LocationGroups interestLocationGroups = new LocationGroups();

            PlacesOfInterestOperand placesOfInterestOperand = new PlacesOfInterestOperand();

            placesOfInterestOperand.category = PlacesOfInterestOperandCategory.DOWNTOWN;

            GeoTargetOperand geoTargetOperand2 = new GeoTargetOperand();

            geoTargetOperand2.locations = new long[] { 1015116 }; // Miami, FL.

            interestLocationGroups.matchingFunction            = new Function();
            interestLocationGroups.matchingFunction.lhsOperand =
                new FunctionArgumentOperand[] { placesOfInterestOperand };
            interestLocationGroups.matchingFunction.@operator  = FunctionOperator.AND;
            interestLocationGroups.matchingFunction.rhsOperand =
                new FunctionArgumentOperand[] { geoTargetOperand2 };

            CampaignCriterion locationGroupCriterion2 = new CampaignCriterion();

            locationGroupCriterion2.campaignId = campaignId;
            locationGroupCriterion2.criterion  = interestLocationGroups;

            // Create location criteria.
            // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
            // for a detailed list of country codes.
            Location location1 = new Location();

            location1.id = 2840; // USA
            CampaignCriterion locationCriterion1 = new CampaignCriterion();

            locationCriterion1.campaignId = campaignId;
            locationCriterion1.criterion  = location1;

            Location location2 = new Location();

            location2.id = 2392; // Japan
            CampaignCriterion locationCriterion2 = new CampaignCriterion();

            locationCriterion2.campaignId = campaignId;
            locationCriterion2.criterion  = location2;

            // Add a negative campaign keyword.
            NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();

            negativeCriterion.campaignId = campaignId;

            Keyword keyword = new Keyword();

            keyword.matchType = KeywordMatchType.BROAD;
            keyword.text      = "jupiter cruise";

            negativeCriterion.criterion = keyword;

            CampaignCriterion[] criteria = new CampaignCriterion[] { languageCriterion1,
                                                                     languageCriterion2, locationCriterion1, locationCriterion2, negativeCriterion,
                                                                     locationGroupCriterion1, locationGroupCriterion2 };

            List <CampaignCriterionOperation> operations = new List <CampaignCriterionOperation>();

            foreach (CampaignCriterion criterion in criteria)
            {
                CampaignCriterionOperation operation = new CampaignCriterionOperation();
                operation.@operator = Operator.ADD;
                operation.operand   = criterion;
                operations.Add(operation);
            }

            try {
                // Set the campaign targets.
                CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray());

                if (retVal != null && retVal.value != null)
                {
                    // Display campaign targets.
                    foreach (CampaignCriterion criterion in retVal.value)
                    {
                        Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                                          " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
                    }
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to set Campaign criteria.", ex);
            }
        }