Targeting Samples

The code samples below provide examples of common targeting functions using the AdWords API. Client Library.

Add targeting criteria to a campaign

// Copyright 2018 Google LLC
//
// 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.v201806;

using System;
using System.Collections.Generic;

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

  /// <summary>
  /// This code example adds various types of targeting criteria to a campaign.
  /// To get a list of campaigns, run GetCampaigns.cs.
  /// </summary>
  public class AddCampaignTargetingCriteria : 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) {
      AddCampaignTargetingCriteria codeExample = new AddCampaignTargetingCriteria();
      Console.WriteLine(codeExample.Description);
      try {
        long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
        string feedIdText = "INSERT_LOCATION_FEED_ID_HERE";

        long? feedId = null;
        long temp;

        if (long.TryParse(feedIdText, out temp)) {
          feedId = temp;
        }

        codeExample.Run(new AdWordsUser(), campaignId, feedId);
      } 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 various types of targeting criteria to a campaign. To " +
            "get a list of 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 which targeting criteria
    /// are added.</param>
    /// <param name="feedId">ID of a feed that has been configured for location
    /// targeting, meaning it has an ENABLED FeedMapping with criterionType of
    /// 77. Feeds linked to a GMB account automatically have this FeedMapping.
    /// If you don't have such a feed, set this value to null.</param>
    public void Run(AdWordsUser user, long campaignId, long? feedId) {
      using (CampaignCriterionService campaignCriterionService =
          (CampaignCriterionService) user.GetService(
              AdWordsService.v201806.CampaignCriterionService)) {

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

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

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

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

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

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

          criteria.Add(radiusLocationGroup);
        }

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

          operations.Add(operation);
        }

        // Add a negative campaign criterion.

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

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

        operations.Add(negativeCriterionOperation);

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

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

Add negative criteria to a customer

// Copyright 2018 Google LLC
//
// 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.v201806;

using System;
using System.Collections.Generic;

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

  /// <summary>
  /// This code example adds various types of negative criteria to a customer. These criteria
  /// will be applied to all campaigns for the customer.
  /// </summary>
  public class AddCustomerNegativeCriteria : 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) {
      AddCustomerNegativeCriteria codeExample = new AddCustomerNegativeCriteria();
      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 various types of negative criteria to a customer. " +
            "These criteria will be applied to all campaigns for the customer.";
      }
    }

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

        List<Criterion> criteria = new List<Criterion>();

        // Exclude tragedy & conflict content.
        ContentLabel tragedyContentLabel = new ContentLabel();
        tragedyContentLabel.contentLabelType = ContentLabelType.TRAGEDY;
        criteria.Add(tragedyContentLabel);

        // Exclude a specific placement.
        Placement placement = new Placement();
        placement.url = "http://www.example.com";
        criteria.Add(placement);

        // Additional criteria types are available for this service. See the types listed
        // under Criterion here:
        // https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion

        // Create operations to add each of the criteria above.
        List<CustomerNegativeCriterionOperation> operations =
            new List<CustomerNegativeCriterionOperation>();
        foreach (Criterion criterion in criteria) {
          CustomerNegativeCriterion negativeCriterion = new CustomerNegativeCriterion();
          negativeCriterion.criterion = criterion;
          CustomerNegativeCriterionOperation operation = new CustomerNegativeCriterionOperation();
          operation.@operator = Operator.ADD;
          operation.operand = negativeCriterion;
          operations.Add(operation);
        }

        try {
          // Send the request to add the criteria.
          CustomerNegativeCriterionReturnValue result =
              customerNegativeCriterionService.mutate(operations.ToArray());

          // Display the results.
          foreach (CustomerNegativeCriterion negativeCriterion in result.value) {
            Console.WriteLine("Customer negative criterion with criterion ID {0} and type '{1}' " +
                "was added.", negativeCriterion.criterion.id,
                negativeCriterion.criterion.type);
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to set customer negative criteria.", e);
        }
      }
    }
  }
}

Get all campaign criteria

// Copyright 2018 Google LLC
//
// 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.v201806;

