Basic Operations Samples

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

Add demographic target criteria to an ad group

// 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 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.v201806
                    .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
                    id = 10
                };

                BiddableAdGroupCriterion genderBiddableAdGroupCriterion =
                    new BiddableAdGroupCriterion
                    {
                        adGroupId = adGroupId,
                        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

                    id = 503001
                };
                NegativeAdGroupCriterion ageRangeNegativeAdGroupCriterion =
                    new NegativeAdGroupCriterion
                    {
                        adGroupId = adGroupId,
                        criterion = ageRangeNegative
                    };

                // Create operations.
                AdGroupCriterionOperation genderBiddableAdGroupCriterionOperation =
                    new AdGroupCriterionOperation
                    {
                        operand = genderBiddableAdGroupCriterion,
                        @operator = Operator.ADD
                    };

                AdGroupCriterionOperation ageRangeNegativeAdGroupCriterionOperation =
                    new AdGroupCriterionOperation
                    {
                        operand = ageRangeNegativeAdGroupCriterion,
                        @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 ad groups 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 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.v201806.AdGroupService))
            {
                List<AdGroupOperation> operations = new List<AdGroupOperation>();

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

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

                    CpcBid cpcBid = new CpcBid
                    {
                        bid = new Money
                        {
                            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
                    {
                        criterionTypeGroup = CriterionTypeGroup.PLACEMENT,
                        targetAll = false
                    };

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

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

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

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

                    // Create the operation.
                    AdGroupOperation operation = new AdGroupOperation
                    {
                        @operator = Operator.ADD,
                        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 campaigns

// 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 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.v201806.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
                    {
                        name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(),
                        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.
                        status = CampaignStatus.PAUSED
                    };

                    BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration
                    {
                        biddingStrategyType = BiddingStrategyType.MANUAL_CPC
                    };
                    campaign.biddingStrategyConfiguration = biddingConfig;

                    campaign.budget = new Budget
                    {
                        budgetId = budget.budgetId
                    };

                    // Set the campaign network options.
                    campaign.networkSetting = new NetworkSetting
                    {
                        targetGoogleSearch = true,
                        targetSearchNetwork = true,
                        targetContentNetwork = false,
                        targetPartnerSearchNetwork = false
                    };

                    // Set the campaign settings for Advanced location options.
                    GeoTargetTypeSetting geoSetting = new GeoTargetTypeSetting
                    {
                        positiveGeoTargetType = GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE,
                        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
                    {
                        impressions = 5,
                        level = Level.ADGROUP,
                        timeUnit = TimeUnit.DAY
                    };
                    campaign.frequencyCap = frequencyCap;

                    // Create the operation.
                    CampaignOperation operation = new CampaignOperation
                    {
                        @operator = Operator.ADD,
                        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.v201806.BudgetService))
            {
                // Create the campaign budget.
                Budget budget = new Budget
                {
                    name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString(),
                    deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD,
                    amount = new Money
                    {
                        microAmount = 500000
                    }
                };

                BudgetOperation budgetOperation = new BudgetOperation
                {
                    @operator = Operator.ADD,
                    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 to an ad group

// 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 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.v201806.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
                    {
                        headlinePart1 = "Cruise #" + i.ToString() + " to Mars",
                        headlinePart2 = "Best Space Cruise Line",
                        description = "Buy your tickets now!",
                        finalUrls = new string[]
                        {
                            "http://www.example.com/" + i
                        }
                    };

                    AdGroupAd expandedTextAdGroupAd = new AdGroupAd
                    {
                        adGroupId = adGroupId,
                        ad = expandedTextAd,

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

                    // Create the operation.
                    AdGroupAdOperation operation = new AdGroupAdOperation
                    {
                        @operator = Operator.ADD,
                        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 to an ad group

// 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;
using System.Web;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201806
{
    /// <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.v201806
                    .AdGroupCriterionService))
            {
                List<AdGroupCriterionOperation> operations = new List<AdGroupCriterionOperation>();

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

                    // Create the biddable ad group criterion.
                    BiddableAdGroupCriterion keywordCriterion = new BiddableAdGroupCriterion
                    {
                        adGroupId = adGroupId,
                        criterion = keyword,

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

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

                    // Create the operations.
                    AdGroupCriterionOperation operation = new AdGroupCriterionOperation
                    {
                        @operator = Operator.ADD,
                        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);
                }
            }
        }
    }
}

Add a responsive search ad to an ad group

// 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 adds a responsive search ad to a given ad group. To get ad groups,
    /// run GetAdGroups.cs.
    /// </summary>
    public class AddResponsiveSearchAd : 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)
        {
            AddResponsiveSearchAd codeExample = new AddResponsiveSearchAd();
            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 a responsive search ad to a given 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 ads are added.
        /// </param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            using (AdGroupAdService adGroupAdService =
                (AdGroupAdService) user.GetService(AdWordsService.v201806.AdGroupAdService))
            {
                // Create a responsive search ad.
                ResponsiveSearchAd responsiveSearchAd = new ResponsiveSearchAd()
                {
                    finalUrls = new string[]
                    {
                        "http://www.example.com/cruise"
                    },
                    path1 = "all-inclusive",
                    path2 = "deals",
                    headlines = new AssetLink[]
                    {
                        new AssetLink()
                        {
                            asset = new TextAsset()
                            {
                                assetText =
                                    "Cruise to Mars #" + ExampleUtilities.GetShortRandomString(),
                            },
                            // Set a pinning to always choose this asset for HEADLINE_1.
                            // Pinning is optional; if no pinning is set, then headlines
                            // and descriptions will be rotated and the ones that perform
                            // best will be used more often.
                            pinnedField = ServedAssetFieldType.HEADLINE_1
                        },
                        new AssetLink()
                        {
                            asset = new TextAsset()
                            {
                                assetText = "Best Space Cruise Line",
                            }
                        },
                        new AssetLink()
                        {
                            asset = new TextAsset()
                            {
                                assetText = "Experience the Stars",
                            }
                        },
                    },
                    descriptions = new AssetLink[]
                    {
                        new AssetLink()
                        {
                            asset = new TextAsset()
                            {
                                assetText = "Buy your tickets now",
                            }
                        },
                        new AssetLink()
                        {
                            asset = new TextAsset()
                            {
                                assetText = "Visit the Red Planet",
                            }
                        },
                    }
                };

                // Create ad group ad.
                AdGroupAd adGroupAd = new AdGroupAd()
                {
                    adGroupId = adGroupId,
                    ad = responsiveSearchAd,

                    // Optional: Set additional settings.
                    status = AdGroupAdStatus.PAUSED
                };


                // Create ad group ad operation and add it to the list.
                AdGroupAdOperation operation = new AdGroupAdOperation()
                {
                    operand = adGroupAd,
                    @operator = Operator.ADD
                };

                try
                {
                    // Add the responsive search ad on the server.
                    AdGroupAdReturnValue retval = adGroupAdService.mutate(new AdGroupAdOperation[]
                    {
                        operation
                    });

                    // Print out some information for the created ad.
                    foreach (AdGroupAd newAdGroupAd in retval.value)
                    {
                        ResponsiveSearchAd newAd = (ResponsiveSearchAd) newAdGroupAd.ad;
                        Console.WriteLine(
                            $"New responsive search ad with ID {newAd.id} was added.");
                        Console.WriteLine("Headlines:");
                        foreach (AssetLink headline in newAd.headlines)
                        {
                            TextAsset textAsset = headline.asset as TextAsset;
                            Console.WriteLine($"    {textAsset.assetText}");
                            if (headline.pinnedFieldSpecified)
                            {
                                Console.WriteLine($"      (pinned to {headline.pinnedField})");
                            }
                        }

                        Console.WriteLine("Descriptions:");
                        foreach (AssetLink description in newAd.descriptions)
                        {
                            TextAsset textAsset = description.asset as TextAsset;
                            Console.WriteLine($"    {textAsset.assetText}");
                            if (description.pinnedFieldSpecified)
                            {
                                Console.WriteLine($"      (pinned to {description.pinnedField})");
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to create responsive search ad.",
                        e);
                }
            }
        }
    }
}

Get the ad groups of 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;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201806
{
    /// <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.v201806.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 all campaigns

// 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 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.v201806.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 all campaigns using AWQL

// 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 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.v201806.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 in an ad group

// 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 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.v201806.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 in an ad group

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

Get responsive search ads in an ad group

// 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 non-removed responsive search ads in an ad group. To add
    /// responsive search ads, run AddResponsiveSearchAd.cs. To get ad groups, run
    /// GetAdGroups.cs.
    /// </summary>
    public class GetResponsiveSearchAds : 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)
        {
            GetResponsiveSearchAds codeExample = new GetResponsiveSearchAds();
            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 non-removed responsive search ads in an ad group. " +
                    "To add responsive search ads, run AddResponsiveSearchAd.cs. 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 from which expanded text ads
        /// are retrieved.</param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            using (AdGroupAdService adGroupAdService =
                (AdGroupAdService) user.GetService(AdWordsService.v201806.AdGroupAdService))
            {
                // Create a selector to select all ads for the specified ad group.
                Selector selector = new Selector()
                {
                    fields = new string[]
                    {
                        ResponsiveSearchAd.Fields.Id,
                        AdGroupAd.Fields.Status,
                        ResponsiveSearchAd.Fields.ResponsiveSearchAdHeadlines,
                        ResponsiveSearchAd.Fields.ResponsiveSearchAdDescriptions
                    },
                    ordering = new OrderBy[]
                    {
                        OrderBy.Asc(ResponsiveSearchAd.Fields.Id)
                    },
                    predicates = new Predicate[]
                    {
                        // Restrict the fetch to only the selected ad group id.
                        Predicate.Equals(AdGroupAd.Fields.AdGroupId, adGroupId),

                        // Retrieve only responsive search ads.
                        Predicate.Equals("AdType", AdType.RESPONSIVE_SEARCH_AD.ToString()),
                    },
                    paging = Paging.Default
                };

                AdGroupAdPage page = new AdGroupAdPage();
                try
                {
                    do
                    {
                        // Get the responsive search 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)
                            {
                                ResponsiveSearchAd ad = (ResponsiveSearchAd) adGroupAd.ad;
                                Console.WriteLine(
                                    $"{i + 1} New responsive search ad with ID {ad.id} and " +
                                    $"status {adGroupAd.status} was found.");
                                Console.WriteLine("Headlines:");
                                foreach (AssetLink headline in ad.headlines)
                                {
                                    TextAsset textAsset = headline.asset as TextAsset;
                                    Console.WriteLine($"    {textAsset.assetText}");
                                    if (headline.pinnedFieldSpecified)
                                    {
                                        Console.WriteLine(
                                            $"      (pinned to {headline.pinnedField})");
                                    }
                                }

                                Console.WriteLine("Descriptions:");
                                foreach (AssetLink description in ad.descriptions)
                                {
                                    TextAsset textAsset = description.asset as TextAsset;
                                    Console.WriteLine($"    {textAsset.assetText}");
                                    if (description.pinnedFieldSpecified)
                                    {
                                        Console.WriteLine(
                                            $"      (pinned to {description.pinnedField})");
                                    }
                                }

                                i++;
                            }
                        }

                        selector.paging.IncreaseOffset();
                    } while (selector.paging.startIndex < page.totalNumEntries);

                    Console.WriteLine("Number of responsive search ads found: {0}",
                        page.totalNumEntries);
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to get responsive search ads.",
                        e);
                }
            }

        }
    }
}

