Basic Operations Samples

The code samples below provide examples of basic operations using the AdWords API. Client Library.

Add ad groups

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;
using System.Collections.Generic;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example illustrates how to create ad groups. To create
  /// campaigns, run AddCampaigns.cs.
  /// </summary>
  public class AddAdGroups : ExampleBase {

    /// <summary>
    /// Number of items being added / updated in this code example.
    /// </summary>
    private const int NUM_ITEMS = 5;

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      AddAdGroups codeExample = new AddAdGroups();
      Console.WriteLine(codeExample.Description);
      try {
        long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
        codeExample.Run(new AdWordsUser(), campaignId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example illustrates how to create ad groups. To create campaigns, " +
            "run AddCampaigns.cs";
      }
    }

    /// <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) {
      using (AdGroupService adGroupService =
          (AdGroupService) user.GetService(AdWordsService.v201710.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();

          CpcBid cpcBid = new CpcBid();
          cpcBid.bid = new Money();
          cpcBid.bid.microAmount = 10000000;

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

          adGroup.biddingStrategyConfiguration = biddingConfig;

          // Optional: Set targeting restrictions.
          // Depending on the criterionTypeGroup value, most TargetingSettingDetail
          // only affect Display campaigns. However, the USER_INTEREST_AND_LIST value
          // works for RLSA campaigns - Search campaigns targeting using a
          // remarketing list.
          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 };

          // Set the rotation mode.
          AdGroupAdRotationMode rotationMode = new AdGroupAdRotationMode();
          rotationMode.adRotationMode = AdRotationMode.OPTIMIZE;
          adGroup.adGroupAdRotationMode = rotationMode;

          // 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 e) {
          throw new System.ApplicationException("Failed to create ad groups.", e);
        }
      }
    }
  }
}

Add ad group demographic criteria

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example adds demographic target criteria to an ad group. To get
  /// ad groups, run AddAdGroup.cs.
  /// </summary>
  public class AddAdGroupDemographicCriteria : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      AddAdGroupDemographicCriteria codeExample = new AddAdGroupDemographicCriteria();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example adds demographic target criteria to an ad group. To get ad " +
            "groups, run AddAdGroup.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group to which criteria are
    /// added.</param>
    public void Run(AdWordsUser user, long adGroupId) {
      using (AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(
              AdWordsService.v201710.AdGroupCriterionService)) {

        // Create biddable ad group criterion for gender
        Gender genderTarget = new Gender();
        // Criterion Id for male. The IDs can be found here
        // https://developers.google.com/adwords/api/docs/appendix/genders
        genderTarget.id = 10;

        BiddableAdGroupCriterion genderBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
        genderBiddableAdGroupCriterion.adGroupId = adGroupId;
        genderBiddableAdGroupCriterion.criterion = genderTarget;

        // Create negative ad group criterion for age range
        AgeRange ageRangeNegative = new AgeRange();
        // Criterion Id for age 18 to 24. The IDs can be found here
        // https://developers.google.com/adwords/api/docs/appendix/ages

        ageRangeNegative.id = 503001;
        NegativeAdGroupCriterion ageRangeNegativeAdGroupCriterion = new NegativeAdGroupCriterion();
        ageRangeNegativeAdGroupCriterion.adGroupId = adGroupId;
        ageRangeNegativeAdGroupCriterion.criterion = ageRangeNegative;

        // Create operations.
        AdGroupCriterionOperation genderBiddableAdGroupCriterionOperation =
            new AdGroupCriterionOperation();
        genderBiddableAdGroupCriterionOperation.operand = genderBiddableAdGroupCriterion;
        genderBiddableAdGroupCriterionOperation.@operator = Operator.ADD;

        AdGroupCriterionOperation ageRangeNegativeAdGroupCriterionOperation =
            new AdGroupCriterionOperation();
        ageRangeNegativeAdGroupCriterionOperation.operand = ageRangeNegativeAdGroupCriterion;
        ageRangeNegativeAdGroupCriterionOperation.@operator = Operator.ADD;

        AdGroupCriterionOperation[] operations = new AdGroupCriterionOperation[] {
          genderBiddableAdGroupCriterionOperation, ageRangeNegativeAdGroupCriterionOperation
        };

        try {
          // Add ad group criteria.
          AdGroupCriterionReturnValue result = adGroupCriterionService.mutate(operations);

          // Display ad group criteria.
          if (result != null && result.value != null) {
            foreach (AdGroupCriterion adGroupCriterionResult in result.value) {
              Console.WriteLine("Ad group criterion with ad group id \"{0}\", criterion id " +
                  "\"{1}\", and type \"{2}\" was added.", adGroupCriterionResult.adGroupId,
                  adGroupCriterionResult.criterion.id,
                  adGroupCriterionResult.criterion.CriterionType);
            }
          } else {
            Console.WriteLine("No ad group criteria were added.");
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to create ad group criteria.", e);
        }
      }
    }
  }
}