using System;

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

  /// <summary>
  /// This code example gets all targeting criteria for a campaign. To set
  /// campaign targeting criteria, run AddCampaignTargetingCriteria.cs. To get
  /// campaigns, run GetCampaigns.cs.
  /// </summary>
  public class GetCampaignTargetingCriteria : 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) {
      GetCampaignTargetingCriteria codeExample = new GetCampaignTargetingCriteria();
      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 gets all targeting criteria for a campaign. To set campaign " +
            "targeting criteria, run AddCampaignTargetingCriteria.cs. 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 from which targeting
    /// criteria are retrieved.</param>
    public void Run(AdWordsUser user, long campaignId) {
      using (CampaignCriterionService campaignCriterionService =
          (CampaignCriterionService) user.GetService(
              AdWordsService.v201806.CampaignCriterionService)) {

        // Create the selector.
        Selector selector = new Selector() {
          fields = new string[] {
            Criterion.Fields.Id, Criterion.Fields.CriteriaType, CampaignCriterion.Fields.CampaignId
          },
          predicates = new Predicate[] {
            Predicate.Equals(CampaignCriterion.Fields.CampaignId, campaignId)
          },
          paging = Paging.Default
        };

        CampaignCriterionPage page = new CampaignCriterionPage();

        try {
          do {
            // Get all campaign targets.
            page = campaignCriterionService.get(selector);

            // Display the results.
            if (page != null && page.entries != null) {
              int i = selector.paging.startIndex;
              foreach (CampaignCriterion campaignCriterion in page.entries) {
                string negative =
                    (campaignCriterion is NegativeCampaignCriterion) ? "Negative " : "";
                Console.WriteLine("{0}) {1}Campaign criterion with id = '{2}' and Type = {3} " +
                    "was found for campaign id '{4}'",
                    i + 1, negative, campaignCriterion.criterion.id,
                    campaignCriterion.criterion.type, campaignCriterion.campaignId);
                i++;
              }
            }
            selector.paging.IncreaseOffset();
          } while (selector.paging.startIndex < page.totalNumEntries);
          Console.WriteLine("Number of campaign targeting criteria found: {0}",
              page.totalNumEntries);
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to get campaign targeting criteria.", e);
        }
      }
    }
  }
}

Get all targetable languages and carriers

// Copyright 2018 Google LLC
//
// 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.v201806;

using System;

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

  /// <summary>
  /// This code example illustrates how to retrieve all carriers and languages
  /// available for targeting.
  /// </summary>
  public class GetTargetableLanguagesAndCarriers : 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) {
      GetTargetableLanguagesAndCarriers codeExample = new GetTargetableLanguagesAndCarriers();
      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 illustrates how to retrieve all carriers and languages " +
            "available for targeting.";
      }
    }

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

        try {
          // Get all carriers.
          Carrier[] carriers = constantDataService.getCarrierCriterion();

          // Display the results.
          if (carriers != null) {
            foreach (Carrier carrier in carriers) {
              Console.WriteLine("Carrier name is '{0}', ID is {1} and country code is '{2}'.",
                  carrier.name, carrier.id, carrier.countryCode);
            }
          } else {
            Console.WriteLine("No carriers were retrieved.");
          }

          // Get all languages.
          Language[] languages = constantDataService.getLanguageCriterion();

          // Display the results.
          if (languages != null) {
            foreach (Language language in languages) {
              Console.WriteLine("Language name is '{0}', ID is {1} and code is '{2}'.",
                  language.name, language.id, language.code);
            }
          } else {
            Console.WriteLine("No languages were found.");
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to get targetable carriers and languages.",
              e);
        }
      }
    }
  }
}

Get location criteria by name

// Copyright 2018 Google LLC
//
// 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.v201806;

using System;
using System.Collections.Generic;

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

  /// <summary>
  /// This code example gets location criteria by name.
  /// </summary>
  public class LookupLocation : 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) {
      LookupLocation codeExample = new LookupLocation();
      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 gets location criteria by name.";
      }
    }

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

        string[] locationNames = new string[] { "Paris", "Quebec", "Spain", "Deutschland" };

        Selector selector = new Selector() {
          fields = new string[] {
            Location.Fields.Id, Location.Fields.LocationName,
            LocationCriterion.Fields.CanonicalName, Location.Fields.DisplayType,
            Location.Fields.ParentLocations, LocationCriterion.Fields.Reach,
            Location.Fields.TargetingStatus
          },

          predicates = new Predicate[] {
            // Location names must match exactly, only EQUALS and IN are supported.
            Predicate.In(Location.Fields.LocationName, locationNames),

            // Set the locale of the returned location names.
            Predicate.Equals(LocationCriterion.Fields.Locale, "en")
          }
        };

        try {
          // Make the get request.
          LocationCriterion[] locationCriteria = locationCriterionService.get(selector);

          // Display the resulting location criteria.
          foreach (LocationCriterion locationCriterion in locationCriteria) {
            string parentLocations = "N/A";

            if (locationCriterion.location != null &&
                locationCriterion.location.parentLocations != null) {
              List<string> parentLocationList = new List<string>();
              foreach (Location location in locationCriterion.location.parentLocations) {
                parentLocationList.Add(GetLocationString(location));
              }
              parentLocations = string.Join(", ", parentLocationList);
            }

            Console.WriteLine("The search term '{0}' returned the location '{1}' of type '{2}' " +
                "with parent locations '{3}',  reach '{4}' and targeting status '{5}.",
                locationCriterion.searchTerm, locationCriterion.location.locationName,
                locationCriterion.location.displayType, parentLocations, locationCriterion.reach,
                locationCriterion.location.targetingStatus);
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to get location criteria.", e);
        }
      }
    }

    /// <summary>
    /// Gets a string representation for a location.
    /// </summary>
    /// <param name="location">The location</param>
    /// <returns>The string representation</returns>
    public string GetLocationString(Location location) {
      return string.Format("{0} ({1})", location.locationName, location.displayType);
    }
  }
}

Send feedback about...

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