/// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group that contains the keyword.
    /// </param>
    /// <param name="keywordId">Id of the keyword to be updated.</param>
    public void Run(AdWordsUser user, long adGroupId, long keywordId) {
      // Get the AdGroupCriterionService.
      AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(AdWordsService.v201502.AdGroupCriterionService);

      // Since we are not updating any keyword-specific fields, it is enough to
      // create a criterion object.
      Criterion criterion = new Criterion();
      criterion.id = keywordId;

      // Create ad group criterion.
      BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion();
      biddableAdGroupCriterion.adGroupId = adGroupId;
      biddableAdGroupCriterion.criterion = criterion;

      // Create the bids.
      BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
      CpcBid cpcBid = new CpcBid();
      cpcBid.bid = new Money();
      cpcBid.bid.microAmount = 1000000;
      biddingConfig.bids = new Bids[] {cpcBid};

      biddableAdGroupCriterion.biddingStrategyConfiguration = biddingConfig;

      // Create the operation.
      AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
      operation.@operator = Operator.SET;
      operation.operand = biddableAdGroupCriterion;

      try {
        // Update the keyword.
        AdGroupCriterionReturnValue retVal =
            adGroupCriterionService.mutate(new AdGroupCriterionOperation[] {operation});

        // Display the results.
        if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
          AdGroupCriterion adGroupCriterion = retVal.value[0];
          long bidAmount = 0;
          foreach (Bids bids in (adGroupCriterion as BiddableAdGroupCriterion).
              biddingStrategyConfiguration.bids) {
            if (bids is CpcBid) {
              bidAmount = (bids as CpcBid).bid.microAmount;
              break;
            }
          }

          Console.WriteLine("Keyword with ad group id = '{0}', id = '{1}' was updated with " +
              "bid amount = '{2}' micros.", adGroupCriterion.adGroupId,
              adGroupCriterion.criterion.id, bidAmount);
        } else {
          Console.WriteLine("No keyword was updated.");
        }
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to update keyword.", ex);
      }
    }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign to which ad groups are
    /// added.</param>
    public void Run(AdWordsUser user, long campaignId) {
      // Get the AdGroupService.
      AdGroupService adGroupService =
          (AdGroupService) user.GetService(AdWordsService.v201502.AdGroupService);

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

      for (int i = 0; i < NUM_ITEMS; i++) {
        // Create the ad group.
        AdGroup adGroup = new AdGroup();
        adGroup.name = string.Format("Earth to Mars Cruises #{0}",
            ExampleUtilities.GetRandomString());
        adGroup.status = AdGroupStatus.ENABLED;
        adGroup.campaignId = campaignId;

        // Set the ad group bids.
        BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();

        CpmBid cpmBid = new CpmBid();
        cpmBid.bid = new Money();
        cpmBid.bid.microAmount = 10000000;

        biddingConfig.bids = new Bids[] {cpmBid};

        adGroup.biddingStrategyConfiguration = biddingConfig;

        // Optional: Set targeting restrictions.
        // These settings only affect serving for the Display Network.
        TargetingSetting targetingSetting = new TargetingSetting();

        // Restricting to serve ads that match your ad group placements.
        // This is equivalent to choosing "Target and bid" in the UI.
        TargetingSettingDetail placementDetail = new TargetingSettingDetail();
        placementDetail.criterionTypeGroup = CriterionTypeGroup.PLACEMENT;
        placementDetail.targetAll = false;

        // Using your ad group verticals only for bidding. This is equivalent
        // to choosing "Bid only" in the UI.
        TargetingSettingDetail verticalDetail = new TargetingSettingDetail();
        verticalDetail.criterionTypeGroup = CriterionTypeGroup.VERTICAL;
        verticalDetail.targetAll = true;

        targetingSetting.details = new TargetingSettingDetail[] {placementDetail, verticalDetail};

        adGroup.settings = new Setting[] {targetingSetting};

        // Create the operation.
        AdGroupOperation operation = new AdGroupOperation();
        operation.@operator = Operator.ADD;
        operation.operand = adGroup;

        operations.Add(operation);
      }

      try {
        // Create the ad group.
        AdGroupReturnValue retVal = adGroupService.mutate(operations.ToArray());

        // Display the results.
        if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
          foreach (AdGroup newAdGroup in retVal.value) {
            Console.WriteLine("Ad group with id = '{0}' and name = '{1}' was created.",
                newAdGroup.id, newAdGroup.name);
          }
        } else {
          Console.WriteLine("No ad groups were created.");
        }
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to create ad groups.", ex);
      }
    }
        /// <summary>
        /// Creates the campaign with a shared bidding strategy.
        /// </summary>
        /// <param name="campaignService">The campaign service.</param>
        /// <param name="name">The campaign name.</param>
        /// <param name="biddingStrategyId">The bidding strategy id.</param>
        /// <param name="sharedBudgetId">The shared budget id.</param>
        /// <returns>The campaign object.</returns>
        private Campaign CreateCampaignWithBiddingStrategy(CampaignService campaignService, string name,
        long biddingStrategyId, long sharedBudgetId)
        {
            // Create campaign.
              Campaign campaign = new Campaign();
              campaign.name = name;
              campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;

              // Set the budget.
              campaign.budget = new Budget();
              campaign.budget.budgetId = sharedBudgetId;

              // Set bidding strategy (required).
              BiddingStrategyConfiguration biddingStrategyConfiguration =
              new BiddingStrategyConfiguration();
              biddingStrategyConfiguration.biddingStrategyId = biddingStrategyId;

              campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;

              // Set network targeting (recommended).
              NetworkSetting networkSetting = new NetworkSetting();
              networkSetting.targetGoogleSearch = true;
              networkSetting.targetSearchNetwork = true;
              networkSetting.targetContentNetwork = true;
              campaign.networkSetting = networkSetting;

              // Create operation.
              CampaignOperation operation = new CampaignOperation();
              operation.operand = campaign;
              operation.@operator = Operator.ADD;

              return campaignService.mutate(new CampaignOperation[] {operation}).value[0];
        }
    /// <summary>
    /// Creates the shopping campaign.
    /// </summary>
    /// <param name="budgetId">The budget id.</param>
    /// <param name="merchantId">The Merchant Center id.</param>
    /// <param name="campaignService">The CampaignService instance.</param>
    /// <returns>The Shopping campaign.</returns>
    private static Campaign CreateCampaign(long budgetId, long merchantId,
        CampaignService campaignService) {
      // Create campaign.
      Campaign campaign = new Campaign();
      campaign.name = "Shopping campaign #" + ExampleUtilities.GetRandomString();
      // The advertisingChannelType is what makes this a Shopping campaign.
      campaign.advertisingChannelType = AdvertisingChannelType.SHOPPING;

      // Set shared budget (required).
      campaign.budget = new Budget();
      campaign.budget.budgetId = budgetId;

      // Set bidding strategy (required).
      BiddingStrategyConfiguration biddingStrategyConfiguration =
          new BiddingStrategyConfiguration();
      biddingStrategyConfiguration.biddingStrategyType = BiddingStrategyType.MANUAL_CPC;

      campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;

      // All Shopping campaigns need a ShoppingSetting.
      ShoppingSetting shoppingSetting = new ShoppingSetting();
      shoppingSetting.salesCountry = "US";
      shoppingSetting.campaignPriority = 0;
      shoppingSetting.merchantId = merchantId;

      // Set to "true" to enable Local Inventory Ads in your campaign.
      shoppingSetting.enableLocal = true;
      campaign.settings = new Setting[] { shoppingSetting };

      // Create operation.
      CampaignOperation campaignOperation = new CampaignOperation();
      campaignOperation.operand = campaign;
      campaignOperation.@operator = Operator.ADD;

      // Make the mutate request.
      CampaignReturnValue retval = campaignService.mutate(
          new CampaignOperation[] { campaignOperation });

      return retval.value[0];
    }
    /// <summary>
    /// Creates a test campaign for running further tests.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="biddingStrategy">The bidding strategy to be used.</param>
    /// <returns>The campaign id.</returns>
    public long CreateCampaign(AdWordsUser user, AdvertisingChannelType channelType,
        BiddingStrategyType strategyType) {
      CampaignService campaignService =
          (CampaignService) user.GetService(AdWordsService.v201502.CampaignService);

      BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
      biddingConfig.biddingStrategyType = strategyType;

      CampaignOperation campaignOperation = new CampaignOperation();
      campaignOperation.@operator = Operator.ADD;
      campaignOperation.operand = new Campaign();
      campaignOperation.operand.name =
          string.Format("Campaign {0}", DateTime.Now.ToString("yyyy-M-d H:m:s.ffffff"));
      campaignOperation.operand.advertisingChannelType = channelType;
      campaignOperation.operand.status = CampaignStatus.PAUSED;
      campaignOperation.operand.biddingStrategyConfiguration = biddingConfig;
      campaignOperation.operand.budget = new Budget();
      campaignOperation.operand.budget.budgetId = CreateBudget(user);
      campaignOperation.operand.budget.period = BudgetBudgetPeriod.DAILY;
      campaignOperation.operand.budget.amount = new Money();
      campaignOperation.operand.budget.amount.microAmount = 100000000;
      campaignOperation.operand.budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD;

      List<Setting> settings = new List<Setting>();

      if (channelType == AdvertisingChannelType.SHOPPING) {
        // All Shopping campaigns need a ShoppingSetting.
        ShoppingSetting shoppingSetting = new ShoppingSetting();
        shoppingSetting.salesCountry = "US";
        shoppingSetting.campaignPriority = 0;
        shoppingSetting.merchantId = (user.Config as AdWordsAppConfig).MerchantCenterId;

        settings.Add(shoppingSetting);
      }
      campaignOperation.operand.settings = settings.ToArray();

      CampaignReturnValue retVal =
          campaignService.mutate(new CampaignOperation[] {campaignOperation});
      return retVal.value[0].id;
    }
    /// <summary>
    /// Creates a test adgroup for running further tests.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">The campaign id for which the adgroup is created.</param>
    /// <param name="isCpmBid">True, if a ManualCPM bid is to be used.</param>
    /// <returns>The adgroup id.</returns>
    public long CreateAdGroup(AdWordsUser user, long campaignId, bool isCpmBid) {
      AdGroupService adGroupService =
          (AdGroupService) user.GetService(AdWordsService.v201502.AdGroupService);

      AdGroupOperation adGroupOperation = new AdGroupOperation();
      adGroupOperation.@operator = Operator.ADD;
      adGroupOperation.operand = new AdGroup();
      adGroupOperation.operand.campaignId = campaignId;
      adGroupOperation.operand.name =
          string.Format("AdGroup {0}", DateTime.Now.ToString("yyyy-M-d H:m:s.ffffff"));
      adGroupOperation.operand.status = AdGroupStatus.ENABLED;

      if (isCpmBid) {
        BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
        CpmBid cpmBid = new CpmBid();
        cpmBid.bid = new Money();
        cpmBid.bid.microAmount = 10000000;
        biddingConfig.bids = new Bids[] {cpmBid};
        adGroupOperation.operand.biddingStrategyConfiguration = biddingConfig;
      } else {
        BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
        CpcBid cpcBid = new CpcBid();
        cpcBid.bid = new Money();
        cpcBid.bid.microAmount = 10000000;
        biddingConfig.bids = new Bids[] {cpcBid};
        adGroupOperation.operand.biddingStrategyConfiguration = biddingConfig;
      }
      AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[] {adGroupOperation});
      return retVal.value[0].id;
    }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the CampaignService.
              BudgetService budgetService =
              (BudgetService) user.GetService(AdWordsService.v201502.BudgetService);

              // Get the CampaignService.
              CampaignService campaignService =
              (CampaignService) user.GetService(AdWordsService.v201502.CampaignService);

              // Create the campaign budget.
              Budget budget = new Budget();
              budget.name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString();
              budget.period = BudgetBudgetPeriod.DAILY;
              budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD;
              budget.amount = new Money();
              budget.amount.microAmount = 500000;

              BudgetOperation budgetOperation = new BudgetOperation();
              budgetOperation.@operator = Operator.ADD;
              budgetOperation.operand = budget;

              try {
            BudgetReturnValue budgetRetval = budgetService.mutate(new BudgetOperation[] {budgetOperation});
            budget = budgetRetval.value[0];
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to add shared budget.", e);
              }

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

              for (int i = 0; i < NUM_ITEMS; i++) {
            // Create the campaign.
            Campaign campaign = new Campaign();
            campaign.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString();
            campaign.status = CampaignStatus.PAUSED;
            campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;

            BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
            biddingConfig.biddingStrategyType = BiddingStrategyType.MANUAL_CPM;

            // Optional: also provide matching bidding scheme.
            biddingConfig.biddingScheme = new ManualCpmBiddingScheme();

            campaign.biddingStrategyConfiguration = biddingConfig;

            // Set the campaign budget.
            campaign.budget = new Budget();
            campaign.budget.budgetId = budget.budgetId;

            // Set targetContentNetwork true. Other network targeting is not available
            // for Ad Exchange Buyers.
            campaign.networkSetting = new NetworkSetting();
            campaign.networkSetting.targetGoogleSearch = false;
            campaign.networkSetting.targetSearchNetwork = false;
            campaign.networkSetting.targetContentNetwork = true;
            campaign.networkSetting.targetPartnerSearchNetwork = false;

            // Enable campaign for Real-time bidding.
            RealTimeBiddingSetting rtbSetting = new RealTimeBiddingSetting();
            rtbSetting.optIn = true;

            campaign.settings = new Setting[] {rtbSetting};

            // Optional: Set the start date.
            campaign.startDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd");

            // Optional: Set the end date.
            campaign.endDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd");

            // Optional: Set the campaign ad serving optimization status.
            campaign.adServingOptimizationStatus = AdServingOptimizationStatus.ROTATE;

            // Optional: Set the frequency cap.
            FrequencyCap frequencyCap = new FrequencyCap();
            frequencyCap.impressions = 5;
            frequencyCap.level = Level.ADGROUP;
            frequencyCap.timeUnit = TimeUnit.DAY;
            campaign.frequencyCap = frequencyCap;

            // Create the operation.
            CampaignOperation operation = new CampaignOperation();
            operation.@operator = Operator.ADD;
            operation.operand = campaign;

            operations.Add(operation);
              }

              try {
            // Add the campaign.
            CampaignReturnValue retVal = campaignService.mutate(operations.ToArray());

            // Display the results.
            if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
              foreach (Campaign newCampaign in retVal.value) {
            Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was added.",
                newCampaign.name, newCampaign.id);
              }
            } else {
              Console.WriteLine("No campaigns were added.");
            }
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to add campaigns.", e);
              }
        }
            /// <summary>
            /// Creates the unit.
            /// </summary>
            /// <param name="parent">The node that should be this node's parent.
            /// </param>
            /// <param name="value">The value being paritioned on.</param>
            /// <param name="bidAmount">The amount to bid for matching products,
            /// in micros.</param>
            /// <param name="isNegative">True, if this is negative criterion, false
            /// otherwise.</param>
            /// <returns>A new unit node.</returns>
            public ProductPartition CreateUnit(ProductPartition parent, ProductDimension value,
          long bidAmount, bool isNegative)
            {
                ProductPartition unit = new ProductPartition();
                unit.partitionType = ProductPartitionType.UNIT;

                // The root node has neither a parent nor a value.
                if (parent != null) {
                  unit.parentCriterionId = parent.id;
                  unit.caseValue = value;
                }

                AdGroupCriterion criterion;

                if (isNegative) {
                  criterion = new NegativeAdGroupCriterion();
                } else {
                  BiddingStrategyConfiguration biddingStrategyConfiguration =
                  new BiddingStrategyConfiguration();

                  CpcBid cpcBid = new CpcBid();
                  cpcBid.bid = new Money();
                  cpcBid.bid.microAmount = bidAmount;
                  biddingStrategyConfiguration.bids = new Bids[] { cpcBid };

                  criterion = new BiddableAdGroupCriterion();
                  (criterion as BiddableAdGroupCriterion).biddingStrategyConfiguration =
                  biddingStrategyConfiguration;
                }

                criterion.adGroupId = this.adGroupId;
                criterion.criterion = unit;

                this.CreateAddOperation(criterion);

                return unit;
            }