Add campaigns

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;
using System.Collections.Generic;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example adds campaigns. To get campaigns, run GetCampaigns.cs.
  /// </summary>
  public class AddCampaigns : ExampleBase {

    /// <summary>
    /// Number of items being added / updated in this code example.
    /// </summary>
    private const int NUM_ITEMS = 5;

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      AddCampaigns codeExample = new AddCampaigns();
      Console.WriteLine(codeExample.Description);
      try {
        codeExample.Run(new AdWordsUser());
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example adds campaigns. To get campaigns, run GetCampaigns.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    public void Run(AdWordsUser user) {
      using (CampaignService campaignService =
          (CampaignService) user.GetService(AdWordsService.v201710.CampaignService)) {

        Budget budget = CreateBudget(user);

        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.advertisingChannelType = AdvertisingChannelType.SEARCH;

          // Recommendation: Set the campaign to PAUSED when creating it to prevent
          // the ads from immediately serving. Set to ENABLED once you've added
          // targeting and the ads are ready to serve.
          campaign.status = CampaignStatus.PAUSED;

          BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
          biddingConfig.biddingStrategyType = BiddingStrategyType.MANUAL_CPC;
          campaign.biddingStrategyConfiguration = biddingConfig;

          campaign.budget = new Budget();
          campaign.budget.budgetId = budget.budgetId;

          // Set the campaign network options.
          campaign.networkSetting = new NetworkSetting();
          campaign.networkSetting.targetGoogleSearch = true;
          campaign.networkSetting.targetSearchNetwork = true;
          campaign.networkSetting.targetContentNetwork = false;
          campaign.networkSetting.targetPartnerSearchNetwork = false;

          // Set the campaign settings for Advanced location options.
          GeoTargetTypeSetting geoSetting = new GeoTargetTypeSetting();
          geoSetting.positiveGeoTargetType = GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE;
          geoSetting.negativeGeoTargetType = GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE;

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

          // 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 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 budget for the campaign.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <returns>The budget instance.</returns>
    private static Budget CreateBudget(AdWordsUser user) {
      using (BudgetService budgetService =
          (BudgetService) user.GetService(AdWordsService.v201710.BudgetService)) {

        // Create the campaign budget.
        Budget budget = new Budget();
        budget.name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString();
        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 });
          return budgetRetval.value[0];
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to add shared budget.", e);
        }
      }
    }
  }
}