Pause an ad

// 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 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.v201806.AdGroupAdService))
            {
                AdGroupAdStatus status = AdGroupAdStatus.PAUSED;

                // Create the ad group ad.
                AdGroupAd adGroupAd = new AdGroupAd
                {
                    status = status,
                    adGroupId = adGroupId,

                    ad = new Ad
                    {
                        id = adId
                    }
                };

                // Create the operation.
                AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation
                {
                    @operator = Operator.SET,
                    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 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 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.v201806.AdGroupAdService))
            {
                // Since we do not need to update any ad-specific fields, it is enough to
                // create the base type.
                Ad ad = new Ad
                {
                    id = adId
                };

                // Create the ad group ad.
                AdGroupAd adGroupAd = new AdGroupAd
                {
                    adGroupId = adGroupId,

                    ad = ad
                };

                // Create the operation.
                AdGroupAdOperation operation = new AdGroupAdOperation
                {
                    operand = adGroupAd,
                    @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 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 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.v201806.AdGroupService))
            {
                // Create ad group with REMOVED status.
                AdGroup adGroup = new AdGroup
                {
                    id = adGroupId,
                    status = AdGroupStatus.REMOVED
                };

                // Create the operation.
                AdGroupOperation operation = new AdGroupOperation
                {
                    operand = adGroup,
                    @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 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 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.v201806.CampaignService))
            {
                // Create campaign with REMOVED status.
                Campaign campaign = new Campaign
                {
                    id = campaignId,
                    status = CampaignStatus.REMOVED
                };

                // Create the operation.
                CampaignOperation operation = new CampaignOperation
                {
                    operand = campaign,
                    @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 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 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.v201806
                    .AdGroupCriterionService))
            {
                // Create base class criterion to avoid setting keyword-specific fields.
                Criterion criterion = new Criterion
                {
                    id = keywordId
                };

                // Create the ad group criterion.
                BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion
                {
                    adGroupId = adGroupId,
                    criterion = criterion
                };

                // Create the operation.
                AdGroupCriterionOperation operation = new AdGroupCriterionOperation
                {
                    operand = adGroupCriterion,
                    @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 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 update an ad group, setting its
    /// status to 'PAUSED', and its CPC bid to a new value if specified.
    /// 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");
                long? bidMicroAmount = null;

                // Optional: Provide a cpc bid for the ad group, in micro amounts.
                long tempVal = 0;
                if (long.TryParse("INSERT_CPC_BID_IN_MICROS_HERE", out tempVal))
                {
                    bidMicroAmount = tempVal;
                }

                codeExample.Run(new AdWordsUser(), adGroupId, bidMicroAmount);
            }
            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', and its CPC bid to a new value if specified. 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>
        /// <param name="bidMicroAmount">The CPC bid amount in micros.</param>
        public void Run(AdWordsUser user, long adGroupId, long? bidMicroAmount)
        {
            using (AdGroupService adGroupService =
                (AdGroupService) user.GetService(AdWordsService.v201806.AdGroupService))
            {
                // Create an ad group with the specified ID.
                AdGroup adGroup = new AdGroup
                {
                    id = adGroupId,

                    // Pause the ad group.
                    status = AdGroupStatus.PAUSED
                };

                // Update the CPC bid if specified.
                if (bidMicroAmount != null)
                {
                    BiddingStrategyConfiguration biddingStrategyConfiguration =
                        new BiddingStrategyConfiguration();
                    Money cpcBidMoney = new Money
                    {
                        microAmount = bidMicroAmount.Value
                    };
                    CpcBid cpcBid = new CpcBid
                    {
                        bid = cpcBidMoney
                    };
                    biddingStrategyConfiguration.bids = new Bids[]
                    {
                        cpcBid
                    };
                    adGroup.biddingStrategyConfiguration = biddingStrategyConfiguration;
                }

                // Create the operation.
                AdGroupOperation operation = new AdGroupOperation
                {
                    @operator = Operator.SET,
                    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 adGroupResult = retVal.value[0];
                        BiddingStrategyConfiguration bsConfig =
                            adGroupResult.biddingStrategyConfiguration;

                        // Find the CpcBid in the bidding strategy configuration's bids collection.
                        long cpcBidMicros = 0L;
                        if (bsConfig != null && bsConfig.bids != null)
                        {
                            foreach (Bids bid in bsConfig.bids)
                            {
                                if (bid is CpcBid)
                                {
                                    cpcBidMicros = ((CpcBid) bid).bid.microAmount;
                                    break;
                                }
                            }
                        }

                        Console.WriteLine(
                            "Ad group with ID {0} and name '{1}' updated to have status '{2}'" +
                            " and CPC bid {3}", adGroupResult.id, adGroupResult.name,
                            adGroupResult.status, cpcBidMicros);
                    }
                    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 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 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.v201806.CampaignService))
            {
                // Create the campaign.
                Campaign campaign = new Campaign
                {
                    id = campaignId,
                    status = CampaignStatus.PAUSED
                };

                // Create the operation.
                CampaignOperation operation = new CampaignOperation
                {
                    @operator = Operator.SET,
                    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 an expanded text ad

// 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 updates an expanded text ad. To get expanded text ads,
    /// run GetExpandedTextAds.cs.
    /// </summary>
    public class UpdateExpandedTextAd : 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)
        {
            UpdateExpandedTextAd codeExample = new UpdateExpandedTextAd();
            Console.WriteLine(codeExample.Description);
            try
            {
                long adId = long.Parse("INSERT_AD_ID_HERE");
                codeExample.Run(new AdWordsUser(), 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 updates an expanded text ad. To get expanded text ads, " +
                    "run GetExpandedTextAds.cs.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adId">Id of the ad to be updated.</param>
        public void Run(AdWordsUser user, long adId)
        {
            using (AdService adService =
                (AdService) user.GetService(AdWordsService.v201806.AdService))
            {
                // Create an expanded text ad using the provided ad ID.
                ExpandedTextAd expandedTextAd = new ExpandedTextAd
                {
                    id = adId,

                    // Update some properties of the expanded text ad.
                    headlinePart1 = "Cruise to Pluto #" + ExampleUtilities.GetShortRandomString(),
                    headlinePart2 = "Tickets on sale now",
                    description = "Best space cruise ever.",
                    finalUrls = new string[]
                    {
                        "http://www.example.com/"
                    },
                    finalMobileUrls = new string[]
                    {
                        "http://www.example.com/mobile"
                    }
                };

                // Create ad group ad operation and add it to the list.
                AdOperation operation = new AdOperation
                {
                    operand = expandedTextAd,
                    @operator = Operator.SET
                };

                try
                {
                    // Update the ad on the server.
                    AdReturnValue result = adService.mutate(new AdOperation[]
                    {
                        operation
                    });
                    ExpandedTextAd updatedAd = (ExpandedTextAd) result.value[0];

                    // Print out some information.
                    Console.WriteLine("Expanded text ad with ID {0} was updated.", updatedAd.id);
                    Console.WriteLine(
                        "Headline part 1: {0}\nHeadline part 2: {1}\nDescription: {2}" +
                        "\nFinal URL: {3}\nFinal mobile URL: {4}", updatedAd.headlinePart1,
                        updatedAd.headlinePart2, updatedAd.description, updatedAd.finalUrls[0],
                        updatedAd.finalMobileUrls[0]);
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to update expanded text ad.", e);
                }
            }
        }
    }
}

Update a keyword

// 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 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.v201806
                    .AdGroupCriterionService))
            {
                // Since we are not updating any keyword-specific fields, it is enough to
                // create a criterion object.
                Criterion criterion = new Criterion
                {
                    id = keywordId
                };

                // Create ad group criterion.
                BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion
                {
                    adGroupId = adGroupId,
                    criterion = criterion
                };

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

                biddableAdGroupCriterion.biddingStrategyConfiguration = biddingConfig;

                // Create the operation.
                AdGroupCriterionOperation operation = new AdGroupCriterionOperation
                {
                    @operator = Operator.SET,
                    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.