Add expanded text ads

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;
using System.Collections.Generic;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example adds expanded text ads to a given ad group. To list
  /// ad groups, run GetAdGroups.cs.
  /// </summary>
  public class AddExpandedTextAds : ExampleBase {

    /// <summary>
    /// Number of ads being added / updated in this code example.
    /// </summary>
    private const int NUMBER_OF_ADS = 5;

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      AddExpandedTextAds codeExample = new AddExpandedTextAds();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example adds expanded text ads to a given ad group. To list " +
            "ad groups, run GetAdGroups.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group to which ads are added.
    /// </param>
    public void Run(AdWordsUser user, long adGroupId) {
      using (AdGroupAdService adGroupAdService =
          (AdGroupAdService) user.GetService(AdWordsService.v201710.AdGroupAdService)) {

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

        for (int i = 0; i < NUMBER_OF_ADS; i++) {
          // Create the expanded text ad.
          ExpandedTextAd expandedTextAd = new ExpandedTextAd();
          expandedTextAd.headlinePart1 = "Cruise #" + i.ToString() + " to Mars";
          expandedTextAd.headlinePart2 = "Best Space Cruise Line";
          expandedTextAd.description = "Buy your tickets now!";
          expandedTextAd.finalUrls = new string[] { "http://www.example.com/" + i };

          AdGroupAd expandedTextAdGroupAd = new AdGroupAd();
          expandedTextAdGroupAd.adGroupId = adGroupId;
          expandedTextAdGroupAd.ad = expandedTextAd;

          // Optional: Set the status.
          expandedTextAdGroupAd.status = AdGroupAdStatus.PAUSED;

          // Create the operation.
          AdGroupAdOperation operation = new AdGroupAdOperation();
          operation.@operator = Operator.ADD;
          operation.operand = expandedTextAdGroupAd;

          operations.Add(operation);
        }

        AdGroupAdReturnValue retVal = null;

        try {
          // Create the ads.
          retVal = adGroupAdService.mutate(operations.ToArray());

          // Display the results.
          if (retVal != null && retVal.value != null) {
            foreach (AdGroupAd adGroupAd in retVal.value) {
              ExpandedTextAd newAd = adGroupAd.ad as ExpandedTextAd;
              Console.WriteLine("Expanded text ad with ID '{0}' and headline '{1} - {2}' " +
                  "was added.", newAd.id, newAd.headlinePart1, newAd.headlinePart2);
            }
          } else {
            Console.WriteLine("No expanded text ads were created.");
          }
          adGroupAdService.Close();
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to create expanded text ad.", e);
        }
      }
    }
  }
}

   

Add keywords

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;
using System.Collections.Generic;
using System.Web;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example adds keywords to an ad group. To get ad groups, run
  /// GetAdGroups.cs.
  /// </summary>
  public class AddKeywords : ExampleBase {

    /// <summary>
    /// Items being added in this code example.
    /// </summary>
    private readonly string[] KEYWORDS = new string[] { "mars cruise", "space hotel" };

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      AddKeywords codeExample = new AddKeywords();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example adds keywords to an ad group. To get ad groups, run " +
            "GetAdGroups.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group to which keywords are added.
    /// </param>
    public void Run(AdWordsUser user, long adGroupId) {
      using (AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(
              AdWordsService.v201710.AdGroupCriterionService)) {

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

        foreach (string keywordText in KEYWORDS) {
          // Create the keyword.
          Keyword keyword = new Keyword();
          keyword.text = keywordText;
          keyword.matchType = KeywordMatchType.BROAD;

          // Create the biddable ad group criterion.
          BiddableAdGroupCriterion keywordCriterion = new BiddableAdGroupCriterion();
          keywordCriterion.adGroupId = adGroupId;
          keywordCriterion.criterion = keyword;

          // Optional: Set the user status.
          keywordCriterion.userStatus = UserStatus.PAUSED;

          // Optional: Set the keyword destination url.
          keywordCriterion.finalUrls = new UrlList() {
            urls = new string[] {
              "http://example.com/mars/cruise/?kw=" + HttpUtility.UrlEncode(keywordText)
            }
          };

          // Create the operations.
          AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
          operation.@operator = Operator.ADD;
          operation.operand = keywordCriterion;

          operations.Add(operation);
        }
        try {
          // Create the keywords.
          AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(
              operations.ToArray());

          // Display the results.
          if (retVal != null && retVal.value != null) {
            foreach (AdGroupCriterion adGroupCriterion in retVal.value) {
              // If you are adding multiple type of criteria, then you may need to
              // check for
              //
              // if (adGroupCriterion is Keyword) { ... }
              //
              // to identify the criterion type.
              Console.WriteLine("Keyword with ad group id = '{0}', keyword id = '{1}', text = " +
                  "'{2}' and match type = '{3}' was created.", adGroupCriterion.adGroupId,
                  adGroupCriterion.criterion.id, (adGroupCriterion.criterion as Keyword).text,
                  (adGroupCriterion.criterion as Keyword).matchType);
            }
          } else {
            Console.WriteLine("No keywords were added.");
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to create keywords.", e);
        }
      }
    }
  }
}

Get ad groups

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example illustrates how to retrieve all the ad groups for a
  /// campaign. To create an ad group, run AddAdGroup.cs.
  /// </summary>
  public class GetAdGroups : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      GetAdGroups codeExample = new GetAdGroups();
      Console.WriteLine(codeExample.Description);
      try {
        long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
        codeExample.Run(new AdWordsUser(), campaignId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example illustrates how to retrieve all the ad groups for a " +
            "campaign. To create an ad group, run AddAdGroup.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign for which ad groups are
    /// retrieved.</param>
    public void Run(AdWordsUser user, long campaignId) {
      using (AdGroupService adGroupService =
          (AdGroupService) user.GetService(AdWordsService.v201710.AdGroupService)) {

        // Create the selector.
        Selector selector = new Selector() {
          fields = new string[] { AdGroup.Fields.Id, AdGroup.Fields.Name },
          predicates = new Predicate[] {
            Predicate.Equals(AdGroup.Fields.CampaignId, campaignId)
          },
          paging = Paging.Default,
          ordering = new OrderBy[] { OrderBy.Asc(AdGroup.Fields.Name) }
        };

        AdGroupPage page = new AdGroupPage();

        try {
          do {
            // Get the ad groups.
            page = adGroupService.get(selector);

            // Display the results.
            if (page != null && page.entries != null) {
              int i = selector.paging.startIndex;
              foreach (AdGroup adGroup in page.entries) {
                Console.WriteLine("{0}) Ad group name is '{1}' and id is {2}.", i + 1,
                    adGroup.name, adGroup.id);
                i++;
              }
            }
            // Note: You can also use selector.paging.IncrementOffsetBy(customPageSize)
            selector.paging.IncreaseOffset();
          } while (selector.paging.startIndex < page.totalNumEntries);
          Console.WriteLine("Number of ad groups found: {0}", page.totalNumEntries);
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to retrieve ad groups.", e);
        }
      }
    }
  }
}

Get campaigns

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example lists all campaigns. To add a campaign, run
  /// AddCampaign.cs.
  /// </summary>
  public class GetCampaigns : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      GetCampaigns codeExample = new GetCampaigns();
      Console.WriteLine(codeExample.Description);
      try {
        codeExample.Run(new AdWordsUser());
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example lists all campaigns. To add a campaign, run AddCampaign.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    public void Run(AdWordsUser user) {
      using (CampaignService campaignService =
          (CampaignService) user.GetService(AdWordsService.v201710.CampaignService)) {

        // Create the selector.
        Selector selector = new Selector() {
          fields = new string[] {
            Campaign.Fields.Id, Campaign.Fields.Name, Campaign.Fields.Status
          },
          paging = Paging.Default
        };

        CampaignPage page = new CampaignPage();

        try {
          do {
            // Get the campaigns.
            page = campaignService.get(selector);

            // Display the results.
            if (page != null && page.entries != null) {
              int i = selector.paging.startIndex;
              foreach (Campaign campaign in page.entries) {
                Console.WriteLine("{0}) Campaign with id = '{1}', name = '{2}' and " +
                    "status = '{3}' was found.", i + 1, campaign.id,
                    campaign.name, campaign.status);
                i++;
              }
            }
            selector.paging.IncreaseOffset();
          } while (selector.paging.startIndex < page.totalNumEntries);
          Console.WriteLine("Number of campaigns found: {0}", page.totalNumEntries);
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to retrieve campaigns", e);
        }
      }
    }
  }
}

Get campaigns with AWQL

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example lists all campaigns using an AWQL query. See
  /// https://developers.google.com/adwords/api/docs/guides/awql for AWQL
  /// documentation. To add a campaign, run AddCampaign.cs.
  /// </summary>
  public class GetCampaignsWithAwql : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      GetCampaignsWithAwql codeExample = new GetCampaignsWithAwql();
      Console.WriteLine(codeExample.Description);
      try {
        codeExample.Run(new AdWordsUser());
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example lists all campaigns using an AWQL query. See " +
            "https://developers.google.com/adwords/api/docs/guides/awql for AWQL documentation. " +
            "To add a campaign, run AddCampaign.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    public void Run(AdWordsUser user) {
      using (CampaignService campaignService =
          (CampaignService) user.GetService(AdWordsService.v201710.CampaignService)) {

        // Create the query.
        string query = "SELECT Id, Name, Status ORDER BY Name";

        int offset = 0;
        int pageSize = 500;

        CampaignPage page = new CampaignPage();

        try {
          do {
            string queryWithPaging = string.Format("{0} LIMIT {1}, {2}", query, offset, pageSize);

            // Get the campaigns.
            page = campaignService.query(queryWithPaging);

            // Display the results.
            if (page != null && page.entries != null) {
              int i = offset;
              foreach (Campaign campaign in page.entries) {
                Console.WriteLine("{0}) Campaign with id = '{1}', name = '{2}' and status = " +
                    "'{3}' was found.", i + 1, campaign.id, campaign.name, campaign.status);
                i++;
              }
            }
            offset += pageSize;
          } while (offset < page.totalNumEntries);
          Console.WriteLine("Number of campaigns found: {0}", page.totalNumEntries);
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to retrieve campaigns", e);
        }
      }
    }
  }
}

Get expanded text ads

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example retrieves all expanded text ads given an existing ad group.
  /// To add expanded text ads to an existing ad group, run AddExpandedTextAds.cs.
  /// </summary>
  public class GetExpandedTextAds : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      GetExpandedTextAds codeExample = new GetExpandedTextAds();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example retrieves all expanded text ads given an existing ad group. " +
            "To add expanded text ads to an existing ad group, run AddExpandedTextAds.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group from which expanded text ads
    /// are retrieved.</param>
    public void Run(AdWordsUser user, long adGroupId) {
      using (AdGroupAdService adGroupAdService =
          (AdGroupAdService) user.GetService(AdWordsService.v201710.AdGroupAdService)) {

        // Create a selector.
        Selector selector = new Selector() {
          fields = new string[] {
            ExpandedTextAd.Fields.Id, AdGroupAd.Fields.Status, ExpandedTextAd.Fields.HeadlinePart1,
            ExpandedTextAd.Fields.HeadlinePart2, ExpandedTextAd.Fields.Description
          },
          ordering = new OrderBy[] { OrderBy.Asc(ExpandedTextAd.Fields.Id) },
          predicates = new Predicate[] {
            // Restrict the fetch to only the selected ad group id.
            Predicate.Equals(AdGroupAd.Fields.AdGroupId, adGroupId),

            // Retrieve only expanded text ads.
            Predicate.Equals("AdType", "EXPANDED_TEXT_AD"),

            // By default disabled ads aren't returned by the selector. To return
            // them include the DISABLED status in the statuses field.
            Predicate.In(AdGroupAd.Fields.Status, new string[] {
              AdGroupAdStatus.ENABLED.ToString(),
              AdGroupAdStatus.PAUSED.ToString(),
              AdGroupAdStatus.DISABLED.ToString()
            })
          },
          paging = Paging.Default
        };

        AdGroupAdPage page = new AdGroupAdPage();

        try {
          do {
            // Get the expanded text ads.
            page = adGroupAdService.get(selector);

            // Display the results.
            if (page != null && page.entries != null) {
              int i = selector.paging.startIndex;

              foreach (AdGroupAd adGroupAd in page.entries) {
                ExpandedTextAd expandedTextAd = (ExpandedTextAd) adGroupAd.ad;
                Console.WriteLine("{0} : Expanded text ad with ID '{1}', headline '{2} - {3}' " +
                    "and description '{4} was found.", i + 1, expandedTextAd.id,
                    expandedTextAd.headlinePart1, expandedTextAd.headlinePart2,
                    expandedTextAd.description);
                i++;
              }
            }
            selector.paging.IncreaseOffset();
          } while (selector.paging.startIndex < page.totalNumEntries);
          Console.WriteLine("Number of expanded text ads found: {0}", page.totalNumEntries);
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to get expanded text ads", e);
        }
      }
    }
  }
}

Get keywords

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example gets all keywords in an ad group. To add keywords, run
  /// AddKeywords.cs.
  /// </summary>
  public class GetKeywords : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      GetKeywords codeExample = new GetKeywords();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example gets all keywords in an ad group. To add keywords, run " +
            "AddKeywords.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">ID of the ad group from which keywords are
    /// retrieved.</param>
    public void Run(AdWordsUser user, long adGroupId) {
      using (AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(
              AdWordsService.v201710.AdGroupCriterionService)) {

        // Create a selector.
        Selector selector = new Selector() {
          fields = new string[] {
            Keyword.Fields.Id, Keyword.Fields.KeywordMatchType,
            Keyword.Fields.KeywordText, Keyword.Fields.CriteriaType
          },
          predicates = new Predicate[] {
            // Select only keywords.
            Predicate.In(Keyword.Fields.CriteriaType, new string[] {"KEYWORD"}),

            // Restrict search to an ad group.
            Predicate.Equals(AdGroupCriterion.Fields.AdGroupId, adGroupId),
          },
          ordering = new OrderBy[] { OrderBy.Asc(Keyword.Fields.KeywordText) },
          paging = Paging.Default
        };

        AdGroupCriterionPage page = new AdGroupCriterionPage();

        try {
          do {
            // Get the keywords.
            page = adGroupCriterionService.get(selector);

            // Display the results.
            if (page != null && page.entries != null) {
              int i = selector.paging.startIndex;

              foreach (AdGroupCriterion adGroupCriterion in page.entries) {
                Keyword keyword = (Keyword) adGroupCriterion.criterion;

                Console.WriteLine("{0}) Keyword with text '{1}', match type '{2}', criteria " +
                    "type '{3}', and ID {4} was found.", i + 1, keyword.text, keyword.matchType,
                    keyword.type, keyword.id);
                i++;
              }
            }
            selector.paging.IncreaseOffset();
          } while (selector.paging.startIndex < page.totalNumEntries);
          Console.WriteLine("Number of keywords found: {0}", page.totalNumEntries);
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to retrieve keywords.", e);
        }
      }
    }
  }
}

Pause an ad

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example pauses a given ad. To list all ads, run GetExpandedTextAds.cs.
  /// </summary>
  public class PauseAd : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      PauseAd codeExample = new PauseAd();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        long adId = long.Parse("INSERT_AD_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId, adId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example pauses a given ad. To list all ads, run GetExpandedTextAds.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group that contains the ad.
    /// </param>
    /// <param name="adId">Id of the ad to be paused.</param>
    public void Run(AdWordsUser user, long adGroupId, long adId) {
      using (AdGroupAdService adGroupAdService =
          (AdGroupAdService) user.GetService(AdWordsService.v201710.AdGroupAdService)) {

        AdGroupAdStatus status = AdGroupAdStatus.PAUSED;

        // Create the ad group ad.
        AdGroupAd adGroupAd = new AdGroupAd();
        adGroupAd.status = status;
        adGroupAd.adGroupId = adGroupId;

        adGroupAd.ad = new Ad();
        adGroupAd.ad.id = adId;

        // Create the operation.
        AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation();
        adGroupAdOperation.@operator = Operator.SET;
        adGroupAdOperation.operand = adGroupAd;

        try {
          // Update the ad.
          AdGroupAdReturnValue retVal = adGroupAdService.mutate(
              new AdGroupAdOperation[] { adGroupAdOperation });

          // Display the results.
          if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
            AdGroupAd pausedAdGroupAd = retVal.value[0];
            Console.WriteLine("Ad with id \"{0}\" and ad group id \"{1}\"was paused.",
                pausedAdGroupAd.ad.id, pausedAdGroupAd.adGroupId);
          } else {
            Console.WriteLine("No ads were paused.");
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to pause ad.", e);
        }
      }
    }
  }
}

Remove an ad

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example removes an ad using the 'REMOVE' operator. To list ads,
  /// run GetTextAds.cs.
  /// </summary>
  public class RemoveAd : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      RemoveAd codeExample = new RemoveAd();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        long adId = long.Parse("INSERT_AD_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId, adId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example removes an ad using the 'REMOVE' operator. To list ads, " +
            "run GetTextAds.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group that contains the ad.</param>
    /// <param name="adId">Id of the ad being removed.</param>
    public void Run(AdWordsUser user, long adGroupId, long adId) {
      using (AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService(
          AdWordsService.v201710.AdGroupAdService)) {

        // Since we do not need to update any ad-specific fields, it is enough to
        // create the base type.
        Ad ad = new Ad();
        ad.id = adId;

        // Create the ad group ad.
        AdGroupAd adGroupAd = new AdGroupAd();
        adGroupAd.adGroupId = adGroupId;

        adGroupAd.ad = ad;

        // Create the operation.
        AdGroupAdOperation operation = new AdGroupAdOperation();
        operation.operand = adGroupAd;
        operation.@operator = Operator.REMOVE;

        try {
          // Remove the ad.
          AdGroupAdReturnValue retVal = adGroupAdService.mutate(
              new AdGroupAdOperation[] { operation });

          if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
            AdGroupAd removedAdGroupAd = retVal.value[0];
            Console.WriteLine("Ad with id = \"{0}\" and type = \"{1}\" was removed.",
                removedAdGroupAd.ad.id, removedAdGroupAd.ad.AdType);
          } else {
            Console.WriteLine("No ads were removed.");
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to remove ad.", e);
        }
      }
    }
  }
}

Remove an ad group

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example removes an ad group by setting the status to 'REMOVED'.
  /// To get ad groups, run GetAdGroups.cs.
  /// </summary>
  public class RemoveAdGroup : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      RemoveAdGroup codeExample = new RemoveAdGroup();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example removes an ad group by setting the status to 'REMOVED'. " +
            "To get ad groups, run GetAdGroups.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group to be removed.</param>
    public void Run(AdWordsUser user, long adGroupId) {
      using (AdGroupService adGroupService = (AdGroupService) user.GetService(
          AdWordsService.v201710.AdGroupService)) {

        // Create ad group with REMOVED status.
        AdGroup adGroup = new AdGroup();
        adGroup.id = adGroupId;
        adGroup.status = AdGroupStatus.REMOVED;

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

        try {
          // Remove the ad group.
          AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[] { operation });

          // Display the results.
          if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
            AdGroup removedAdGroup = retVal.value[0];
            Console.WriteLine("Ad group with id = \"{0}\" and name = \"{1}\" was removed.",
                removedAdGroup.id, removedAdGroup.name);
          } else {
            Console.WriteLine("No ad groups were removed.");
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to remove ad group.", e);
        }
      }
    }
  }
}

Remove a campaign

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example removes a campaign by setting the status to 'REMOVED'.
  /// To get campaigns, run GetCampaigns.cs.
  /// </summary>
  public class RemoveCampaign : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      RemoveCampaign codeExample = new RemoveCampaign();
      Console.WriteLine(codeExample.Description);
      try {
        long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
        codeExample.Run(new AdWordsUser(), campaignId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example removes a campaign by setting the status to 'REMOVED'. " +
            "To get campaigns, run GetCampaigns.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign to be removed.</param>
    public void Run(AdWordsUser user, long campaignId) {
      using (CampaignService campaignService = (CampaignService) user.GetService(
          AdWordsService.v201710.CampaignService)) {

        // Create campaign with REMOVED status.
        Campaign campaign = new Campaign();
        campaign.id = campaignId;
        campaign.status = CampaignStatus.REMOVED;

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

        try {
          // Remove the campaign.
          CampaignReturnValue retVal = campaignService.mutate(
              new CampaignOperation[] { operation });

          // Display the results.
          if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
            Campaign removedCampaign = retVal.value[0];
            Console.WriteLine("Campaign with id = \"{0}\" was renamed to \"{1}\" and removed.",
                removedCampaign.id, removedCampaign.name);
          } else {
            Console.WriteLine("No campaigns were removed.");
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to remove campaign.", e);
        }
      }
    }
  }
}

Remove a keyword

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example removes a keyword using the 'REMOVE' operator. To get
  /// keywords, run GetKeywords.cs.
  /// </summary>
  public class RemoveKeyword : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      RemoveKeyword codeExample = new RemoveKeyword();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        long keywordId = long.Parse("INSERT_KEYWORD_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId, keywordId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example removes a keyword using the 'REMOVE' operator. To get " +
            "keywords, run GetKeywords.cs.";
      }
    }

    /// <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 removed.</param>
    public void Run(AdWordsUser user, long adGroupId, long keywordId) {
      using (AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(
              AdWordsService.v201710.AdGroupCriterionService)) {

        // Create base class criterion to avoid setting keyword-specific fields.
        Criterion criterion = new Criterion();
        criterion.id = keywordId;

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

        // Create the operation.
        AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
        operation.operand = adGroupCriterion;
        operation.@operator = Operator.REMOVE;

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

          // Display the results.
          if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
            AdGroupCriterion removedKeyword = retVal.value[0];
            Console.WriteLine("Keyword with ad group id = \"{0}\" and id = \"{1}\" was removed.",
                removedKeyword.adGroupId, removedKeyword.criterion.id);
          } else {
            Console.WriteLine("No keywords were removed.");
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to remove keyword.", e);
        }
      }
    }
  }
}

Update an ad group

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example illustrates how to update an ad group, setting its
  /// status to 'PAUSED'. To create an ad group, run AddAdGroup.cs.
  /// </summary>
  public class UpdateAdGroup : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      UpdateAdGroup codeExample = new UpdateAdGroup();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example illustrates how to update an ad group, setting its status to " +
            "'PAUSED'. To create an ad group, run AddAdGroup.cs";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group to be updated.</param>
    public void Run(AdWordsUser user, long adGroupId) {
      using (AdGroupService adGroupService =
          (AdGroupService) user.GetService(AdWordsService.v201710.AdGroupService)) {

        // Create the ad group.
        AdGroup adGroup = new AdGroup();
        adGroup.status = AdGroupStatus.PAUSED;
        adGroup.id = adGroupId;

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

        try {
          // Update the ad group.
          AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[] { operation });

          // Display the results.
          if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
            AdGroup pausedAdGroup = retVal.value[0];
            Console.WriteLine("Ad group with id = '{0}' was successfully updated.",
                pausedAdGroup.id);
          } else {
            Console.WriteLine("No ad groups were updated.");
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to update ad group.", e);
        }
      }
    }
  }
}

Update a campaign

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example updates a campaign. To get campaigns, run
  /// GetCampaigns.cs.
  /// </summary>
  public class UpdateCampaign : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      UpdateCampaign codeExample = new UpdateCampaign();
      Console.WriteLine(codeExample.Description);
      try {
        long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
        codeExample.Run(new AdWordsUser(), campaignId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example updates a campaign. To get campaigns, run GetCampaigns.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign to be updated.</param>
    public void Run(AdWordsUser user, long campaignId) {
      using (CampaignService campaignService =
          (CampaignService) user.GetService(AdWordsService.v201710.CampaignService)) {

        // Create the campaign.
        Campaign campaign = new Campaign();
        campaign.id = campaignId;
        campaign.status = CampaignStatus.PAUSED;

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

        try {
          // Update the campaign.
          CampaignReturnValue retVal = campaignService.mutate(
              new CampaignOperation[] { operation });

          // Display the results.
          if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
            Campaign updatedCampaign = retVal.value[0];
            Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was updated.",
                updatedCampaign.name, updatedCampaign.id);
          } else {
            Console.WriteLine("No campaigns were updated.");
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to update campaign.", e);
        }
      }
    }
  }
}

Update a keyword

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example updates the bid of a keyword. To get keyword, run
  /// GetKeywords.cs.
  /// </summary>
  public class UpdateKeyword : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      UpdateKeyword codeExample = new UpdateKeyword();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        long keywordId = long.Parse("INSERT_KEYWORD_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId, keywordId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example updates the bid of a keyword. To get keyword, run " +
            "GetKeywords.cs.";
      }
    }

    /// <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) {
      using (AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(
              AdWordsService.v201710.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 e) {
          throw new System.ApplicationException("Failed to update keyword.", e);
        }
      }
    }
  }
}

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.