/// <summary>
        /// 
        /// </summary>
        /// <param name="UseSandbox"></param>
        /// <param name="Name"></param>
        /// <param name="Countries"></param>
        /// <param name="Languages"></param>
        /// <param name="BudgetPeriod"></param>
        /// <param name="BudgetAmount"></param>
        /// <param name="MaxAdGroups"></param>
        /// <param name="DisplayUrl"></param>
        /// <param name="destinationUrlPrefix"></param>
        public void CreateCampaignByKeywordDensityContentMatch(bool UseSandbox, Guid AffiliateSiteRefId, int BudgetPeriod,
            Moneyv200906 BudgetAmount, AdGroupCriterionMoneyv200906 KeywordMaxCpc, string DisplayUrl, int MaxAdGroups, int AdKeywordType, int MinKeywordDensity,
            int MaxKeywordDensity, int MinContentMatch, decimal maxApiUsageDollars)
        {
            // Create a user (reads headers from App.config file).
            AdWordsUser user = new AdWordsUser();
            if (UseSandbox)
                user.UseSandbox();	// use sandbox

            AccountService accountService = (AccountService)user.GetService(ApiServices.v13.AccountService);
            string[] accounts = accountService.getClientAccounts();

            try
            {
                #region Create Campaign

                PpcNetwork ppcNetwork = DataRepository.PpcNetworkProvider.GetByName("AdWords");

                TList<PpcCampaign> Campaigns =
                    DataRepository.PpcCampaignProvider.GetByPpcNetworkRefId(ppcNetwork.PpcNetworkRefId);

                foreach (PpcCampaign campaign in Campaigns)
                {
                    // Target the campaign at
                    CampaignServicev200906 campaignService =
                        (com.google.api.adwords.v200906.CampaignService.CampaignService)
                        user.GetService(ApiServices.v200906.CampaignService);

                    // Create a new campaign with an ad group.  First create a
                    // campaign, so we can get its id.
                    Campaignv200906 newCampaign = new Campaignv200906();

                    // The campaign name is optional.  An error results if a campaign
                    // of the same name already exists.
                    newCampaign.name = campaign.CampaignName + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();

                    // Set the campaign status to paused, we don't want to start
                    // paying for this test.
                    // Required: Set the campaign status.
                    newCampaign.status = CampaignStatusv200906.ACTIVE;
                    newCampaign.statusSpecified = true;

                    // Required: Specify the currency and budget amount.
                    Budget budget = new Budget();
                    BudgetAmount.microAmountSpecified = true;
                    budget.amount = BudgetAmount;

                    // Required: Specify the bidding strategy.
                    newCampaign.biddingStrategy = new ManualCPC();

                    // Optional: Specify the budget period and delivery method.
                    budget.periodSpecified = true;
                    budget.period = BudgetBudgetPeriod.DAILY;
                    budget.deliveryMethodSpecified = true;
                    budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD;
                    newCampaign.budget = budget;

                    // Optional: Specify an endDate for the campaign.
                    newCampaign.endDate = DateTime.Now.AddDays(campaign.DurationInDays).ToString("yyyyMMdd");

                    // Define an Add operation to add the campaign.
                    CampaignOperation campaignOperation = new CampaignOperation();

                    campaignOperation.operatorSpecified = true;
                    campaignOperation.@operator = CampaignOperatorv200906.ADD;
                    campaignOperation.operand = newCampaign;

                    try
                    {
                        CampaignReturnValue results =
                            campaignService.mutate(new CampaignOperation[] { campaignOperation });
                        if (results != null && results.value != null && results.value.Length > 0)
                        {
                            newCampaign.id = results.value[0].id;
                            newCampaign.idSpecified = true;
                            Trace.TraceInformation(
                                "New campaign with name = \"{0}\" and id = " + "\"{1}\" was created.",
                                results.value[0].name, results.value[0].id);
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Error:" + ex.Message);
                        throw new Exception("Failed to create campaign. " + ex.Message);
                    }

                #endregion

                    #region Targeting

                    CampaignTargetService service =
                        (CampaignTargetService)user.GetService(ApiServices.v200906.CampaignTargetService);

                    // Create a language target - for English language.
                    LanguageTargetv200906 languageTarget = new LanguageTargetv200906();
                    languageTarget.languageCode = "en"; //TODO: Add as property
                    LanguageTargetList languageTargetList = new LanguageTargetList();
                    languageTargetList.targets = new LanguageTargetv200906[] { languageTarget };
                    languageTargetList.campaignId = newCampaign.id;
                    languageTargetList.campaignIdSpecified = true;

                    // Create a country target - include US, exclude metrocode 743.
                    CountryTargetv200906 countryTarget = new CountryTargetv200906();
                    countryTarget.countryCode = campaign.TargetCountry;
                    countryTarget.excludedSpecified = true;
                    countryTarget.excluded = false;
                    MetroTargetv200906 metroTarget = new MetroTargetv200906();
                    metroTarget.excludedSpecified = true;
                    metroTarget.excluded = true;
                    metroTarget.metroCode = campaign.ExcludeMetroTarget;

                    GeoTargetList geoTargetList = new GeoTargetList();
                    geoTargetList.targets = new GeoTargetv200906[] { countryTarget, metroTarget };
                    geoTargetList.campaignId = newCampaign.id;
                    geoTargetList.campaignIdSpecified = true;

                    // Create a network target - Google Search.
                    NetworkTargetv200906 networkTarget1 = new NetworkTargetv200906();
                    networkTarget1.networkCoverageTypeSpecified = true;
                    networkTarget1.networkCoverageType = NetworkCoverageTypev200906.GOOGLE_SEARCH;
                    NetworkTargetv200906 networkTarget2 = new NetworkTargetv200906();
                    networkTarget2.networkCoverageTypeSpecified = true;
                    networkTarget2.networkCoverageType = NetworkCoverageTypev200906.SEARCH_NETWORK;

                    NetworkTargetList networkTargetList = new NetworkTargetList();
                    networkTargetList.targets = new NetworkTargetv200906[] { networkTarget1, networkTarget2 };
                    networkTargetList.campaignId = newCampaign.id;
                    networkTargetList.campaignIdSpecified = true;

                    TargetList[] targets =
                        new TargetList[] { languageTargetList, geoTargetList, networkTargetList };

                    ArrayList campaignTargetOperations = new ArrayList();

                    foreach (TargetList target in targets)
                    {
                        CampaignTargetOperation ops = new CampaignTargetOperation();
                        ops.operatorSpecified = true;
                        ops.@operator = CampaignTargetOperatorv200906.SET;
                        ops.operand = target;
                        campaignTargetOperations.Add(ops);
                    }

                    try
                    {
                        service.mutate((CampaignTargetOperation[])
                                       campaignTargetOperations.ToArray(typeof(CampaignTargetOperation)));
                        Trace.TraceInformation("Geo, language, and network targeting were " +
                                               "successfully added to campaign id = \"{0}\".", newCampaign.id);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Failed to create campaign targeting. " +
                                         "Exception says \"{0}\"", ex.Message);
                    }

                    #endregion

                    #region Create your Services

                    //create your services
                    List<SeedKeyword> keywords = new List<SeedKeyword>();

                    AdGroupAdServicev200906 adService =
                        (AdGroupAdServicev200906)user.GetService(ApiServices.v200906.AdGroupAdService);
                    KeywordToolService keywordToolService =
                        (KeywordToolService)user.GetService(ApiServices.v13.KeywordToolService);
                    AdGroupServicev200906 adgroupService =
                        (AdGroupServicev200906)user.GetService(ApiServices.v200906.AdGroupService);
                    TrafficEstimatorService trafficEstimatorService =
                        (TrafficEstimatorService)user.GetService(ApiServices.v13.TrafficEstimatorService);

                    #endregion

                    #region Enumerate thru all the keywords by category

                    AdGroupv200906 newAdGroup = null;

                    foreach (
                        SiteCategory siteCategory in
                            DataRepository.SiteCategoryProvider.GetByAffiliateSiteRefId(AffiliateSiteRefId))
                    {
                        int adGroupCnt = 1;
                        //enumerate thru all the keywords
                        foreach (
                            KeywordUrLsDistinct keywordUrLsDistinct in
                                DataRepository.KeywordUrLsDistinctProvider.GetBySiteCategoryRefId(
                                    siteCategory.SiteCategoryRefId))
                        {
                            VList<KeywordDensity> keywordDensityList =
                                DataRepository.KeywordDensityProvider.GetURLKeywordDensity(keywordUrLsDistinct.Url,
                                                                                           MinKeywordDensity,
                                                                                           MaxKeywordDensity).
                                    FindAllDistinct("SiteContent");

                            int GroupAdCount = 0;

                            //check the avg keyword density
                            if (keywordDensityList.Count >= MinContentMatch)
                            {
                                if (adGroupCnt == 1)
                                {
                                    #region Ad AdGroup

                                    if (GroupAdCount >= MaxAdGroups)
                                        break;

                                    //Create an ad group by site category
                                    newAdGroup = new AdGroupv200906();
                                    newAdGroup.name = siteCategory.Name;

                                    newAdGroup.campaignId = newCampaign.id;
                                    newAdGroup.campaignIdSpecified = true;
                                    //newAdGroup.campaignName = newCampaign.name;

                                    // Optional: set the status of adgroup.
                                    newAdGroup.statusSpecified = true;
                                    newAdGroup.status = AdGroupStatus.ENABLED;

                                    // Optional: Create a Manual CPC Bid.
                                    ManualCPCAdGroupBids bids = new ManualCPCAdGroupBids();

                                    // Set the keyword content max cpc.
                                    bids.keywordContentMaxCpc = new Bid();

                                    Money kwdContentMaxCpc = new Money();
                                    kwdContentMaxCpc.microAmountSpecified = true;
                                    kwdContentMaxCpc.microAmount = KeywordMaxCpc.microAmount;
                                    bids.keywordContentMaxCpc.amount = kwdContentMaxCpc;

                                    // Set the keyword max cpc.
                                    bids.keywordMaxCpc = new Bid();
                                    Money kwdMaxCpc = new Money();
                                    kwdMaxCpc.microAmountSpecified = true;
                                    kwdMaxCpc.microAmount = KeywordMaxCpc.microAmount;
                                    bids.keywordMaxCpc.amount = kwdMaxCpc;

                                    // Set the manual bid to the adgroup.
                                    newAdGroup.bids = bids;

                                    AdGroupOperation adGroupOperation = new AdGroupOperation();
                                    adGroupOperation.operatorSpecified = true;
                                    adGroupOperation.@operator = AddGroupOperatorv200906.ADD;
                                    adGroupOperation.operand = newAdGroup;

                                    try
                                    {
                                        AdGroupReturnValue results =
                                            adgroupService.mutate(new AdGroupOperation[] { adGroupOperation });
                                        if (results != null && results.value != null && results.value.Length > 0)
                                        {
                                            newAdGroup.id = results.value[0].id;
                                            newAdGroup.idSpecified = true;
                                            Trace.TraceInformation(
                                                "New ad group with name = \"{0}\" and id = \"{1}\" was created.",
                                                results.value[0].name, results.value[0].id);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Trace.TraceError("Failed to create ad group. Exception says \"{0}\"", ex.Message);
                                    }

                                    adGroupCnt++;

                                    #endregion
                                }

                                Trace.TraceInformation(keywordUrLsDistinct.Url);

                                //Create an add for each product
                                //
                                // IMPORTANT: create an ad before adding keywords!  Else the
                                // minCpc will have a higher value.
                                TList<PpcAdTemplate> ppcAdTemplateList =
                                    DataRepository.PpcAdTemplateProvider.GetByPpcCampaignRefId(campaign.PpcCampaignRefId);
                                foreach (var ppcAdTemplate in ppcAdTemplateList)
                                {

                                    TextAdv200906 newTextAd = new TextAdv200906();
                                    Product prod =
                                        DataRepository.ProductProvider.GetByProductRefId(
                                            (Guid)keywordUrLsDistinct.ProductRefId);
                                    newTextAd.headline = StringUtils.ScrubProdName(prod.Name);

                                    while (newTextAd.headline.Length > 25)
                                    {
                                        // if one word longer than 25 chars
                                        if (newTextAd.headline.LastIndexOf(" ") < 0)
                                            continue;

                                        newTextAd.headline =
                                            newTextAd.headline.Substring(0, newTextAd.headline.LastIndexOf(" ")).
                                                Substring(
                                                0,
                                                newTextAd.headline.Substring(0, newTextAd.headline.LastIndexOf(" "))
                                                    .
                                                    LastIndexOf(" "));
                                    }

                                    newTextAd.description1 = ppcAdTemplate.AdLine1.Replace(KeywordToken,
                                                                                           keywordDensityList[0].Keywords).Replace(ProductNameToken, newTextAd.headline);
                                    newTextAd.description2 = ppcAdTemplate.AdLine2;

                                    //}

                                    newTextAd.displayUrl = DisplayUrl;
                                    newTextAd.url = keywordUrLsDistinct.Url;
                                    //don't add it yet, there is a check below to see if it meets criteria

                                    //SeedKeyword[] keywordsArray = new SeedKeyword[] { new SeedKeyword() };
                                    //keywordsArray = keywords.ToArray();

                                    // Associate this ad group with the newly created campaign.  Send
                                    // the request to add the new ad group.

                                    try
                                    {
                                        //we found a keyword that meets criteria so ad the new Ad.
                                        AdGroupAd adGroupAd = new AdGroupAd();
                                        adGroupAd.adGroupId = newAdGroup.id;
                                        adGroupAd.adGroupIdSpecified = true;
                                        adGroupAd.ad = newTextAd;

                                        AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation();
                                        adGroupAdOperation.operatorSpecified = true;
                                        adGroupAdOperation.@operator = AddGroupAdOperatorv200906.ADD;
                                        adGroupAdOperation.operand = adGroupAd;

                                        AdGroupAdReturnValue result = null;
                                        try
                                        {
                                            result = adService.mutate(new AdGroupAdOperation[] { adGroupAdOperation });

                                            if (result.value != null && result.value.Length > 0)
                                            {
                                                foreach (AdGroupAd tempAdGroupAd in result.value)
                                                {
                                                    Trace.TraceInformation(
                                                        String.Format(
                                                            "New text ad with headline = \"{0}\" and id = \"{1}\" was created.",
                                                            ((TextAdv200906)tempAdGroupAd.ad).headline,
                                                            tempAdGroupAd.ad.id));
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Trace.TraceError("Failed to create Ad(s). Exception says \"{0}\"",
                                                             ex.Message);
                                        }

                                        GroupAdCount++;
                                        Trace.TraceInformation("Text ad" + GroupAdCount + ": " + newTextAd.headline +
                                                               " Text Line1:" +
                                                               newTextAd.description1 + " Text Line2:" +
                                                               newTextAd.description2);

                                        //Trace.TraceInformation("Text ad: " + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2);
                                    }
                                    catch
                                    {
                                        //do nothing
                                        Trace.TraceError("***Text ad Failed:" + newTextAd.headline + " Text Line1:" +
                                                         newTextAd.description1 + " Text Line2:" +
                                                         newTextAd.description2);
                                    }

                                }

                                //Add the Product name as a whole phrase
                                AdGroupCriterionServicev200906 criterionService =
                                    (AdGroupCriterionServicev200906)
                                    user.GetService(ApiServices.v200906.AdGroupCriterionService);

                                foreach (KeywordDensity kd in keywordDensityList)
                                {
                                    try
                                    {
                                        Keywordv200906 newKeyword = new Keywordv200906();
                                        newKeyword.matchTypeSpecified = true;
                                        newKeyword.matchType =
                                            com.google.api.adwords.v200906.AdGroupCriterionService.KeywordMatchType.
                                                BROAD;
                                        newKeyword.text = kd.Keywords;

                                        BiddableAdGroupCriterion criterion = new BiddableAdGroupCriterion();
                                        criterion.adGroupId = newAdGroup.id;
                                        criterion.adGroupIdSpecified = true;
                                        criterion.criterion = newKeyword;
                                        criterion.destinationUrl = kd.Url;

                                        //TODO: Use the Traffic Estimator to determine the
                                        // the maxCpc to use
                                        //newKeyword.maxCpc = KeywordMaxCpc;
                                        //newKeyword.maxCpcSpecified = true;

                                        var adGroupCriterionBids =
                                            new com.google.api.adwords.v200906.AdGroupCriterionService.
                                                ManualCPCAdGroupCriterionBids();

                                        adGroupCriterionBids.maxCpc =
                                            new com.google.api.adwords.v200906.AdGroupCriterionService.Bid();
                                        adGroupCriterionBids.maxCpc.amount = KeywordMaxCpc;
                                        criterion.bids = adGroupCriterionBids;

                                        AdGroupCriterionOperation adGroupCriterionOperation =
                                            new AdGroupCriterionOperation();
                                        adGroupCriterionOperation.@operator =
                                            com.google.api.adwords.v200906.AdGroupCriterionService.Operator.ADD;
                                        adGroupCriterionOperation.operatorSpecified = true;
                                        adGroupCriterionOperation.operand = criterion;

                                        try
                                        {
                                            AdGroupCriterionReturnValue results =
                                                criterionService.mutate(new AdGroupCriterionOperation[] { adGroupCriterionOperation });
                                            if (results != null && results.value != null && results.value.Length > 0)
                                            {
                                                Keywordv200906 result = results.value[0].criterion as Keywordv200906;
                                                Trace.TraceInformation(
                                                    String.Format(
                                                        "New keyword with text = \"{0}\" and id = \"{1}\" was created.",
                                                        result.text, result.id));
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Trace.TraceError(
                                                String.Format(
                                                    "Failed to create keyword at Ad group level. Exception says \"{0}\"",
                                                    ex.Message));
                                        }

                                    }
                                    catch
                                    {
                                        //do nothing
                                        Trace.TraceError("***Add Criteria Failed: Keyword" + kd.Keywords);
                                    }
                                }

                                if (GroupAdCount >= MaxAdGroups)
                                    break;
                            }
                        }
                    }

                    #endregion
                }

                #region Check api usage
                // check api usage
                ApiUsage apiUsage = new ApiUsage();
                APIQuotaValues aPIQuotaValues = apiUsage.GetApiUsage(UseSandbox);

                Trace.TraceInformation("FreeQuotaUsed:" + aPIQuotaValues.FreeQuotaUsed.ToString() + " FreeUnitsRemaining:" + aPIQuotaValues.FreeUnitsRemaining.ToString() + " SysDefinesQuotaCap:" + aPIQuotaValues.SysDefinesQuotaCap.ToString() + " TotalUsed:" + aPIQuotaValues.TotalUsed.ToString());

                #endregion

                #region Log everything created
                //AdGroup[] adGroups = adgroupService.getAllAdGroups(campaignId);

                //foreach (AdGroup adGroup in adGroups)
                //{
                //    Trace.TraceInformation("Ad group: " + adGroup.name);

                //    Ad[] ads = adService.getAllAds(new long[] { adGroup.id });

                //    foreach (Ad ad in ads)
                //    {
                //        if (ad is TextAd)
                //        {
                //            TextAd textAd = (TextAd)ad;
                //            Trace.TraceInformation("Text ad: " + textAd.headline + " Text Line1:" + textAd.description1 + " Text Line2:" + textAd.description2);
                //        }
                //    }
                //}

                #endregion

            }
            catch (Exception ex)
            {
                Trace.TraceError("Error:" + ex.Message);
                throw ex;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which ad groups are
        /// added.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            // Get the AdGroupService.
            AdGroupService adGroupService =
                (AdGroupService)user.GetService(AdWordsService.v201506.AdGroupService);

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

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

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

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

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

                adGroup.biddingStrategyConfiguration = biddingConfig;

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

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

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

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

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

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

                operations.Add(operation);
            }

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

                // Display the results.
                if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                {
                    foreach (AdGroup newAdGroup in retVal.value)
                    {
                        Console.WriteLine("Ad group with id = '{0}' and name = '{1}' was created.",
                                          newAdGroup.id, newAdGroup.name);
                    }
                }
                else
                {
                    Console.WriteLine("No ad groups were created.");
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to create ad groups.", e);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad groups to which placements are
        /// added.</param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            // Get the MutateJobService.
            MutateJobService mutateJobService = (MutateJobService)user.GetService(
                AdWordsService.v201502.MutateJobService);

            const int    RETRY_INTERVAL   = 30;
            const int    RETRIES_COUNT    = 30;
            const int    PLACEMENT_NUMBER = 100;
            const string INDEX_REGEX      = "operations\\[(\\d+)\\].operand";

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

            // Create AdGroupCriterionOperation to add placements.
            for (int i = 0; i < PLACEMENT_NUMBER; i++)
            {
                Placement placement = new Placement();
                placement.url = "http://mars.google.com/" + i.ToString();

                BiddableAdGroupCriterion criterion = new BiddableAdGroupCriterion();
                criterion.adGroupId = adGroupId;
                criterion.criterion = placement;

                AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation();
                adGroupCriterionOperation.@operator = Operator.ADD;
                adGroupCriterionOperation.operand   = criterion;

                operations.Add(adGroupCriterionOperation);
            }

            BulkMutateJobPolicy policy = new BulkMutateJobPolicy();

            // You can specify up to 3 job IDs that must successfully complete before
            // this job can be processed.
            policy.prerequisiteJobIds = new long[] {};

            SimpleMutateJob job = mutateJobService.mutate(operations.ToArray(), policy);

            // Wait for the job to complete.
            bool completed  = false;
            int  retryCount = 0;

            Console.WriteLine("Retrieving job status...");

            while (completed == false && retryCount < RETRIES_COUNT)
            {
                BulkMutateJobSelector selector = new BulkMutateJobSelector();
                selector.jobIds = new long[] { job.id };

                try {
                    Job[] allJobs = mutateJobService.get(selector);
                    if (allJobs != null && allJobs.Length > 0)
                    {
                        job = (SimpleMutateJob)allJobs[0];
                        if (job.status == BasicJobStatus.COMPLETED || job.status == BasicJobStatus.FAILED)
                        {
                            completed = true;
                            break;
                        }
                        else
                        {
                            Console.WriteLine("{0}: Current status is {1}, waiting {2} seconds to retry...",
                                              retryCount, job.status, RETRY_INTERVAL);
                            Thread.Sleep(RETRY_INTERVAL * 1000);
                            retryCount++;
                        }
                    }
                } catch (Exception e) {
                    throw new System.ApplicationException(string.Format("Failed to fetch simple mutate " +
                                                                        "job with id = {0}.", job.id), e);
                }
            }

            if (job.status == BasicJobStatus.COMPLETED)
            {
                // Handle cases where the job completed.

                // Create the job selector.
                BulkMutateJobSelector selector = new BulkMutateJobSelector();
                selector.jobIds = new long[] { job.id };

                // Get the job results.
                JobResult jobResult = mutateJobService.getResult(selector);
                if (jobResult != null)
                {
                    SimpleMutateResult results = (SimpleMutateResult)jobResult.Item;
                    if (results != null)
                    {
                        // Display the results.
                        if (results.results != null)
                        {
                            for (int i = 0; i < results.results.Length; i++)
                            {
                                Operand operand = results.results[i];
                                Console.WriteLine("Operation {0} - {1}", i, (operand.Item is PlaceHolder) ?
                                                  "FAILED" : "SUCCEEDED");
                            }
                        }

                        // Display the errors.
                        if (results.errors != null)
                        {
                            foreach (ApiError apiError in results.errors)
                            {
                                Match  match = Regex.Match(apiError.fieldPath, INDEX_REGEX, RegexOptions.IgnoreCase);
                                string index = (match.Success)? match.Groups[1].Value : "???";
                                Console.WriteLine("Operation index {0} failed due to reason: '{1}', " +
                                                  "trigger: '{2}'", index, apiError.errorString, apiError.trigger);
                            }
                        }
                    }
                }
                Console.WriteLine("Job completed successfully!");
            }
            else if (job.status == BasicJobStatus.FAILED)
            {
                // Handle the cases where job failed.
                Console.WriteLine("Job failed with reason: " + job.failureReason);
            }
            else if (job.status == BasicJobStatus.PROCESSING || job.status == BasicJobStatus.PENDING)
            {
                // Handle the cases where job didn't complete after wait period.
                Console.WriteLine("Job did not complete in {0} secconds.", RETRY_INTERVAL * RETRIES_COUNT);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">The ad group to which product partition is
        /// added.</param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            using (AdGroupCriterionService adGroupCriterionService =
                       (AdGroupCriterionService)user.GetService(
                           AdWordsService.v201710.AdGroupCriterionService)) {
                // Build a new ProductPartitionTree using the ad group's current set of criteria.
                ProductPartitionTree partitionTree =
                    ProductPartitionTree.DownloadAdGroupTree(user, adGroupId);

                Console.WriteLine("Original tree: {0}", partitionTree);

                // Clear out any existing criteria.
                ProductPartitionNode rootNode = partitionTree.Root.RemoveAllChildren();

                // Make the root node a subdivision.
                rootNode = rootNode.AsSubdivision();

                // Add a unit node for condition = NEW.
                ProductPartitionNode newConditionNode = rootNode.AddChild(
                    ProductDimensions.CreateCanonicalCondition(ProductCanonicalConditionCondition.NEW));
                newConditionNode.AsBiddableUnit().CpcBid = 200000;

                ProductPartitionNode usedConditionNode = rootNode.AddChild(
                    ProductDimensions.CreateCanonicalCondition(ProductCanonicalConditionCondition.USED));
                usedConditionNode.AsBiddableUnit().CpcBid = 100000;

                // Add a subdivision node for condition = null (everything else).
                ProductPartitionNode otherConditionNode =
                    rootNode.AddChild(ProductDimensions.CreateCanonicalCondition()).AsSubdivision();

                // Add a unit node under condition = null for brand = "CoolBrand".
                ProductPartitionNode coolBrandNode = otherConditionNode.AddChild(
                    ProductDimensions.CreateBrand("CoolBrand"));
                coolBrandNode.AsBiddableUnit().CpcBid = 900000L;

                // Add a unit node under condition = null for brand = "CheapBrand".
                ProductPartitionNode cheapBrandNode = otherConditionNode.AddChild(
                    ProductDimensions.CreateBrand("CheapBrand"));
                cheapBrandNode.AsBiddableUnit().CpcBid = 10000L;

                // Add a subdivision node under condition = null for brand = null (everything else).
                ProductPartitionNode otherBrandNode = otherConditionNode.AddChild(
                    ProductDimensions.CreateBrand(null)).AsSubdivision();

                // Add unit nodes under condition = null/brand = null.
                // The value for each bidding category is a fixed ID for a specific
                // category. You can retrieve IDs for categories from the ConstantDataService.
                // See the 'GetProductCategoryTaxonomy' example for more details.

                // Add a unit node under condition = null/brand = null for product type
                // level 1 = 'Luggage & Bags'.
                ProductPartitionNode luggageAndBagNode = otherBrandNode.AddChild(
                    ProductDimensions.CreateBiddingCategory(ProductDimensionType.BIDDING_CATEGORY_L1,
                                                            -5914235892932915235L));
                luggageAndBagNode.AsBiddableUnit().CpcBid = 750000L;

                // Add a unit node under condition = null/brand = null for product type
                // level 1 = null (everything else).
                ProductPartitionNode everythingElseNode = otherBrandNode.AddChild(
                    ProductDimensions.CreateBiddingCategory(ProductDimensionType.BIDDING_CATEGORY_L1));
                everythingElseNode.AsBiddableUnit().CpcBid = 110000L;

                try {
                    // Make the mutate request, using the operations returned by the ProductPartitionTree.
                    AdGroupCriterionOperation[] mutateOperations = partitionTree.GetMutateOperations();

                    if (mutateOperations.Length == 0)
                    {
                        Console.WriteLine("Skipping the mutate call because the original tree and the " +
                                          "current tree are logically identical.");
                    }
                    else
                    {
                        adGroupCriterionService.mutate(mutateOperations);
                    }

                    // The request was successful, so create a new ProductPartitionTree based on the updated
                    // state of the ad group.
                    partitionTree = ProductPartitionTree.DownloadAdGroupTree(user, adGroupId);

                    Console.WriteLine("Final tree: {0}", partitionTree);
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to set shopping product partition.", e);
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Updates the campaign DSA setting to add DSA pagefeeds.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">The Campaign ID.</param>
        /// <param name="feedId">The page feed ID.</param>
        private static void UpdateCampaignDsaSetting(AdWordsUser user, long campaignId, long feedId)
        {
            using (CampaignService campaignService =
                       (CampaignService)user.GetService(AdWordsService.v201806.CampaignService))
            {
                Selector selector = new Selector()
                {
                    fields = new string[]
                    {
                        Campaign.Fields.Id,
                        Campaign.Fields.Settings
                    },
                    predicates = new Predicate[]
                    {
                        Predicate.Equals(Campaign.Fields.Id, campaignId)
                    },
                    paging = Paging.Default
                };

                CampaignPage page = campaignService.get(selector);

                if (page == null || page.entries == null || page.entries.Length == 0)
                {
                    throw new System.ApplicationException(
                              string.Format("Failed to retrieve campaign with ID = {0}.", campaignId));
                }

                Campaign campaign = page.entries[0];

                if (campaign.settings == null)
                {
                    throw new System.ApplicationException("This is not a DSA campaign.");
                }

                DynamicSearchAdsSetting dsaSetting = null;
                Setting[] campaignSettings         = campaign.settings;

                for (int i = 0; i < campaign.settings.Length; i++)
                {
                    Setting setting = campaignSettings[i];
                    if (setting is DynamicSearchAdsSetting)
                    {
                        dsaSetting = (DynamicSearchAdsSetting)setting;
                        break;
                    }
                }

                if (dsaSetting == null)
                {
                    throw new System.ApplicationException("This is not a DSA campaign.");
                }

                // Use a page feed to specify precisely which URLs to use with your
                // Dynamic Search Ads.
                dsaSetting.pageFeed = new PageFeed()
                {
                    feedIds = new long[]
                    {
                        feedId
                    },
                };

                // Optional: Specify whether only the supplied URLs should be used with your
                // Dynamic Search Ads.
                dsaSetting.useSuppliedUrlsOnly = true;

                Campaign campaignToUpdate = new Campaign
                {
                    id       = campaignId,
                    settings = campaignSettings
                };

                CampaignOperation operation = new CampaignOperation
                {
                    operand   = campaignToUpdate,
                    @operator = Operator.SET
                };

                try
                {
                    CampaignReturnValue retval = campaignService.mutate(new CampaignOperation[]
                    {
                        operation
                    });
                    Campaign updatedCampaign = retval.value[0];
                    Console.WriteLine(
                        "DSA page feed for campaign ID '{0}' was updated with feed ID '{1}'.",
                        updatedCampaign.id, feedId);
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to set page feed for campaign.",
                                                          e);
                }
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">ID of the ad group to which ad is added.
        /// </param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            using (AdGroupAdService adGroupAdService =
                       (AdGroupAdService)user.GetService(AdWordsService.v201802.AdGroupAdService))
            {
                // Create the expanded text ad.
                ExpandedTextAd expandedTextAd = new ExpandedTextAd()
                {
                    headlinePart1 = "Luxury Cruise to Mars",
                    headlinePart2 = "Visit the Red Planet in style.",
                    description   = "Low-gravity fun for everyone!",
                };

                // Specify a tracking URL for 3rd party tracking provider. You may
                // specify one at customer, campaign, ad group, ad, criterion or
                // feed item levels.
                expandedTextAd.trackingUrlTemplate =
                    "http://tracker.example.com/?season={_season}&promocode={_promocode}&u={lpurl}";

                // Since your tracking URL has two custom parameters, provide their
                // values too. This can be provided at campaign, ad group, ad, criterion
                // or feed item levels.
                CustomParameter seasonParameter = new CustomParameter
                {
                    key   = "season",
                    value = "christmas"
                };

                CustomParameter promoCodeParameter = new CustomParameter
                {
                    key   = "promocode",
                    value = "NYC123"
                };

                expandedTextAd.urlCustomParameters = new CustomParameters
                {
                    parameters = new CustomParameter[]
                    {
                        seasonParameter,
                        promoCodeParameter
                    }
                };

                // Specify a list of final URLs. This field cannot be set if URL field is
                // set. This may be specified at ad, criterion and feed item levels.
                expandedTextAd.finalUrls = new string[]
                {
                    "http://www.example.com/cruise/space/",
                    "http://www.example.com/locations/mars/"
                };

                // Specify a list of final mobile URLs. This field cannot be set if URL
                // field is set, or finalUrls is unset. This may be specified at ad,
                // criterion and feed item levels.
                expandedTextAd.finalMobileUrls = new string[]
                {
                    "http://mobile.example.com/cruise/space/",
                    "http://mobile.example.com/locations/mars/"
                };

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

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

                // Create the operation.
                AdGroupAdOperation operation = new AdGroupAdOperation
                {
                    @operator = Operator.ADD,
                    operand   = adGroupAd
                };

                AdGroupAdReturnValue retVal = null;

                try
                {
                    // Create the ads.
                    retVal = adGroupAdService.mutate(new AdGroupAdOperation[]
                    {
                        operation
                    });

                    // Display the results.
                    if (retVal != null && retVal.value != null)
                    {
                        ExpandedTextAd newExpandedTextAd = retVal.value[0].ad as ExpandedTextAd;

                        Console.WriteLine(
                            "Expanded text ad with ID '{0}' and headline '{1} - {2}' was added.",
                            newExpandedTextAd.id, newExpandedTextAd.headlinePart1,
                            newExpandedTextAd.headlinePart2);

                        Console.WriteLine("Upgraded URL properties:");

                        Console.WriteLine("  Final URLs: {0}",
                                          string.Join(", ", newExpandedTextAd.finalUrls));
                        Console.WriteLine("  Final Mobile URLs: {0}",
                                          string.Join(", ", newExpandedTextAd.finalMobileUrls));
                        Console.WriteLine("  Tracking URL template: {0}",
                                          newExpandedTextAd.trackingUrlTemplate);

                        List <string> parameters = new List <string>();
                        foreach (CustomParameter customParam in newExpandedTextAd
                                 .urlCustomParameters.parameters)
                        {
                            parameters.Add(string.Format("{0}={1}", customParam.key,
                                                         customParam.value));
                        }

                        Console.WriteLine("  Custom parameters: {0}",
                                          string.Join(", ", parameters.ToArray()));
                    }
                    else
                    {
                        Console.WriteLine("No expanded text ads were created.");
                    }
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to create expanded text ad.", e);
                }
            }
        }
            /// <summary>
            /// Main method for the thread.
            /// </summary>
            /// <param name="obj">The thread parameter.</param>
            public void Run(Object obj)
            {
                // Create the operations.
                List <AdGroupCriterionOperation> operations = new List <AdGroupCriterionOperation>();

                for (int j = 0; j < NUM_KEYWORDS; j++)
                {
                    // Create the keyword.
                    Keyword keyword = new Keyword();
                    keyword.text      = "mars cruise thread " + threadIndex.ToString() + " seed " + j.ToString();
                    keyword.matchType = KeywordMatchType.BROAD;

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

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

                    operations.Add(keywordOperation);
                }

                // Get the AdGroupCriterionService. This should be done within the
                // thread, since a service can only handle one outgoing HTTP request
                // at a time.
                using (AdGroupCriterionService adGroupCriterionService =
                           (AdGroupCriterionService)user.GetService(
                               AdWordsService.v201710.AdGroupCriterionService)) {
                    adGroupCriterionService.RequestHeader.validateOnly = true;
                    int       retryCount  = 0;
                    const int NUM_RETRIES = 3;
                    try {
                        while (retryCount < NUM_RETRIES)
                        {
                            try {
                                // Validate the keywords.
                                adGroupCriterionService.mutate(operations.ToArray());
                                break;
                            } catch (AdWordsApiException e) {
                                // Handle API errors.
                                ApiException innerException = e.ApiException as ApiException;
                                if (innerException == null)
                                {
                                    throw new Exception("Failed to retrieve ApiError. See inner exception " +
                                                        "for more details.", e);
                                }
                                foreach (ApiError apiError in innerException.errors)
                                {
                                    if (!(apiError is RateExceededError))
                                    {
                                        // Rethrow any errors other than RateExceededError.
                                        throw;
                                    }
                                    // Handle rate exceeded errors.
                                    RateExceededError rateExceededError = (RateExceededError)apiError;
                                    Console.WriteLine("Got Rate exceeded error - rate name = '{0}', " +
                                                      "scope = '{1}', retry After {2} seconds.", rateExceededError.rateScope,
                                                      rateExceededError.rateName, rateExceededError.retryAfterSeconds);
                                    Thread.Sleep(rateExceededError.retryAfterSeconds * 1000);
                                    retryCount = retryCount + 1;
                                }
                            } finally {
                                if (retryCount == NUM_RETRIES)
                                {
                                    throw new Exception(String.Format("Could not recover after making {0} attempts.",
                                                                      retryCount));
                                }
                            }
                        }
                    } catch (Exception e) {
                        throw new System.ApplicationException("Failed to validate keywords.", e);
                    }
                }
            }
Ejemplo n.º 8
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group to which placements are added.
        /// </param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(AdWordsService.v201502.AdGroupCriterionService);

            // Create the placement.
            Placement placement1 = new Placement();

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

            // Create biddable ad group criterion.
            AdGroupCriterion placementCriterion1 = new BiddableAdGroupCriterion();

            placementCriterion1.adGroupId = adGroupId;
            placementCriterion1.criterion = placement1;

            // Create the placement.
            Placement placement2 = new Placement();

            placement2.url = "http://venus.google.com";

            // Create biddable ad group criterion.
            AdGroupCriterion placementCriterion2 = new BiddableAdGroupCriterion();

            placementCriterion2.adGroupId = adGroupId;
            placementCriterion2.criterion = placement2;

            // Create the operations.
            AdGroupCriterionOperation placementOperation1 = new AdGroupCriterionOperation();

            placementOperation1.@operator = Operator.ADD;
            placementOperation1.operand   = placementCriterion1;

            AdGroupCriterionOperation placementOperation2 = new AdGroupCriterionOperation();

            placementOperation2.@operator = Operator.ADD;
            placementOperation2.operand   = placementCriterion2;

            try {
                // Create the placements.
                AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(
                    new AdGroupCriterionOperation[] { placementOperation1, placementOperation2 });

                // 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 Placement) { ... }
                        //
                        // to identify the criterion type.
                        Console.WriteLine("Placement with ad group id = '{0}, placement id = '{1}, url = " +
                                          "'{2}' was created.", adGroupCriterion.adGroupId,
                                          adGroupCriterion.criterion.id, (adGroupCriterion.criterion as Placement).url);
                    }
                }
                else
                {
                    Console.WriteLine("No placements were added.");
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to create placements.", e);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which targeting criteria
        /// are added.</param>
        /// <param name="feedId">ID of a feed that has been configured for location
        /// targeting, meaning it has an ENABLED FeedMapping with criterionType of
        /// 77. Feeds linked to a GMB account automatically have this FeedMapping.
        /// If you don't have such a feed, set this value to null.</param>
        public void Run(AdWordsUser user, long campaignId, long?feedId)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionService campaignCriterionService =
                (CampaignCriterionService)user.GetService(
                    AdWordsService.v201601.CampaignCriterionService);

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

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

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

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

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

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

            locationGroupTier3.matchingFunction = tier3MatchingFunction;

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

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

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

                criteria.Add(radiusLocationGroup);
            }

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

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

                operations.Add(operation);
            }

            // Add a negative campaign criterion.

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

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

            operations.Add(negativeCriterionOperation);

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

                if (retVal != null && retVal.value != null)
                {
                    // Display campaign targets.
                    foreach (CampaignCriterion criterion in retVal.value)
                    {
                        Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                                          " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
                    }
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to set Campaign criteria.", e);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            using (CustomerSyncService customerSyncService =
                       (CustomerSyncService)user.GetService(AdWordsService.v201705.
                                                            CustomerSyncService)) {
                // The date time string should be of the form  yyyyMMdd HHmmss zzz
                string minDateTime = DateTime.Now.AddDays(-1).ToUniversalTime().ToString(
                    "yyyyMMdd HHmmss") + " UTC";
                string maxDateTime = DateTime.Now.ToUniversalTime().ToString("yyyyMMdd HHmmss") +
                                     " UTC";

                // Create date time range.
                DateTimeRange dateTimeRange = new DateTimeRange();
                dateTimeRange.min = minDateTime;
                dateTimeRange.max = maxDateTime;

                try {
                    // Create the selector.
                    CustomerSyncSelector selector = new CustomerSyncSelector();
                    selector.dateTimeRange = dateTimeRange;
                    selector.campaignIds   = GetAllCampaignIds(user);

                    // Get all account changes for campaign.
                    CustomerChangeData accountChanges = customerSyncService.get(selector);

                    // Display the changes.
                    if (accountChanges != null && accountChanges.changedCampaigns != null)
                    {
                        Console.WriteLine("Displaying changes up to: {0}",
                                          accountChanges.lastChangeTimestamp);
                        foreach (CampaignChangeData campaignChanges in accountChanges.changedCampaigns)
                        {
                            Console.WriteLine("Campaign with id \"{0}\" was changed:",
                                              campaignChanges.campaignId);
                            Console.WriteLine("  Campaign changed status: {0}",
                                              campaignChanges.campaignChangeStatus);
                            if (campaignChanges.campaignChangeStatus != ChangeStatus.NEW)
                            {
                                Console.WriteLine("  Added campaign criteria: {0}",
                                                  GetFormattedList(campaignChanges.addedCampaignCriteria));
                                Console.WriteLine("  Removed campaign criteria: {0}",
                                                  GetFormattedList(campaignChanges.removedCampaignCriteria));

                                if (campaignChanges.changedAdGroups != null)
                                {
                                    foreach (AdGroupChangeData adGroupChanges in campaignChanges.changedAdGroups)
                                    {
                                        Console.WriteLine("  Ad group with id \"{0}\" was changed:",
                                                          adGroupChanges.adGroupId);
                                        Console.WriteLine("    Ad group changed status: {0}",
                                                          adGroupChanges.adGroupChangeStatus);
                                        if (adGroupChanges.adGroupChangeStatus != ChangeStatus.NEW)
                                        {
                                            Console.WriteLine("    Ads changed: {0}",
                                                              GetFormattedList(adGroupChanges.changedAds));
                                            Console.WriteLine("    Criteria changed: {0}",
                                                              GetFormattedList(adGroupChanges.changedCriteria));
                                            Console.WriteLine("    Criteria removed: {0}",
                                                              GetFormattedList(adGroupChanges.removedCriteria));
                                        }
                                    }
                                }
                            }
                            Console.WriteLine();
                        }
                    }
                    else
                    {
                        Console.WriteLine("No account changes were found.");
                    }
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to get account changes.", e);
                }
            }
        }
Ejemplo n.º 11
0
        /// <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.v201708.AdGroupCriterionService)) {
                // Since we are not updating any keyword-specific fields, it is enough to
                // create a criterion object.
                Criterion criterion = new Criterion();
                criterion.id = keywordId;

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

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

                biddableAdGroupCriterion.biddingStrategyConfiguration = biddingConfig;

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

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

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

                        Console.WriteLine("Keyword with ad group id = '{0}', id = '{1}' was updated with " +
                                          "bid amount = '{2}' micros.", adGroupCriterion.adGroupId,
                                          adGroupCriterion.criterion.id, bidAmount);
                    }
                    else
                    {
                        Console.WriteLine("No keyword was updated.");
                    }
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to update keyword.", e);
                }
            }
        }
Ejemplo n.º 12
0
        /// <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)
        {
            // Get the AdGroupAdService.
            AdGroupAdService service =
                (AdGroupAdService)user.GetService(AdWordsService.v201402.AdGroupAdService);

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

            for (int i = 0; i < NUM_ITEMS; i++)
            {
                // Create the text ad.
                TextAd textAd = new TextAd();
                textAd.headline     = "Luxury Cruise to Mars";
                textAd.description1 = "Visit the Red Planet in style.";
                textAd.description2 = "Low-gravity fun for everyone!";
                textAd.displayUrl   = "www.example.com";
                textAd.url          = "http://www.example.com/" + i;

                AdGroupAd textAdGroupAd = new AdGroupAd();
                textAdGroupAd.adGroupId = adGroupId;
                textAdGroupAd.ad        = textAd;

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

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

                operations.Add(operation);
            }

            AdGroupAdReturnValue retVal = null;

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

                // Display the results.
                if (retVal != null && retVal.value != null)
                {
                    // If you are adding multiple type of Ads, then you may need to check
                    // for
                    //
                    // if (adGroupAd.ad is TextAd) { ... }
                    //
                    // to identify the ad type.
                    foreach (AdGroupAd adGroupAd in retVal.value)
                    {
                        Console.WriteLine("New text ad with id = \"{0}\" and displayUrl = \"{1}\" was created.",
                                          adGroupAd.ad.id, adGroupAd.ad.displayUrl);
                    }
                }
                else
                {
                    Console.WriteLine("No text ads were created.");
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to create text ad.", ex);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign for which bid simulations are
        /// retrieved.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            // Get the DataService.
            DataService dataService = (DataService)user.GetService(AdWordsService.v201605.DataService);


            // Create selector.
            Selector selector = new Selector()
            {
                fields = new string[] {
                    CriterionBidLandscape.Fields.CampaignId,
                    CriterionBidLandscape.Fields.CriterionId,
                    CriterionBidLandscape.Fields.StartDate,
                    CriterionBidLandscape.Fields.EndDate,
                    BidLandscapeLandscapePoint.Fields.LocalClicks,
                    BidLandscapeLandscapePoint.Fields.LocalCost,
                    BidLandscapeLandscapePoint.Fields.LocalImpressions,
                    BidLandscapeLandscapePoint.Fields.TotalLocalClicks,
                    BidLandscapeLandscapePoint.Fields.TotalLocalCost,
                    BidLandscapeLandscapePoint.Fields.TotalLocalImpressions,
                    BidLandscapeLandscapePoint.Fields.RequiredBudget,
                    BidLandscapeLandscapePoint.Fields.BidModifier,
                },
                predicates = new Predicate[] {
                    Predicate.Equals(CriterionBidLandscape.Fields.CampaignId, campaignId)
                },
                paging = Paging.Default
            };

            int landscapePointsInLastResponse = 0;
            int landscapePointsFound          = 0;

            try {
                CriterionBidLandscapePage page = null;

                do
                {
                    // When retrieving bid landscape, page.totalNumEntities cannot be used to determine
                    // if there are more entries, since it shows only the total number of bid landscapes
                    // and not the number of bid landscape points. So you need to iterate until you no
                    // longer get back any bid landscapes.

                    // Get bid landscape for campaign.
                    page = dataService.getCampaignCriterionBidLandscape(selector);
                    landscapePointsInLastResponse = 0;

                    if (page != null && page.entries != null)
                    {
                        foreach (CriterionBidLandscape bidLandscape in page.entries)
                        {
                            Console.WriteLine("Found campaign-level criterion bid modifier landscapes for" +
                                              " criterion with ID {0}, start date '{1}', end date '{2}', and" +
                                              " landscape points:",
                                              bidLandscape.criterionId,
                                              bidLandscape.startDate,
                                              bidLandscape.endDate
                                              );

                            foreach (BidLandscapeLandscapePoint point in bidLandscape.landscapePoints)
                            {
                                Console.WriteLine("- bid modifier: {0:0.00} => clicks: {1}, cost: {2}, " +
                                                  "impressions: {3}, total clicks: {4}, total cost: {5}, " +
                                                  "total impressions: {6}, and required budget: {7}",
                                                  point.bidModifier, point.clicks, point.cost.microAmount,
                                                  point.impressions, point.totalLocalClicks, point.totalLocalCost.microAmount,
                                                  point.totalLocalImpressions, point.requiredBudget.microAmount);
                                landscapePointsInLastResponse++;
                                landscapePointsFound++;
                            }
                        }
                    }
                    // Offset by the number of landscape points, NOT the number
                    // of entries (bid landscapes) in the last response.
                    selector.paging.IncreaseOffsetBy(landscapePointsInLastResponse);
                } while (landscapePointsInLastResponse > 0);
                Console.WriteLine("Number of bid landscape points found: {0}",
                                  landscapePointsFound);
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to get campaign bid landscapes.", e);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group that contains the criterion.
        /// </param>
        /// <param name="criterionId">Id of the keyword for which the ad
        /// parameters are set.</param>
        public void Run(AdWordsUser user, long adGroupId, long criterionId)
        {
            using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(
                       AdWordsService.v201806.AdGroupAdService))
                using (AdParamService adParamService = (AdParamService)user.GetService(
                           AdWordsService.v201806.AdParamService)) {
                    // Create the expanded text ad.
                    ExpandedTextAd expandedTextAd = new ExpandedTextAd {
                        headlinePart1 = "Mars Cruises",
                        headlinePart2 = "Low-gravity fun for {param1:cheap}.",
                        description   = "Only {param2:a few} seats left!",
                        finalUrls     = new string[] { "http://www.example.com" }
                    };

                    AdGroupAd adOperand = new AdGroupAd {
                        adGroupId = adGroupId,
                        status    = AdGroupAdStatus.ENABLED,
                        ad        = expandedTextAd
                    };

                    // Create the operation.
                    AdGroupAdOperation adOperation = new AdGroupAdOperation {
                        operand   = adOperand,
                        @operator = Operator.ADD
                    };


                    // Create the text ad.
                    AdGroupAdReturnValue retVal = adGroupAdService.mutate(
                        new AdGroupAdOperation[] { adOperation });

                    // Display the results.
                    if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                    {
                        Console.WriteLine("Expanded text ad with id ='{0}' was successfully added.",
                                          retVal.value[0].ad.id);
                    }
                    else
                    {
                        throw new System.ApplicationException("Failed to create expanded text ads.");
                    }

                    // Create the ad param for price.
                    AdParam priceParam = new AdParam {
                        adGroupId     = adGroupId,
                        criterionId   = criterionId,
                        paramIndex    = 1,
                        insertionText = "$100"
                    };

                    // Create the ad param for seats.
                    AdParam seatParam = new AdParam {
                        adGroupId     = adGroupId,
                        criterionId   = criterionId,
                        paramIndex    = 2,
                        insertionText = "50"
                    };

                    // Create the operations.
                    AdParamOperation priceOperation = new AdParamOperation {
                        @operator = Operator.SET,
                        operand   = priceParam
                    };

                    AdParamOperation seatOperation = new AdParamOperation {
                        @operator = Operator.SET,
                        operand   = seatParam
                    };

                    try {
                        // Set the ad parameters.
                        AdParam[] newAdParams = adParamService.mutate(new AdParamOperation[]
                                                                      { priceOperation, seatOperation });

                        // Display the results.
                        if (newAdParams != null)
                        {
                            Console.WriteLine("Ad parameters were successfully updated.");
                        }
                        else
                        {
                            Console.WriteLine("No ad parameters were set.");
                        }
                    } catch (Exception e) {
                        throw new System.ApplicationException("Failed to set ad parameters.", e);
                    }
                }
        }
        /// <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 campaignId)
        {
            // Get the AdGroupAdService.
            AdGroupBidModifierService adGroupBidModifierService =
                (AdGroupBidModifierService)user.GetService(
                    AdWordsService.v201502.AdGroupBidModifierService);

            const int PAGE_SIZE = 500;

            // Get all ad group bid modifiers for the campaign.
            Selector selector = new Selector();

            selector.fields = new String[] { "CampaignId", "AdGroupId", "BidModifier", "BidModifierSource",
                                             "CriteriaType", "Id" };

            Predicate predicate = new Predicate();

            predicate.field     = "CampaignId";
            predicate.@operator = PredicateOperator.EQUALS;
            predicate.values    = new string[] { campaignId.ToString() };
            selector.predicates = new Predicate[] { predicate };

            // Set the selector paging.
            selector.paging = new Paging();

            int offset   = 0;
            int pageSize = PAGE_SIZE;

            AdGroupBidModifierPage page = new AdGroupBidModifierPage();

            try {
                do
                {
                    selector.paging.startIndex    = offset;
                    selector.paging.numberResults = pageSize;

                    // Get the campaigns.
                    page = adGroupBidModifierService.get(selector);

                    // Display the results.
                    if (page != null && page.entries != null)
                    {
                        int i = offset;
                        foreach (AdGroupBidModifier adGroupBidModifier in page.entries)
                        {
                            string bidModifier = (adGroupBidModifier.bidModifierSpecified)?
                                                 adGroupBidModifier.bidModifier.ToString() : "UNSET";
                            Console.WriteLine("{0}) Campaign ID {1}, AdGroup ID {2}, Criterion ID {3} has " +
                                              "ad group level modifier: {4} and source = {5}.",
                                              i + 1, adGroupBidModifier.campaignId,
                                              adGroupBidModifier.adGroupId, adGroupBidModifier.criterion.id, bidModifier,
                                              adGroupBidModifier.bidModifierSource);
                            i++;
                        }
                    }
                    offset += pageSize;
                } while (offset < page.totalNumEntries);
                Console.WriteLine("Number of adgroup bid modifiers found: {0}", page.totalNumEntries);
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to retrieve adgroup bid modifiers.", ex);
            }
        }
Ejemplo n.º 16
0
        /// <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)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(
                    AdWordsService.v201705.AdGroupCriterionService);

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

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

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

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

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

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

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

                // Display the results.
                if (retVal != null && retVal.value != null)
                {
                    foreach (AdGroupCriterion adGroupCriterion in retVal.value)
                    {
                        // If you are adding multiple type of criteria, then you may need to
                        // check for
                        //
                        // if (adGroupCriterion is Keyword) { ... }
                        //
                        // to identify the criterion type.
                        Console.WriteLine("Keyword with ad group id = '{0}', keyword id = '{1}', text = " +
                                          "'{2}' and match type = '{3}' was created.", adGroupCriterion.adGroupId,
                                          adGroupCriterion.criterion.id, (adGroupCriterion.criterion as Keyword).text,
                                          (adGroupCriterion.criterion as Keyword).matchType);
                    }
                }
                else
                {
                    Console.WriteLine("No keywords were added.");
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to create keywords.", e);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the UserListService.
            AdwordsUserListService userListService =
                (AdwordsUserListService)user.GetService(
                    AdWordsService.v201708.AdwordsUserListService);

            // Create a user list.
            CrmBasedUserList userList = new CrmBasedUserList()
            {
                name = "Customer relationship management list #" +
                       ExampleUtilities.GetRandomString(),
                description = "A list of customers that originated from email " +
                              "addresses",

                // CRM Userlist has a maximum membership lifespan of 180 days. See
                // https://support.google.com/adwords/answer/6276125 for details.
                membershipLifeSpan = 180L,
            };

            // Create operation.
            UserListOperation operation = new UserListOperation()
            {
                operand   = userList,
                @operator = Operator.ADD
            };

            try {
                // Add user list.
                UserListReturnValue result = userListService.mutate(
                    new UserListOperation[] { operation });

                Console.WriteLine("Created new user list with name = '{0}' and id = " +
                                  "'{1}'.", result.value[0].name, result.value[0].id);

                // Get user list ID.
                long userListId = result.value[0].id;

                // Prepare the emails for upload.
                List <Member> memberList = new List <Member>();

                // Hash normalized email addresses based on SHA-256 hashing algorithm.
                String[] emailHashes = new String[EMAILS.Length];
                for (int i = 0; i < EMAILS.Length; i++)
                {
                    Member member = new Member();
                    member.hashedEmail = ToSha256String(digest, ToNormalizedEmail(EMAILS[i]));

                    // Adding address info is currently available on a whitelist-only basis. This
                    // code demonstrates how to do it, but if you are not on the whitelist, you
                    // will need to remove this block for the example to run.
                    AddressInfo addressInfo = new AddressInfo();
                    addressInfo.hashedFirstName = ToSha256String(digest, FIRST_NAME);
                    addressInfo.hashedLastName  = ToSha256String(digest, LAST_NAME);
                    addressInfo.zipCode         = ZIP_CODE;
                    addressInfo.countryCode     = COUNTRY_CODE;
                    member.addressInfo          = addressInfo;

                    memberList.Add(member);
                }
                ;

                // Create operation to add members to the user list based on email
                // addresses.
                MutateMembersOperation mutateMembersOperation =
                    new MutateMembersOperation()
                {
                    operand = new MutateMembersOperand()
                    {
                        userListId  = userListId,
                        membersList = memberList.ToArray()
                    },
                    @operator = Operator.ADD
                };

                // Add members to the user list based on email addresses.
                MutateMembersReturnValue mutateMembersResult =
                    userListService.mutateMembers(
                        new MutateMembersOperation[] { mutateMembersOperation });

                // Display results.
                // Reminder: it may take several hours for the list to be populated
                // with members.
                foreach (UserList userListResult in mutateMembersResult.userLists)
                {
                    Console.WriteLine("Email addresses were added to user list with " +
                                      "name '{0}' and id '{1}'.",
                                      userListResult.name, userListResult.id);
                }
                userListService.Close();
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to add user lists " +
                                                      "(a.k.a. audiences) and upload email addresses.", e);
            }
        }
        /// <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)
        {
            // Get the AdGroupAdService.
            AdGroupAdService service =
                (AdGroupAdService)user.GetService(AdWordsService.v201705.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 = service.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);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which targeting criteria
        /// are added.</param>
        /// <param name="feedId">ID of a feed that has been configured for location
        /// targeting, meaning it has an ENABLED FeedMapping with criterionType of
        /// 77. Feeds linked to a GMB account automatically have this FeedMapping.
        /// If you don't have such a feed, set this value to null.</param>
        public void Run(AdWordsUser user, long campaignId, long?feedId)
        {
            using (CampaignCriterionService campaignCriterionService =
                       (CampaignCriterionService)user.GetService(
                           AdWordsService.v201802.CampaignCriterionService)) {
                // Create locations. The IDs can be found in the documentation or
                // retrieved with the LocationCriterionService.
                Location california = new Location()
                {
                    id = 21137L
                };

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

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

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

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

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

                    criteria.Add(radiusLocationGroup);
                }

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

                    operations.Add(operation);
                }

                // Add a negative campaign criterion.

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

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

                operations.Add(negativeCriterionOperation);

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

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

            try {
                // Create a BatchJob.
                BatchJobOperation addOp = new BatchJobOperation()
                {
                    @operator = Operator.ADD,
                    operand   = new BatchJob()
                };

                BatchJob batchJob = batchJobService.mutate(new BatchJobOperation[] { addOp }).value[0];

                // Get the upload URL from the new job.
                string uploadUrl = batchJob.uploadUrl.url;

                Console.WriteLine("Created BatchJob with ID {0}, status '{1}' and upload URL {2}.",
                                  batchJob.id, batchJob.status, batchJob.uploadUrl.url);

                // Create the mutate request that will be sent to the upload URL.
                List <Operation> operations = new List <Operation>();

                // Create and add an operation to create a new budget.
                BudgetOperation budgetOperation = BuildBudgetOperation();
                operations.Add(budgetOperation);

                // Create and add operations to create new campaigns.
                List <CampaignOperation> campaignOperations =
                    BuildCampaignOperations(budgetOperation.operand.budgetId);
                operations.AddRange(campaignOperations);

                // Create and add operations to create new ad groups.
                List <AdGroupOperation> adGroupOperations = new List <AdGroupOperation>();
                foreach (CampaignOperation campaignOperation in campaignOperations)
                {
                    adGroupOperations.AddRange(BuildAdGroupOperations(campaignOperation.operand.id));
                }
                operations.AddRange(adGroupOperations);

                // Create and add operations to create new ad group ads (expanded text ads).
                foreach (AdGroupOperation adGroupOperation in adGroupOperations)
                {
                    operations.AddRange(BuildAdGroupAdOperations(adGroupOperation.operand.id));
                }

                // Create and add operations to create new ad group criteria (keywords).
                foreach (AdGroupOperation adGroupOperation in adGroupOperations)
                {
                    operations.AddRange(BuildAdGroupCriterionOperations(adGroupOperation.operand.id));
                }

                BatchJobUtilities batchJobUploadHelper = new BatchJobUtilities(user);

                // Create a resumable Upload URL to upload the operations.
                string resumableUploadUrl = batchJobUploadHelper.GetResumableUploadUrl(uploadUrl);

                // Use the BatchJobUploadHelper to upload all operations.
                batchJobUploadHelper.Upload(resumableUploadUrl, operations);

                bool isCompleted = batchJobUploadHelper.WaitForPendingJob(batchJob.id,
                                                                          TIME_TO_WAIT_FOR_COMPLETION, delegate(BatchJob waitBatchJob, long timeElapsed) {
                    Console.WriteLine("[{0} seconds]: Batch job ID {1} has status '{2}'.",
                                      timeElapsed / 1000, waitBatchJob.id, waitBatchJob.status);
                    batchJob = waitBatchJob;
                    return(false);
                });

                if (!isCompleted)
                {
                    throw new TimeoutException("Job is still in pending state after waiting for " +
                                               TIME_TO_WAIT_FOR_COMPLETION + " seconds.");
                }

                if (batchJob.processingErrors != null)
                {
                    foreach (BatchJobProcessingError processingError in batchJob.processingErrors)
                    {
                        Console.WriteLine("  Processing error: {0}, {1}, {2}, {3}, {4}",
                                          processingError.ApiErrorType, processingError.trigger,
                                          processingError.errorString, processingError.fieldPath,
                                          processingError.reason);
                    }
                }

                if (batchJob.downloadUrl != null && batchJob.downloadUrl.url != null)
                {
                    BatchJobMutateResponse mutateResponse = batchJobUploadHelper.Download(
                        batchJob.downloadUrl.url);
                    Console.WriteLine("Downloaded results from {0}.", batchJob.downloadUrl.url);
                    foreach (MutateResult mutateResult in mutateResponse.rval)
                    {
                        String outcome = mutateResult.errorList == null ? "SUCCESS" : "FAILURE";
                        Console.WriteLine("  Operation [{0}] - {1}", mutateResult.index, outcome);
                    }
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to add campaigns using batch job.", e);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            using (ManagedCustomerService managedCustomerService =
                       (ManagedCustomerService)user.GetService(
                           AdWordsService.v201806.ManagedCustomerService)) {
                // Create selector.
                Selector selector = new Selector {
                    fields = new string[] {
                        ManagedCustomer.Fields.CustomerId, ManagedCustomer.Fields.Name
                    },
                    paging = Paging.Default
                };

                // Map from customerId to customer node.
                Dictionary <long, ManagedCustomerTreeNode> customerIdToCustomerNode =
                    new Dictionary <long, ManagedCustomerTreeNode>();

                // Temporary cache to save links.
                List <ManagedCustomerLink> allLinks = new List <ManagedCustomerLink>();

                ManagedCustomerPage page = null;
                try {
                    do
                    {
                        page = managedCustomerService.get(selector);

                        if (page.entries != null)
                        {
                            // Create account tree nodes for each customer.
                            foreach (ManagedCustomer customer in page.entries)
                            {
                                ManagedCustomerTreeNode node = new ManagedCustomerTreeNode {
                                    Account = customer
                                };
                                customerIdToCustomerNode.Add(customer.customerId, node);
                            }

                            if (page.links != null)
                            {
                                allLinks.AddRange(page.links);
                            }
                        }
                        selector.paging.IncreaseOffset();
                    } while (selector.paging.startIndex < page.totalNumEntries);

                    // For each link, connect nodes in tree.
                    foreach (ManagedCustomerLink link in allLinks)
                    {
                        ManagedCustomerTreeNode managerNode =
                            customerIdToCustomerNode[link.managerCustomerId];
                        ManagedCustomerTreeNode childNode = customerIdToCustomerNode[link.clientCustomerId];
                        childNode.ParentNode = managerNode;
                        if (managerNode != null)
                        {
                            managerNode.ChildAccounts.Add(childNode);
                        }
                    }

                    // Find the root account node in the tree.
                    ManagedCustomerTreeNode rootNode = null;
                    foreach (ManagedCustomerTreeNode node in customerIdToCustomerNode.Values)
                    {
                        if (node.ParentNode == null)
                        {
                            rootNode = node;
                            break;
                        }
                    }

                    // Display account tree.
                    Console.WriteLine("CustomerId, Name");
                    Console.WriteLine(rootNode.ToTreeString(0, new StringBuilder()));
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to create ad groups.", e);
                }
            }
        }
Ejemplo n.º 22
0
        /// <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);
                }
            }
        }
        /// <summary>
        /// Gets the shared criteria in a shared set.
        /// </summary>
        /// <param name="user">The user that owns the shared set.</param>
        /// <param name="sharedSetIds">The shared criteria IDs.</param>
        /// <returns>The list of shared criteria.</returns>
        private List <SharedCriterion> GetSharedCriteria(AdWordsUser user,
                                                         List <string> sharedSetIds)
        {
            SharedCriterionService sharedCriterionService =
                (SharedCriterionService)user.GetService(AdWordsService.v201607.SharedCriterionService);

            Selector selector = new Selector()
            {
                fields = new string[] {
                    SharedSet.Fields.SharedSetId, Criterion.Fields.Id,
                    Keyword.Fields.KeywordText, Keyword.Fields.KeywordMatchType,
                    Placement.Fields.PlacementUrl
                },
                predicates = new Predicate[] {
                    Predicate.In(SharedSet.Fields.SharedSetId, sharedSetIds)
                },
                paging = Paging.Default
            };

            List <SharedCriterion> sharedCriteria = new List <SharedCriterion>();
            SharedCriterionPage    page           = new SharedCriterionPage();

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

                    // Display the results.
                    if (page != null && page.entries != null)
                    {
                        int i = selector.paging.startIndex;
                        foreach (SharedCriterion sharedCriterion in page.entries)
                        {
                            switch (sharedCriterion.criterion.type)
                            {
                            case CriterionType.KEYWORD:
                                Keyword keyword = (Keyword)sharedCriterion.criterion;
                                Console.WriteLine("{0}) Shared negative keyword with ID {1} and text '{2}' " +
                                                  "was found.", i + 1, keyword.id, keyword.text);
                                break;

                            case CriterionType.PLACEMENT:
                                Placement placement = (Placement)sharedCriterion.criterion;
                                Console.WriteLine("{0}) Shared negative placement with ID {1} and URL '{2}' " +
                                                  "was found.", i + 1, placement.id, placement.url);
                                break;

                            default:
                                Console.WriteLine("{0}) Shared criteria with ID {1} was found.",
                                                  i + 1, sharedCriterion.criterion.id);
                                break;
                            }
                            i++;
                            sharedCriteria.Add(sharedCriterion);
                        }
                    }
                    selector.paging.IncreaseOffset();
                } while (selector.paging.startIndex < page.totalNumEntries);

                return(sharedCriteria);
            } catch (Exception e) {
                throw new Exception("Failed to get shared criteria.", e);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which sitelinks will
        /// be added.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            using (CustomerExtensionSettingService customerExtensionSettingService =
                       (CustomerExtensionSettingService)user.GetService(
                           AdWordsService.v201802.CustomerExtensionSettingService)) {
                // Create the price extension feed item.
                PriceFeedItem priceFeedItem = new PriceFeedItem()
                {
                    priceExtensionType = PriceExtensionType.SERVICES,

                    // Price qualifier is optional.
                    priceQualifier      = PriceExtensionPriceQualifier.FROM,
                    trackingUrlTemplate = "http://tracker.example.com/?u={lpurl}",
                    language            = "en",

                    campaignTargeting = new FeedItemCampaignTargeting()
                    {
                        TargetingCampaignId = campaignId,
                    },
                    scheduling = new FeedItemSchedule[] {
                        new FeedItemSchedule()
                        {
                            dayOfWeek   = DayOfWeek.SATURDAY,
                            startHour   = 10,
                            startMinute = MinuteOfHour.ZERO,
                            endHour     = 22,
                            endMinute   = MinuteOfHour.ZERO
                        },
                        new FeedItemSchedule()
                        {
                            dayOfWeek   = DayOfWeek.SUNDAY,
                            startHour   = 10,
                            startMinute = MinuteOfHour.ZERO,
                            endHour     = 18,
                            endMinute   = MinuteOfHour.ZERO
                        }
                    }
                };

                // To create a price extension, at least three table rows are needed.
                List <PriceTableRow> priceTableRows = new List <PriceTableRow>();
                String currencyCode = "USD";
                priceTableRows.Add(
                    CreatePriceTableRow(
                        "Scrubs",
                        "Body Scrub, Salt Scrub",
                        "http://www.example.com/scrubs",
                        "http://m.example.com/scrubs",
                        60000000,
                        currencyCode,
                        PriceExtensionPriceUnit.PER_HOUR));
                priceTableRows.Add(
                    CreatePriceTableRow(
                        "Hair Cuts",
                        "Once a month",
                        "http://www.example.com/haircuts",
                        "http://m.example.com/haircuts",
                        75000000,
                        currencyCode,
                        PriceExtensionPriceUnit.PER_MONTH));
                priceTableRows.Add(
                    CreatePriceTableRow(
                        "Skin Care Package",
                        "Four times a month",
                        "http://www.example.com/skincarepackage",
                        null,
                        250000000,
                        currencyCode,
                        PriceExtensionPriceUnit.PER_MONTH));

                priceFeedItem.tableRows = priceTableRows.ToArray();

                // Create your campaign extension settings. This associates the sitelinks
                // to your campaign.
                CustomerExtensionSetting customerExtensionSetting = new CustomerExtensionSetting()
                {
                    extensionType    = FeedType.PRICE,
                    extensionSetting = new ExtensionSetting()
                    {
                        extensions = new ExtensionFeedItem[] { priceFeedItem }
                    }
                };

                CustomerExtensionSettingOperation operation = new CustomerExtensionSettingOperation()
                {
                    operand   = customerExtensionSetting,
                    @operator = Operator.ADD
                };

                try {
                    // Add the extensions.
                    CustomerExtensionSettingReturnValue retVal =
                        customerExtensionSettingService.mutate(
                            new CustomerExtensionSettingOperation[] { operation });
                    if (retVal.value != null && retVal.value.Length > 0)
                    {
                        CustomerExtensionSetting newExtensionSetting = retVal.value[0];
                        Console.WriteLine("Extension setting with type '{0}' was added.",
                                          newExtensionSetting.extensionType);
                    }
                    else
                    {
                        Console.WriteLine("No extension settings were created.");
                    }
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to create extension settings.", e);
                }
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Set custom targeting for the page feed URLs based on a list of labels.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Ad group ID.</param>
        /// <param name="labelName">The label name.</param>
        /// <returns>The newly created webpage criterion.</returns>
        private static BiddableAdGroupCriterion AddDsaTargeting(AdWordsUser user, long adGroupId,
                                                                string labelName)
        {
            using (AdGroupCriterionService adGroupCriterionService =
                       (AdGroupCriterionService)user.GetService(AdWordsService.v201806
                                                                .AdGroupCriterionService))
            {
                // Create a webpage criterion.
                Webpage webpage = new Webpage();

                WebpageParameter parameter = new WebpageParameter
                {
                    criterionName = "Test criterion"
                };
                webpage.parameter = parameter;

                // Add a condition for label=specified_label_name.
                WebpageCondition condition = new WebpageCondition
                {
                    operand  = WebpageConditionOperand.CUSTOM_LABEL,
                    argument = labelName
                };
                parameter.conditions = new WebpageCondition[]
                {
                    condition
                };

                BiddableAdGroupCriterion criterion = new BiddableAdGroupCriterion
                {
                    adGroupId = adGroupId,
                    criterion = webpage
                };

                // Set a custom bid for this criterion.
                BiddingStrategyConfiguration biddingStrategyConfiguration =
                    new BiddingStrategyConfiguration
                {
                    bids = new Bids[]
                    {
                        new CpcBid()
                        {
                            bid = new Money()
                            {
                                microAmount = 1500000
                            }
                        }
                    }
                };

                criterion.biddingStrategyConfiguration = biddingStrategyConfiguration;

                AdGroupCriterionOperation operation = new AdGroupCriterionOperation
                {
                    operand   = criterion,
                    @operator = Operator.ADD
                };

                try
                {
                    AdGroupCriterionReturnValue retval = adGroupCriterionService.mutate(
                        new AdGroupCriterionOperation[]
                    {
                        operation
                    });
                    BiddableAdGroupCriterion newCriterion =
                        (BiddableAdGroupCriterion)retval.value[0];

                    Console.WriteLine(
                        "Web page criterion with ID = {0} and status = {1} was created.",
                        newCriterion.criterion.id, newCriterion.userStatus);
                    return(newCriterion);
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException(
                              "Failed to create webpage criterion for " + "custom page feed label.", e);
                }
            }
        }
Ejemplo n.º 26
0
        /// <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.v201710.AdGroupService)) {
                // Create an ad group with the specified ID.
                AdGroup adGroup = new AdGroup();
                adGroup.id = adGroupId;

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

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

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

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

                    // Display the results.
                    if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                    {
                        AdGroup 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);
                }
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which sitelinks will
        /// be added.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            // Get the CampaignExtensionSettingService.
            CampaignExtensionSettingService campaignExtensionSettingService =
                (CampaignExtensionSettingService)user.GetService(
                    AdWordsService.v201506.CampaignExtensionSettingService);

            CustomerService customerService = (CustomerService)user.GetService(
                AdWordsService.v201506.CustomerService);
            Customer customer = customerService.get();

            List <ExtensionFeedItem> extensions = new List <ExtensionFeedItem>();

            // Create your sitelinks.
            SitelinkFeedItem sitelink1 = new SitelinkFeedItem()
            {
                sitelinkText      = "Store Hours",
                sitelinkFinalUrls = new string[] { "http://www.example.com/storehours" }
            };

            extensions.Add(sitelink1);

            DateTime startOfThanksGiving = new DateTime(DateTime.Now.Year, 11, 20, 0, 0, 0);
            DateTime endOfThanksGiving   = new DateTime(DateTime.Now.Year, 11, 27, 23, 59, 59);

            // Add check to make sure we don't create a sitelink with end date in the
            // past.
            if (DateTime.Now < endOfThanksGiving)
            {
                // Show the Thanksgiving specials link only from 20 - 27 Nov.
                SitelinkFeedItem sitelink2 = new SitelinkFeedItem()
                {
                    sitelinkText      = "Thanksgiving Specials",
                    sitelinkFinalUrls = new string[] { "http://www.example.com/thanksgiving" },
                    startTime         = string.Format("{0} {1}", startOfThanksGiving.ToString("yyyyMMdd HHmmss"),
                                                      customer.dateTimeZone),
                    endTime = string.Format("{0} {1}", endOfThanksGiving.ToString("yyyyMMdd HHmmss"),
                                            customer.dateTimeZone)
                };
                extensions.Add(sitelink2);
            }
            // Show the wifi details primarily for high end mobile users.
            SitelinkFeedItem sitelink3 = new SitelinkFeedItem()
            {
                sitelinkText      = "Wifi available",
                sitelinkFinalUrls = new string[] { "http://www.example.com/mobile/wifi" },
                devicePreference  = new FeedItemDevicePreference()
                {
                    // See https://developers.google.com/adwords/api/docs/appendix/platforms
                    // for device criteria IDs.
                    devicePreference = 30001
                }
            };

            extensions.Add(sitelink3);

            // Show the happy hours link only during Mon - Fri 6PM to 9PM.
            SitelinkFeedItem sitelink4 = new SitelinkFeedItem()
            {
                sitelinkText      = "Happy hours",
                sitelinkFinalUrls = new string[] { "http://www.example.com/happyhours" },
                scheduling        = new FeedItemSchedule[] {
                    new FeedItemSchedule()
                    {
                        dayOfWeek   = DayOfWeek.MONDAY,
                        startHour   = 18,
                        startMinute = MinuteOfHour.ZERO,
                        endHour     = 21,
                        endMinute   = MinuteOfHour.ZERO
                    },
                    new FeedItemSchedule()
                    {
                        dayOfWeek   = DayOfWeek.TUESDAY,
                        startHour   = 18,
                        startMinute = MinuteOfHour.ZERO,
                        endHour     = 21,
                        endMinute   = MinuteOfHour.ZERO
                    },
                    new FeedItemSchedule()
                    {
                        dayOfWeek   = DayOfWeek.WEDNESDAY,
                        startHour   = 18,
                        startMinute = MinuteOfHour.ZERO,
                        endHour     = 21,
                        endMinute   = MinuteOfHour.ZERO
                    },
                    new FeedItemSchedule()
                    {
                        dayOfWeek   = DayOfWeek.THURSDAY,
                        startHour   = 18,
                        startMinute = MinuteOfHour.ZERO,
                        endHour     = 21,
                        endMinute   = MinuteOfHour.ZERO
                    },
                    new FeedItemSchedule()
                    {
                        dayOfWeek   = DayOfWeek.FRIDAY,
                        startHour   = 18,
                        startMinute = MinuteOfHour.ZERO,
                        endHour     = 21,
                        endMinute   = MinuteOfHour.ZERO
                    }
                }
            };

            extensions.Add(sitelink4);

            // Create your campaign extension settings. This associates the sitelinks
            // to your campaign.
            CampaignExtensionSetting campaignExtensionSetting = new CampaignExtensionSetting();

            campaignExtensionSetting.campaignId       = campaignId;
            campaignExtensionSetting.extensionType    = FeedType.SITELINK;
            campaignExtensionSetting.extensionSetting = new ExtensionSetting()
            {
                extensions = extensions.ToArray()
            };

            CampaignExtensionSettingOperation operation = new CampaignExtensionSettingOperation()
            {
                operand   = campaignExtensionSetting,
                @operator = Operator.ADD
            };

            try {
                // Add the extensions.
                CampaignExtensionSettingReturnValue retVal = campaignExtensionSettingService.mutate(
                    new CampaignExtensionSettingOperation[] { operation });

                // Display the results.
                if (retVal.value != null && retVal.value.Length > 0)
                {
                    CampaignExtensionSetting newExtensionSetting = retVal.value[0];
                    Console.WriteLine("Extension setting with type = {0} was added to campaign ID {1}.",
                                      newExtensionSetting.extensionType, newExtensionSetting.campaignId);
                }
                else
                {
                    Console.WriteLine("No extension settings were created.");
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to create extension settings.", e);
            }
        }
        /// <summary>
        /// Sets the campaign's targeting criteria.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaign">The campaign for which targeting criteria is
        /// created.</param>
        private void SetCampaignTargetingCriteria(AdWordsUser user, Campaign campaign)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionService campaignCriterionService =
                (CampaignCriterionService)user.GetService(
                    AdWordsService.v201609.CampaignCriterionService);

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

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

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

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

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

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

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

                operations.Add(operation);
            }

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

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

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

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

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

            Language language2 = new Language();

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

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

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

            IncomeOperand incomeOperand = new IncomeOperand();

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

            GeoTargetOperand geoTargetOperand1 = new GeoTargetOperand();

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

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

            CampaignCriterion locationGroupCriterion1 = new CampaignCriterion();

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

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

            PlacesOfInterestOperand placesOfInterestOperand = new PlacesOfInterestOperand();

            placesOfInterestOperand.category = PlacesOfInterestOperandCategory.DOWNTOWN;

            GeoTargetOperand geoTargetOperand2 = new GeoTargetOperand();

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

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

            CampaignCriterion locationGroupCriterion2 = new CampaignCriterion();

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

            CampaignCriterion locationGroupCriterion3 = new CampaignCriterion();

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

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

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

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

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

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

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

            Location location2 = new Location();

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

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

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

            negativeCriterion.campaignId = campaignId;

            Keyword keyword = new Keyword();

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

            negativeCriterion.criterion = keyword;

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

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

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

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

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

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

            // Create the campaign.
            Campaign campaign = new Campaign();

            campaign.name = "Interplanetary Cruise App #" + ExampleUtilities.GetRandomString();

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

            // Set the advertising channel and subchannel types for universal app campaigns.
            campaign.advertisingChannelType    = AdvertisingChannelType.MULTI_CHANNEL;
            campaign.advertisingChannelSubType = AdvertisingChannelSubType.UNIVERSAL_APP_CAMPAIGN;

            // Set the campaign's bidding strategy. Universal app campaigns
            // only support TARGET_CPA bidding strategy.
            BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();

            biddingConfig.biddingStrategyType = BiddingStrategyType.TARGET_CPA;

            // Set the target CPA to $1 / app install.
            TargetCpaBiddingScheme biddingScheme = new TargetCpaBiddingScheme();

            biddingScheme.targetCpa             = new Money();
            biddingScheme.targetCpa.microAmount = 1000000;

            biddingConfig.biddingScheme           = biddingScheme;
            campaign.biddingStrategyConfiguration = biddingConfig;

            // Set the campaign's budget.
            campaign.budget          = new Budget();
            campaign.budget.budgetId = CreateBudget(user).budgetId;

            // 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");

            // Set the campaign's assets and ad text ideas. These values will be used to
            // generate ads.
            UniversalAppCampaignSetting universalAppSetting = new UniversalAppCampaignSetting();

            universalAppSetting.appId        = "com.labpixies.colordrips";
            universalAppSetting.description1 = "Best Space Cruise Line";
            universalAppSetting.description2 = "Visit all the planets";
            universalAppSetting.description3 = "Trips 7 days a week";
            universalAppSetting.description4 = "Buy your tickets now!";

            // Optional: You can set up to 10 image assets for your campaign.
            // See UploadImage.cs for an example on how to upload images.
            //
            // universalAppSetting.imageMediaIds = new long[] { INSERT_IMAGE_MEDIA_ID_HERE };

            // Optimize this campaign for getting new users for your app.
            universalAppSetting.universalAppBiddingStrategyGoalType =
                UniversalAppBiddingStrategyGoalType.OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME;

            // Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal
            // type, then also specify your in-app conversion types so AdWords can
            // focus your campaign on people who are most likely to complete the
            // corresponding in-app actions.
            // Conversion type IDs can be retrieved using ConversionTrackerService.get.
            //
            // campaign.selectiveOptimization = new SelectiveOptimization();
            // campaign.selectiveOptimization.conversionTypeIds =
            //    new long[] { INSERT_CONVERSION_TYPE_ID_1_HERE, INSERT_CONVERSION_TYPE_ID_2_HERE };

            // Optional: Set the campaign settings for Advanced location options.
            GeoTargetTypeSetting geoSetting = new GeoTargetTypeSetting();

            geoSetting.positiveGeoTargetType =
                GeoTargetTypeSettingPositiveGeoTargetType.LOCATION_OF_PRESENCE;
            geoSetting.negativeGeoTargetType =
                GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE;

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

            // Create the operation.
            CampaignOperation operation = new CampaignOperation();

            operation.@operator = Operator.ADD;
            operation.operand   = campaign;

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

                // Display the results.
                if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                {
                    foreach (Campaign newCampaign in retVal.value)
                    {
                        Console.WriteLine("Universal app campaign with name = '{0}' and id = '{1}' was added.",
                                          newCampaign.name, newCampaign.id);

                        // Optional: Set the campaign's location and language targeting. No other targeting
                        // criteria can be used for universal app campaigns.
                        SetCampaignTargetingCriteria(user, newCampaign);
                    }
                }
                else
                {
                    Console.WriteLine("No universal app campaigns were added.");
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to add universal app campaigns.", e);
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Creates an AdWords Campaign grouped by category
        /// </summary>
        /// <param name="UseSandbox">Call the webservices in the test env</param>
        /// <param name="AffiliateSiteRefId"></param>
        /// <param name="Name">Campaign Name</param>
        /// <param name="Countries">Targeted countires</param>
        /// <param name="Languages">Targeted Languages</param>
        /// <param name="BudgetPeriod">The duration over which to spend the budgetAmount. For most developers, Daily is the only allowable option.</param>
        /// <param name="BudgetAmount">The amount of the budget in micros. Use budgetPeriod to set the duration over which to spend this amount.</param>
        /// <param name="KeywordMaxCpc">The default maximum cost-per-click bid for Keyword criteria in this ad group. See the note on bid amounts for more information on using this field.</param>
        /// <param name="MaxAdsPerGroup">Max Ads to create for each AdGroup</param>
        /// <param name="MaxAdvertiserCompetitionScale">The Max level of competition allowed from advertisers for keyword variations, on a scale from 0 to 5. Set to -1 if data is not available</param>
        /// <param name="MinSearchVolumeScale">The Min amount of searches to allowed related to keyword variations, on a scale from 0 to 5. Set to -1 if data is not available</param>
        /// <param name="DisplayUrl">Display Url to use for each Ad</param>
        /// <param name="destinationUrlPrefix">Destination Url Prefix for the destination Url of the Ads created.</param>
        /// <param name="UseKeywordVariations">Check for Keyword variations</param>
        /// <param name="MaxVariations">Max number of Keyword variations to use.</param>
        /// <param name="AdKeywordType">The type of keyword, indicating how it is targeted. This is not mutable after being set the first time. Values are: Broad=0,Phrase=1,Exact=2</param>
        //public void CreateCampaignGroupByProduct(bool UseSandbox, Guid AffiliateSiteRefId, string Name, String[] Countries, String[] Languages, int BudgetPeriod,
        //                                        Moneyv200906 BudgetAmount, long KeywordMaxCpc, int MaxAdGroups, int MaxAdvertiserCompetitionScale, int MinSearchVolumeScale,
        //                                        string DisplayUrl, string destinationUrlPrefix, bool GetKeywordsFromLandingPage, int MaxVariations, int AdKeywordType)
        //{
        //    // Create a user (reads headers from App.config file).
        //    AdWordsUser user = new AdWordsUser();
        //    if (UseSandbox)
        //        user.UseSandbox();	// use sandbox
        //    AccountService accountService = (AccountService)user.GetService(ApiServices.v13.AccountService);
        //    string[] accounts = accountService.getClientAccounts();
        //    try
        //    {
        //        #region Create Campaign
        //        // Create a new campaign with an ad group.  First create a
        //        // campaign, so we can get its id.
        //        Campaignv200906 newCampaign = new Campaignv200906();
        //        newCampaign.budget.amount = BudgetAmount;
        //        //newCampaign.budget.amountSpecified = true;
        //        newCampaign.budget.period = (BudgetPeriodv200906)Enum.ToObject(typeof(BudgetPeriodv200906), BudgetPeriod);
        //        newCampaign.budget.periodSpecified = true;
        //        // The campaign name is optional.  An error results if a campaign
        //        // of the same name already exists.
        //        newCampaign.name = Name;
        //        //TODO:newCampaign.networkTargeting = new NetworkType[] { NetworkType.SearchNetwork };
        //        // Target the campaign at
        //        CampaignServicev200906 campaignService = (CampaignServicev200906)user.GetService(ApiServices.v200906.CampaignService);
        //        // Set the campaign status to paused, we don't want to start
        //        // paying for this test.
        //        newCampaign.status = CampaignStatusv200906.PAUSED;
        //        // Add this campaign.  The campaign object is returned with ids
        //        // filled in.
        //        // Define an Add operation to add the campaign.
        //        CampaignOperation campaignOperation = new CampaignOperation();
        //        campaignOperation.operatorSpecified = true;
        //        campaignOperation.@operator = CampaignOperatorv200906.ADD;
        //        campaignOperation.operand = newCampaign;
        //        try
        //        {
        //            CampaignReturnValue results =
        //              campaignService.mutate(new CampaignOperation[] { campaignOperation });
        //            if (results != null && results.value != null && results.value.Length > 0)
        //            {
        //                Trace.TraceInformation("New campaign with name = \"{0}\" and id = " + "\"{1}\" was created.", results.value[0].name, results.value[0].id);
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            throw new Exception("Failed to create campaign. " + ex.Message);
        //        }
        //        long campaignId = newCampaign.id;
        //        #endregion
        //        #region Targeting
        //        CampaignTargetServicev200906 service = (CampaignTargetServicev200906)user.GetService(ApiServices.v200906.CampaignTargetService);
        //        // Create a language target - for English language.
        //        LanguageTargetv200906 languageTarget = new LanguageTargetv200906();
        //        languageTarget.languageCode = "en";
        //        LanguageTargetList languageTargetList = new LanguageTargetList();
        //        languageTargetList.targets = new LanguageTargetv200906[] { languageTarget };
        //        languageTargetList.campaignId = campaignId;
        //        languageTargetList.campaignIdSpecified = true;
        //        // Create a country target - include US, exclude metrocode 743.
        //        CountryTargetv200906 countryTarget = new CountryTargetv200906();
        //        countryTarget.countryCode = "US";
        //        countryTarget.excludedSpecified = true;
        //        countryTarget.excluded = false;
        //        MetroTargetv200906 metroTarget = new MetroTargetv200906();
        //        metroTarget.excludedSpecified = true;
        //        metroTarget.excluded = true;
        //        metroTarget.metroCode = "743";
        //        GeoTargetList geoTargetList = new GeoTargetList();
        //        geoTargetList.targets = new GeoTargetv200906[] { countryTarget, metroTarget };
        //        geoTargetList.campaignId = campaignId;
        //        geoTargetList.campaignIdSpecified = true;
        //        // Create a network target - Google Search.
        //        NetworkTargetv200906 networkTarget1 = new NetworkTargetv200906();
        //        networkTarget1.networkCoverageTypeSpecified = true;
        //        networkTarget1.networkCoverageType = NetworkCoverageTypev200906.GOOGLE_SEARCH;
        //        NetworkTargetv200906 networkTarget2 = new NetworkTargetv200906();
        //        networkTarget2.networkCoverageTypeSpecified = true;
        //        networkTarget2.networkCoverageType = NetworkCoverageTypev200906.SEARCH_NETWORK;
        //        NetworkTargetList networkTargetList = new NetworkTargetList();
        //        networkTargetList.targets = new NetworkTargetv200906[] { networkTarget1, networkTarget2 };
        //        networkTargetList.campaignId = campaignId;
        //        networkTargetList.campaignIdSpecified = true;
        //        TargetList[] targets =
        //            new TargetList[] { languageTargetList, geoTargetList, networkTargetList };
        //        ArrayList campaignTargetOperations = new ArrayList();
        //        foreach (TargetList target in targets)
        //        {
        //            CampaignTargetOperation ops = new CampaignTargetOperation();
        //            ops.operatorSpecified = true;
        //            ops.@operator = CampaignTargetOperatorv200906.SET;
        //            ops.operand = target;
        //            campaignTargetOperations.Add(ops);
        //        }
        //        try
        //        {
        //            service.mutate((CampaignTargetOperation[])
        //              campaignTargetOperations.ToArray(typeof(CampaignTargetOperation)));
        //            Console.WriteLine("Geo, language, and network targeting were " +
        //                "successfully added to campaign id = \"{0}\".", campaignId);
        //        }
        //        catch (Exception ex)
        //        {
        //            Console.WriteLine("Failed to create campaign targeting. " +
        //                "Exception says \"{0}\"", ex.Message);
        //        }
        //        #endregion
        //        #region Create your Services
        //        //create your services
        //        List<SeedKeyword> keywords = new List<SeedKeyword>();
        //        AdService adService = (AdService)user.GetService(ApiServices.v200906.AdGroupAdService);
        //        KeywordToolService keywordToolService = (KeywordToolService)user.GetService(ApiServices.v13.KeywordToolService);
        //        AdGroupService adgroupService = (AdGroupService)user.GetService(ApiServices.v200906.AdGroupService);
        //        TrafficEstimatorService trafficEstimatorService = (TrafficEstimatorService)user.GetService(ApiServices.v13.TrafficEstimatorService);
        //        #endregion
        //        #region Enumerate thru all the categories
        //        //enumerate thru all the categories
        //        foreach (SiteCategory siteCategory in DataRepository.SiteCategoryProvider.GetByAffiliateSiteRefId(AffiliateSiteRefId))
        //        {
        //            int GroupAdCount = 0;
        //            DataRepository.SiteCategoryProvider.DeepLoad(siteCategory, true, DeepLoadType.IncludeChildren, typeof(TList<SiteCategoryCategoryMapping>));
        //            //////Create an ad group by site category
        //            ////AdGroup newAdGroup = new AdGroup();
        //            ////newAdGroup.name = siteCategory.SiteCategory;
        //            ////newAdGroup.keywordMaxCpc = KeywordMaxCpc;
        //            ////newAdGroup.keywordMaxCpcSpecified = true;
        //            ////// Associate this ad group with the newly created campaign.  Send
        //            ////// the request to add the new ad group.
        //            ////AdGroup myAdGroup = adgroupService.addAdGroup(campaignId, newAdGroup);
        //            ////long adGroupId = myAdGroup.id;
        //            #region Enumerate thru the category mappings to get the merchants
        //            //enumerate thru the categoru mappings to get the merchants
        //            foreach (SiteCategoryCategoryMapping catMap in siteCategory.SiteCategoryCategoryMappingCollection)
        //            {
        //                if (GroupAdCount >= MaxAdGroups)
        //                    break;
        //                DataRepository.SiteCategoryCategoryMappingProvider.DeepLoad(catMap, true, DeepLoadType.IncludeChildren, typeof(Category));
        //                DataRepository.CategoryProvider.DeepLoad(catMap.CategoryRefIdSource, true, DeepLoadType.IncludeChildren, typeof(TList<Merchant>));
        //                catMap.CategoryRefIdSource.MerchantCollection.Shuffle();
        //                foreach (Merchant merch in catMap.CategoryRefIdSource.MerchantCollection)
        //                {
        //                    if (GroupAdCount >= MaxAdGroups)
        //                        break;
        //                    DataRepository.MerchantProvider.DeepLoad(merch, true, DeepLoadType.IncludeChildren, typeof(TList<Product>));
        //                    //shuffle the products
        //                    merch.ProductCollection.Shuffle();
        //                    // enumerate thru all the merchant's products
        //                    foreach (Product prod in merch.ProductCollection)
        //                    {
        //                        //Create an ad group by site category
        //                        AdGroup newAdGroup = new AdGroup();
        //                        newAdGroup.name = siteCategory.Name + "-" + prod.Name;
        //                        newAdGroup.keywordMaxCpc = KeywordMaxCpc;
        //                        newAdGroup.keywordMaxCpcSpecified = true;
        //                        Trace.TraceInformation(prod.Name);
        //                        string cleanProdName = StringUtils.ScrubProdName(StringUtils.RemoveDuplicateWords(prod.Name));
        //                        string urlProdName = StringUtils.ScrubProdNameUrl(cleanProdName) + ".aspx";
        //                        int c = 0;
        //                        keywords.Clear();
        //                        string[] rawKeywords = new string[] { "" };
        //                        //check to see if the product record has keywords
        //                        //if (prod.Keywords != null)
        //                        //    rawKeywords = prod.Keywords.Split(',');
        //                        //if (rawKeywords.Length < 2)
        //                        rawKeywords = cleanProdName.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
        //                        foreach (string str in rawKeywords)
        //                        {
        //                            int tryInt = 0; //not empty, not a number, and not lower case
        //                            if (str.Trim() != "" && !int.TryParse(str.Trim(), out tryInt)) //&& !isLowerCase(str.Trim().Substring(0, 1).ToCharArray()[0])
        //                            {
        //                                SeedKeyword sw = new SeedKeyword();
        //                                sw.text = StringUtils.ScrubKeywords(str);
        //                                if (sw.text.Trim() != "")
        //                                {
        //                                    sw.type = (KeywordType)Enum.ToObject(typeof(KeywordType), AdKeywordType);
        //                                    sw.negative = false;
        //                                    keywords.Add(sw);
        //                                    c++;
        //                                    if (c == 10) //TODO: fix this to get all words
        //                                        break;
        //                                }
        //                            }
        //                        }
        //                        //Create an add for each product
        //                        //
        //                        // IMPORTANT: create an ad before adding keywords!  Else the
        //                        // minCpc will have a higher value.
        //                        TextAd newTextAd = new TextAd();
        //                        newTextAd.headline = prod.Name;
        //                        while (newTextAd.headline.Length > 25)
        //                        {
        //                            newTextAd.headline = newTextAd.headline.Substring(0, newTextAd.headline.LastIndexOf(" ")).Substring(0, newTextAd.headline.Substring(0, newTextAd.headline.LastIndexOf(" ")).LastIndexOf(" "));
        //                        }
        //                        if (prod.Description.Length > 35)
        //                        {
        //                            string[] words = prod.Description.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
        //                            //descriptions are limited to 35 chars
        //                            foreach (string wrd in words)
        //                            {
        //                                string word = StringUtils.ScrubKeywords(wrd);
        //                                if (word.Trim() != "")
        //                                {
        //                                    if (newTextAd.description1 == null || (newTextAd.description1.Length + word.Length) < 35)
        //                                        newTextAd.description1 += word + " ";
        //                                    else if (newTextAd.description2 == null || (newTextAd.description2.Length + word.Length) < 35)
        //                                    {
        //                                        newTextAd.description1 = newTextAd.description1.PadRight(35);
        //                                        newTextAd.description2 += word + " ";
        //                                    }
        //                                    else
        //                                    {
        //                                        newTextAd.description2 = newTextAd.description2.PadRight(35);
        //                                        break;
        //                                    }
        //                                }
        //                            }
        //                            if (newTextAd.description2 == null || (newTextAd.description2.Length + string.Format("{0:c}", prod.Price).Length) < 35)
        //                                newTextAd.description2 += string.Format("{0:c}", prod.Price);
        //                        }
        //                        else
        //                        {
        //                            newTextAd.description1 = prod.Description;
        //                            newTextAd.description2 = string.Format("{0:c}", prod.Price);
        //                        }
        //                        newTextAd.displayUrl = DisplayUrl;
        //                        newTextAd.destinationUrl = destinationUrlPrefix + siteCategory.PageUrl.Substring(2, siteCategory.PageUrl.IndexOf(".") - 2) + "__" + urlProdName;
        //                        //newTextAd.adGroupId = adGroupId;
        //                        //don't add it yet, there is a check below to see if it meets criteria
        //                        SeedKeyword[] keywordsArray = new SeedKeyword[] { new SeedKeyword() };
        //                        keywordsArray = keywords.ToArray();
        //                        //add variations if requested
        //                        if (GetKeywordsFromLandingPage)
        //                        {
        //                            SiteKeywordGroups siteKeywordGroups = keywordToolService.getKeywordsFromSite(newTextAd.destinationUrl, false, Languages, Countries);
        //                            int maxVariations = 0;
        //                            bool AdAdded = false;
        //                            // Associate this ad group with the newly created campaign.  Send
        //                            // the request to add the new ad group.
        //                            AdGroup myAdGroup; //= adgroupService.addAdGroup(campaignId, newAdGroup);
        //                            long adGroupId = 0; //= myAdGroup.id;
        //                            if (siteKeywordGroups.keywords != null)
        //                            {
        //                                foreach (SiteKeyword sitekeyword in siteKeywordGroups.keywords)
        //                                {
        //                                    //Trace.TraceInformation("Checking Site Keyword " + maxVariations + ":" + sitekeyword.text);
        //                                    // check for low compitition and high search volumes
        //                                    if (sitekeyword.advertiserCompetitionScale <= MaxAdvertiserCompetitionScale && sitekeyword.lastMonthSearchVolume >= MinSearchVolumeScale)
        //                                    {
        //                                        // Add keywords to the newly created ad group.
        //                                        //add keywords and url to dbs
        //                                        AffiliTrac.Entities.Keywords kws = new AffiliTrac.Entities.Keywords();
        //                                        kws.KeywordRefId = Guid.NewGuid();
        //                                        kws.Keywords = sitekeyword.text;
        //                                        kws.Url = newTextAd.destinationUrl;
        //                                        kws.SiteCategoryRefId = siteCategory.SiteCategoryRefId;
        //                                        DataRepository.KeywordsProvider.Insert(kws);
        //                                        CriterionService criterionService = (CriterionService)user.GetService(ApiServices.v200906.CampaignCriterionService);
        //                                        // check for low compitition and high search volumes
        //                                        #region Create Ad & Keywords from the Product Name
        //                                        if (!AdAdded)
        //                                        {
        //                                            // Associate this ad group with the newly created campaign.  Send
        //                                            // the request to add the new ad group.
        //                                            myAdGroup = adgroupService.addAdGroup(campaignId, newAdGroup);
        //                                            adGroupId = myAdGroup.id;
        //                                            newTextAd.adGroupId = adGroupId;
        //                                            // create the new add
        //                                            try
        //                                            {
        //                                                //we found a keyword that meets criteria so ad the new Ad.
        //                                                Ad[] myAds = adService.addAds(new Ad[] { newTextAd });
        //                                                GroupAdCount++;
        //                                                Trace.TraceInformation("Text ad" + GroupAdCount + ": " + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2);
        //                                                //Trace.TraceInformation("Text ad: " + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2);
        //                                                AdAdded = true;
        //                                            }
        //                                            catch
        //                                            {
        //                                                //do nothing
        //                                                Trace.TraceError("***Text ad Failed:" + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2);
        //                                            }
        //                                            //Add the Product name as a whole phrase
        //                                            try
        //                                            {
        //                                                //add keywords and url to dbs
        //                                                kws = new AffiliTrac.Entities.Keywords();
        //                                                kws.KeywordRefId = Guid.NewGuid();
        //                                                kws.Keywords = cleanProdName;
        //                                                kws.Url = newTextAd.destinationUrl;
        //                                                kws.SiteCategoryRefId = siteCategory.SiteCategoryRefId;
        //                                                DataRepository.KeywordsProvider.Insert(kws);
        //                                                Keyword newKeyword = new Keyword();
        //                                                newKeyword.adGroupId = adGroupId;
        //                                                newKeyword.type = (KeywordType)Enum.ToObject(typeof(KeywordType), AdKeywordType);
        //                                                newKeyword.text = cleanProdName;
        //                                                //TODO: Use the Traffic Estimator to determine the
        //                                                // the maxCpc to use
        //                                                newKeyword.maxCpc = KeywordMaxCpc;
        //                                                newKeyword.maxCpcSpecified = true;
        //                                                newKeyword.criterionType = CriterionType.Keyword;
        //                                                newKeyword.destinationUrl = destinationUrlPrefix + siteCategory.PageUrl.Substring(2, siteCategory.PageUrl.IndexOf(".") - 2) + "__" + urlProdName;
        //                                                Criterion[] newCriteria = new Criterion[] { newKeyword };
        //                                                newCriteria[0].destinationUrl = newKeyword.destinationUrl;
        //                                                criterionService.addCriteria(newCriteria);
        //                                            }
        //                                            catch
        //                                            {
        //                                                //do nothing
        //                                                Trace.TraceError("***Add Criteria Failed: Keyword" + cleanProdName);
        //                                            }
        //                                            //Add the individual product name keywords
        //                                            foreach (SeedKeyword sk in keywordsArray)
        //                                            {
        //                                                try
        //                                                {
        //                                                    //add keywords and url to dbs
        //                                                    kws = new AffiliTrac.Entities.Keywords();
        //                                                    kws.KeywordRefId = Guid.NewGuid();
        //                                                    kws.Keywords = sk.text;
        //                                                    kws.Url = newTextAd.destinationUrl;
        //                                                    kws.SiteCategoryRefId = siteCategory.SiteCategoryRefId;
        //                                                    DataRepository.KeywordsProvider.Insert(kws);
        //                                                    // Add keywords to the newly created ad group.
        //                                                    Keyword newKeyword = new Keyword();
        //                                                    newKeyword.adGroupId = adGroupId;
        //                                                    newKeyword.type = (KeywordType)Enum.ToObject(typeof(KeywordType), AdKeywordType);
        //                                                    newKeyword.text = sk.text;
        //                                                    //TODO: Use the Traffic Estimator to determine the
        //                                                    // the maxCpc to use
        //                                                    newKeyword.maxCpc = KeywordMaxCpc;
        //                                                    newKeyword.maxCpcSpecified = true;
        //                                                    newKeyword.criterionType = CriterionType.Keyword;
        //                                                    newKeyword.destinationUrl = destinationUrlPrefix + siteCategory.PageUrl.Substring(2, siteCategory.PageUrl.IndexOf(".") - 2) + "__" + urlProdName;
        //                                                    Criterion[] newCriteria = new Criterion[] { newKeyword };
        //                                                    newCriteria[0].destinationUrl = newKeyword.destinationUrl;
        //                                                    criterionService.addCriteria(newCriteria);
        //                                                }
        //                                                catch
        //                                                {
        //                                                    //do nothing
        //                                                    Trace.TraceError("***Add Criteria Failed: Keyword" + sk.text);
        //                                                }
        //                                            }
        //                                        }
        //                                        #endregion
        //                                        #region Create keywords from the keyword suggestion gotten from the landing page
        //                                        try
        //                                        {
        //                                            Keyword newKeyword = new Keyword();
        //                                            newKeyword = new Keyword();
        //                                            newKeyword.adGroupId = adGroupId;
        //                                            newKeyword.type = (KeywordType)Enum.ToObject(typeof(KeywordType), AdKeywordType);
        //                                            newKeyword.text = sitekeyword.text;
        //                                            //TODO: Use the Traffic Estimator to determine the
        //                                            // the maxCpc to use
        //                                            newKeyword.maxCpc = KeywordMaxCpc;
        //                                            newKeyword.maxCpcSpecified = true;
        //                                            newKeyword.criterionType = CriterionType.Keyword;
        //                                            newKeyword.destinationUrl = destinationUrlPrefix + siteCategory.PageUrl.Substring(2, siteCategory.PageUrl.IndexOf(".") - 2) + "__" + urlProdName;
        //                                            Criterion[] newCriteria = new Criterion[] { newKeyword };
        //                                            newCriteria[0].destinationUrl = newKeyword.destinationUrl;
        //                                            criterionService.addCriteria(newCriteria);
        //                                        }
        //                                        catch
        //                                        {
        //                                            //do nothing
        //                                            Trace.TraceError("***Add Criteria Failed: Keyword" + sitekeyword.text);
        //                                        }
        //                                        #endregion
        //                                    }
        //                                    maxVariations++;
        //                                    if (maxVariations > MaxVariations)
        //                                        break;
        //                                }
        //                            }
        //                            //check add variations for product name raw keywords
        //                            try
        //                            {
        //                                KeywordVariations keywordVariations = keywordToolService.getKeywordVariations(keywordsArray, true, Languages, Countries);
        //                                foreach (KeywordVariation keywordVariation in keywordVariations.moreSpecific)
        //                                {
        //                                    if (Languages[0].ToString() == keywordVariation.language && keywordVariation.advertiserCompetitionScale <= MaxAdvertiserCompetitionScale && keywordVariation.lastMonthSearchVolume >= MinSearchVolumeScale)
        //                                    {
        //                                        // Add keywords to the newly created ad group.
        //                                        //add keywords and url to dbs
        //                                        AffiliTrac.Entities.Keywords kws = new AffiliTrac.Entities.Keywords();
        //                                        kws.KeywordRefId = Guid.NewGuid();
        //                                        kws.Keywords = keywordVariation.text;
        //                                        kws.Url = newTextAd.destinationUrl;
        //                                        kws.SiteCategoryRefId = siteCategory.SiteCategoryRefId;
        //                                        DataRepository.KeywordsProvider.Insert(kws);
        //                                        CriterionService criterionService = (CriterionService)user.GetService(ApiServices.v200906.CampaignCriterionService);
        //                                        // check for low compitition and high search volumes
        //                                        #region Create Ad & Keywords from the Product Name
        //                                        if (!AdAdded)
        //                                        {
        //                                            // Associate this ad group with the newly created campaign.  Send
        //                                            // the request to add the new ad group.
        //                                            myAdGroup = adgroupService.addAdGroup(campaignId, newAdGroup);
        //                                            adGroupId = myAdGroup.id;
        //                                            newTextAd.adGroupId = adGroupId;
        //                                            // create the new add
        //                                            try
        //                                            {
        //                                                //we found a keyword that meets criteria so ad the new Ad.
        //                                                Ad[] myAds = adService.addAds(new Ad[] { newTextAd });
        //                                                GroupAdCount++;
        //                                                Trace.TraceInformation("Text ad" + GroupAdCount + ": " + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2);
        //                                                //Trace.TraceInformation("Text ad: " + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2);
        //                                                AdAdded = true;
        //                                            }
        //                                            catch
        //                                            {
        //                                                //do nothing
        //                                                Trace.TraceError("***Text ad Failed:" + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2);
        //                                            }
        //                                            //Add the Product name as a whole phrase
        //                                            try
        //                                            {
        //                                                //add keywords and url to dbs
        //                                                kws = new AffiliTrac.Entities.Keywords();
        //                                                kws.KeywordRefId = Guid.NewGuid();
        //                                                kws.Keywords = cleanProdName;
        //                                                kws.Url = newTextAd.destinationUrl;
        //                                                kws.SiteCategoryRefId = siteCategory.SiteCategoryRefId;
        //                                                DataRepository.KeywordsProvider.Insert(kws);
        //                                                Keyword newKeyword = new Keyword();
        //                                                newKeyword.adGroupId = adGroupId;
        //                                                newKeyword.type = (KeywordType)Enum.ToObject(typeof(KeywordType), AdKeywordType);
        //                                                newKeyword.text = cleanProdName;
        //                                                //TODO: Use the Traffic Estimator to determine the
        //                                                // the maxCpc to use
        //                                                newKeyword.maxCpc = KeywordMaxCpc;
        //                                                newKeyword.maxCpcSpecified = true;
        //                                                newKeyword.criterionType = CriterionType.Keyword;
        //                                                newKeyword.destinationUrl = destinationUrlPrefix + siteCategory.PageUrl.Substring(2, siteCategory.PageUrl.IndexOf(".") - 2) + "__" + urlProdName;
        //                                                Criterion[] newCriteria = new Criterion[] { newKeyword };
        //                                                newCriteria[0].destinationUrl = newKeyword.destinationUrl;
        //                                                criterionService.addCriteria(newCriteria);
        //                                            }
        //                                            catch (Exception ex)
        //                                            {
        //                                                //do nothing
        //                                                Trace.TraceError("***Add Criteria Failed: Keyword" + cleanProdName + ex.Message);
        //                                            }
        //                                            //Add the individual product name keywords
        //                                            foreach (SeedKeyword sk in keywordsArray)
        //                                            {
        //                                                try
        //                                                {
        //                                                    //add keywords and url to dbs
        //                                                    kws = new AffiliTrac.Entities.Keywords();
        //                                                    kws.KeywordRefId = Guid.NewGuid();
        //                                                    kws.Keywords = sk.text;
        //                                                    kws.Url = newTextAd.destinationUrl;
        //                                                    kws.SiteCategoryRefId = siteCategory.SiteCategoryRefId;
        //                                                    DataRepository.KeywordsProvider.Insert(kws);
        //                                                    // Add keywords to the newly created ad group.
        //                                                    Keyword newKeyword = new Keyword();
        //                                                    newKeyword.adGroupId = adGroupId;
        //                                                    newKeyword.type = (KeywordType)Enum.ToObject(typeof(KeywordType), AdKeywordType);
        //                                                    newKeyword.text = sk.text;
        //                                                    //TODO: Use the Traffic Estimator to determine the
        //                                                    // the maxCpc to use
        //                                                    newKeyword.maxCpc = KeywordMaxCpc;
        //                                                    newKeyword.maxCpcSpecified = true;
        //                                                    newKeyword.criterionType = CriterionType.Keyword;
        //                                                    newKeyword.destinationUrl = destinationUrlPrefix + siteCategory.PageUrl.Substring(2, siteCategory.PageUrl.IndexOf(".") - 2) + "__" + urlProdName;
        //                                                    Criterion[] newCriteria = new Criterion[] { newKeyword };
        //                                                    newCriteria[0].destinationUrl = newKeyword.destinationUrl;
        //                                                    criterionService.addCriteria(newCriteria);
        //                                                }
        //                                                catch (Exception ex)
        //                                                {
        //                                                    //do nothing
        //                                                    Trace.TraceError("***Add Criteria Failed: Keyword" + cleanProdName + ex.Message);
        //                                                }
        //                                            }
        //                                        }
        //                                        #endregion
        //                                        #region Create keywords from the keyword suggestion gotten from the landing page
        //                                        try
        //                                        {
        //                                            Keyword newKeyword = new Keyword();
        //                                            newKeyword = new Keyword();
        //                                            newKeyword.adGroupId = adGroupId;
        //                                            newKeyword.type = (KeywordType)Enum.ToObject(typeof(KeywordType), AdKeywordType);
        //                                            newKeyword.text = keywordVariation.text;
        //                                            //TODO: Use the Traffic Estimator to determine the
        //                                            // the maxCpc to use
        //                                            newKeyword.maxCpc = KeywordMaxCpc;
        //                                            newKeyword.maxCpcSpecified = true;
        //                                            newKeyword.criterionType = CriterionType.Keyword;
        //                                            newKeyword.destinationUrl = destinationUrlPrefix + siteCategory.PageUrl.Substring(2, siteCategory.PageUrl.IndexOf(".") - 2) + "__" + urlProdName;
        //                                            Criterion[] newCriteria = new Criterion[] { newKeyword };
        //                                            newCriteria[0].destinationUrl = newKeyword.destinationUrl;
        //                                            criterionService.addCriteria(newCriteria);
        //                                        }
        //                                        catch (Exception ex)
        //                                        {
        //                                            //do nothing
        //                                            Trace.TraceError("***Add Criteria Failed: Keyword" + cleanProdName + ex.Message);
        //                                        }
        //                                        #endregion
        //                                    }
        //                                }
        //                            }
        //                            catch
        //                            {//this call fails quite a bit so we need the try catch
        //                            }
        //                        }
        //                        else
        //                        {
        //                            #region Create Keywords from the Product Name Only
        //                            //  create the ad
        //                            // Associate this ad group with the newly created campaign.  Send
        //                            // the request to add the new ad group.
        //                            AdGroup myAdGroup = adgroupService.addAdGroup(campaignId, newAdGroup);
        //                            long adGroupId = myAdGroup.id;
        //                            newTextAd.adGroupId = adGroupId;
        //                            try
        //                            {
        //                                //we found a keyword that meets criteria so ad the new Ad.
        //                                Ad[] myAds = adService.addAds(new Ad[] { newTextAd });
        //                                GroupAdCount++;
        //                                Trace.TraceInformation("Text ad" + GroupAdCount + ": " + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2);
        //                                //Trace.TraceInformation("Text ad: " + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2);
        //                            }
        //                            catch
        //                            {
        //                                //do nothing
        //                                Trace.TraceError("***Text ad Failed:" + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2);
        //                            }
        //                            //Add the Product name as a whole phrase
        //                            CriterionService criterionService = (CriterionService)user.GetService(ApiServices.v200906.CampaignCriterionService);
        //                            //add keywords and url to dbs
        //                            AffiliTrac.Entities.Keywords kws = new AffiliTrac.Entities.Keywords();
        //                            kws.KeywordRefId = Guid.NewGuid();
        //                            kws.Keywords = cleanProdName;
        //                            kws.Url = newTextAd.destinationUrl;
        //                            kws.SiteCategoryRefId = siteCategory.SiteCategoryRefId;
        //                            DataRepository.KeywordsProvider.Insert(kws);
        //                            try
        //                            {
        //                                Keyword newKeyword = new Keyword();
        //                                newKeyword.adGroupId = adGroupId;
        //                                newKeyword.type = (KeywordType)Enum.ToObject(typeof(KeywordType), AdKeywordType);
        //                                newKeyword.text = cleanProdName;
        //                                //TODO: Use the Traffic Estimator to determine the
        //                                // the maxCpc to use
        //                                newKeyword.maxCpc = KeywordMaxCpc;
        //                                newKeyword.maxCpcSpecified = true;
        //                                newKeyword.criterionType = CriterionType.Keyword;
        //                                newKeyword.destinationUrl = destinationUrlPrefix + siteCategory.PageUrl.Substring(2, siteCategory.PageUrl.IndexOf(".") - 2) + "__" + urlProdName;
        //                                Criterion[] newCriteria = new Criterion[] { newKeyword };
        //                                newCriteria[0].destinationUrl = newKeyword.destinationUrl;
        //                                criterionService.addCriteria(newCriteria);
        //                            }
        //                            catch
        //                            {
        //                                //do nothing
        //                                Trace.TraceError("***Add Criteria Failed: Keyword" + cleanProdName);
        //                            }
        //                            //Add the individual product name keywords
        //                            foreach (SeedKeyword sk in keywordsArray)
        //                            {
        //                                //add keywords and url to dbs
        //                                kws = new AffiliTrac.Entities.Keywords();
        //                                kws.KeywordRefId = Guid.NewGuid();
        //                                kws.Keywords = sk.text;
        //                                kws.Url = newTextAd.destinationUrl;
        //                                kws.SiteCategoryRefId = siteCategory.SiteCategoryRefId;
        //                                DataRepository.KeywordsProvider.Insert(kws);
        //                                try
        //                                {
        //                                    // Add keywords to the newly created ad group.
        //                                    Keyword newKeyword = new Keyword();
        //                                    newKeyword.adGroupId = adGroupId;
        //                                    newKeyword.type = (KeywordType)Enum.ToObject(typeof(KeywordType), AdKeywordType);
        //                                    newKeyword.text = sk.text;
        //                                    //TODO: Use the Traffic Estimator to determine the
        //                                    // the maxCpc to use
        //                                    newKeyword.maxCpc = KeywordMaxCpc;
        //                                    newKeyword.maxCpcSpecified = true;
        //                                    newKeyword.criterionType = CriterionType.Keyword;
        //                                    newKeyword.destinationUrl = destinationUrlPrefix + siteCategory.PageUrl.Substring(2, siteCategory.PageUrl.IndexOf(".") - 2) + "__" + urlProdName;
        //                                    Criterion[] newCriteria = new Criterion[] { newKeyword };
        //                                    newCriteria[0].destinationUrl = newKeyword.destinationUrl;
        //                                    criterionService.addCriteria(newCriteria);
        //                                }
        //                                catch
        //                                {
        //                                    //do nothing
        //                                    Trace.TraceError("***Add Criteria Failed: Keyword" + sk.text);
        //                                }
        //                            }
        //                            #endregion
        //                        }
        //                        if (GroupAdCount >= MaxAdGroups)
        //                            break;
        //                    }
        //                }
        //            }
        //            #endregion
        //        }
        //        #endregion
        //        #region Log everything created
        //        AdGroup[] adGroups = adgroupService.getAllAdGroups(campaignId);
        //        foreach (AdGroup adGroup in adGroups)
        //        {
        //            Trace.TraceInformation("Ad group: " + adGroup.name);
        //            Ad[] ads = adService.getAllAds(new long[] { adGroup.id });
        //            foreach (Ad ad in ads)
        //            {
        //                if (ad is TextAd)
        //                {
        //                    TextAd textAd = (TextAd)ad;
        //                    Trace.TraceInformation("Text ad: " + textAd.headline + " Text Line1:" + textAd.description1 + " Text Line2:" + textAd.description2);
        //                }
        //            }
        //        }
        //        #endregion
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}
        /// <summary>
        /// CreateKeywordsByAffiliateSiteRefId
        /// </summary>
        /// <param name="CheckAgainstAdwordsAPI"></param>
        /// <param name="UseSandbox"></param>
        /// <param name="AffiliateSiteRefId"></param>
        /// <param name="destinationUrlPrefix"></param>
        /// <param name="MaxAdvertiserCompetitionScale"></param>
        /// <param name="MinSearchVolumeScale"></param>
        /// <param name="MaxEstimateCpc"></param>
        /// <param name="MinEstimateCpc"></param>
        /// <param name="MaxEstimateClicksPerDay"></param>
        /// <param name="MinEstimateClicksPerDay"></param>
        /// <param name="getVariations"></param>
        /// <param name="getSiteKeywords"></param>
        /// <param name="Languages"></param>
        /// <param name="Countries"></param>
        public VList<SiteCategoryKeywords> CreateKeywordsByAffiliateSiteRefId(bool CheckAgainstAdwordsAPI, bool UseSandbox, Guid AffiliateSiteRefId,
            bool getVariations, bool getSiteKeywords, int maxKeywordsPerEstimate, String[] Languages,
            String[] Countries, decimal maxApiUsageDollars)
        {
            // Create a user (reads headers from App.config file).
            AdWordsUser user = new AdWordsUser();

            VList<SiteCategoryKeywords> reserachList = new VList<SiteCategoryKeywords>();

            //get seo parameters
            SeoParameters seop = DataRepository.SeoParametersProvider.GetByAffiliateSiteRefId(AffiliateSiteRefId)[0];

            if (CheckAgainstAdwordsAPI)
            {
                if (UseSandbox)
                    user.UseSandbox();	// use sandbox

                AccountService accountService = (AccountService)user.GetService(ApiServices.v13.AccountService);
                string[] accounts = accountService.getClientAccounts();
            }

            try
            {
                #region Create your Services
                //create your services
                List<KeywordRequest> keywords = new List<KeywordRequest>();
                //List<SeedKeyword> keywordsForVariation = new List<SeedKeyword>();

                TrafficEstimatorService trafficEstimatorService = (TrafficEstimatorService)user.GetService(ApiServices.v13.TrafficEstimatorService);
                AdGroupAdServicev200906 adService = (AdGroupAdServicev200906)user.GetService(ApiServices.v200906.AdGroupAdService);

                KeywordToolService keywordToolService = (KeywordToolService)user.GetService(ApiServices.v13.KeywordToolService);
                AdGroupServicev200906 adgroupService = (AdGroupServicev200906)user.GetService(ApiServices.v200906.AdGroupService);

                #endregion

                #region Enumerate thru all the categories
                bool SiteCategoryKeywordMaxCntReached = false;
                int SiteCategoryKeywordMaxCnt = 0;
                int SiteCategoryAdMaxCnt = 0;
                int SiteCategoryKeywordCnt = 0;

                // calculate max values by budget
                CalculateKeywordCountsPerSiteCategoryByApiBudget(out SiteCategoryKeywordMaxCnt, out SiteCategoryAdMaxCnt);

                //enumerate thru all the categories
                foreach (SiteCategory siteCategory in DataRepository.SiteCategoryProvider.GetByAffiliateSiteRefId(AffiliateSiteRefId))
                {
                    if (SiteCategoryKeywordMaxCntReached)
                    {
                        SiteCategoryKeywordMaxCntReached = false;
                        SiteCategoryKeywordCnt = 0;
                    }

                    DataRepository.SiteCategoryProvider.DeepLoad(siteCategory, true, DeepLoadType.IncludeChildren, typeof(TList<SiteCategoryCategoryMapping>));

                    #region Enumerate thru the category mappings to get the merchants
                    //enumerate thru the categoru mappings to get the merchants
                    foreach (SiteCategoryCategoryMapping catMap in siteCategory.SiteCategoryCategoryMappingCollection)
                    {
                        if (SiteCategoryKeywordMaxCntReached)
                            break;

                        DataRepository.SiteCategoryCategoryMappingProvider.DeepLoad(catMap, true, DeepLoadType.IncludeChildren, typeof(Category));
                        DataRepository.CategoryProvider.DeepLoad(catMap.CategoryRefIdSource, true, DeepLoadType.IncludeChildren, typeof(TList<Merchant>));
                        catMap.CategoryRefIdSource.MerchantCollection.Shuffle();
                        foreach (Merchant merch in catMap.CategoryRefIdSource.MerchantCollection)
                        {
                            if (SiteCategoryKeywordMaxCntReached)
                                break;

                            DataRepository.MerchantProvider.DeepLoad(merch, true, DeepLoadType.IncludeChildren, typeof(TList<Product>));

                            //shuffle the products
                            merch.ProductCollection.Shuffle();

                            // enumerate thru all the merchant's products
                            foreach (Product prod in merch.ProductCollection)
                            {
                                if (SiteCategoryKeywordMaxCntReached)
                                    break;

                                Trace.TraceInformation(prod.Name);
                                //scrub the product name to extract the keywords
                                string cleanProdKeywords = StringUtils.ScrubProdName(StringUtils.RemoveDuplicateWords(prod.Name));

                                string urlProdRefId = siteCategory.ProductUrlPrefix + prod.ProductRefId.ToString();

                                keywords.Clear();

                                //create an array of keywords
                                string[] rawKeywords = new string[] { "" };
                                //seperate into individual keywords
                                rawKeywords = cleanProdKeywords.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                                List<string> cleanKeyword = new List<string>();
                                foreach (string str in rawKeywords)
                                {
                                    int tryInt = 0; //not empty, not a number, and not lower case
                                    if (str.Length > 2 && str.Trim() != "" && !int.TryParse(str.Trim(), out tryInt)) //&& !isLowerCase(str.Trim().Substring(0, 1).ToCharArray()[0])
                                    {
                                        cleanKeyword.Add(StringUtils.ScrubKeywords(str));
                                    }
                                }

                                //seperate into keywords phrases
                                //TODO: KeywordPhraseWordCount use this config
                                for (int i = 0; i < rawKeywords.Length - 1; i++)
                                {
                                    int tryInt = 0; //not empty, not a number, and not lower case
                                    if (rawKeywords[i].Length > 2 && rawKeywords[i].Trim() != "" && !int.TryParse(rawKeywords[i].Trim(), out tryInt) && rawKeywords[i + 1].Length > 2 && rawKeywords[i + 1].Trim() != "" && !int.TryParse(rawKeywords[i + 1].Trim(), out tryInt))
                                    {
                                        cleanKeyword.Add(StringUtils.ScrubKeywords(rawKeywords[i] + " " + StringUtils.ScrubKeywords(rawKeywords[i + 1])));
                                    }
                                }

                                //also add a key word for the entire product name
                                cleanKeyword.Add(prod.Name);

                                foreach (string keyword in cleanKeyword)
                                {
                                    if (DataRepository.KeywordsProvider.GetByUrlKeywords(urlProdRefId, keyword) == null)
                                    {
                                        //add keywords and url to dbs
                                        AffiliTrac.Entities.Keywords kws = new AffiliTrac.Entities.Keywords();
                                        kws.KeywordRefId = Guid.NewGuid();
                                        kws.Keywords = keyword;
                                        kws.Url = urlProdRefId;
                                        kws.ProductRefId = prod.ProductRefId;
                                        kws.SiteCategoryRefId = siteCategory.SiteCategoryRefId;

                                        DataRepository.KeywordsProvider.Insert(kws);
                                        SiteCategoryKeywordCnt += 1;

                                        if (SiteCategoryKeywordCnt >= SiteCategoryKeywordMaxCnt)
                                        {
                                            SiteCategoryKeywordMaxCntReached = true;
                                            break;
                                        }
                                    }
                                }
                            }

                        }
                    }
                    #endregion
                }
                #endregion

                #region Check Traffic Estimates for Keywords
                if (CheckAgainstAdwordsAPI)
                {
                    try
                    {
                        int apiUnitUsage = 0;
                        reserachList = DataRepository.SiteCategoryKeywordsProvider.GetDistinct(AffiliateSiteRefId);
                        foreach (SiteCategoryKeywords kw in reserachList)
                        {
                            //TODO: check usage
                            //if (apiUsage >= maxApiUsage)
                            //    break;

                            KeywordRequest sw = new KeywordRequest();
                            sw.text = kw.Keywords;

                            sw.type = kw.Keywords.IndexOf(' ') > 0 ? KeywordType.Phrase : KeywordType.Broad; //check to see if it's a phrase
                            sw.maxCpc = seop.MaxEstimateCpc;
                            sw.maxCpcSpecified = true;
                            sw.typeSpecified = true;
                            keywords.Add(sw);

                            #region Add Aditional Search types
                            //sw = new KeywordRequest();
                            //sw.text = StringUtils.ScrubKeywords(str);
                            //if (sw.text.Length > 2 && sw.text.Trim() != "")
                            //{
                            //    sw.type = KeywordType.Exact;
                            //    sw.maxCpc = 1000000;
                            //    sw.maxCpcSpecified = true;
                            //    sw.typeSpecified = true;

                            //    keywords.Add(sw);
                            //}

                            //sw = new KeywordRequest();
                            //sw.text = StringUtils.ScrubKeywords(str);
                            //if (sw.text.Length > 2 && sw.text.Trim() != "")
                            //{
                            //    sw.type = KeywordType.Phrase;
                            //    sw.maxCpc = 1000000;
                            //    sw.maxCpcSpecified = true;
                            //    sw.typeSpecified = true;

                            //    keywords.Add(sw);
                            //}
                            #endregion
                        }

                        // check traffic estimates 100 at a time
                        for (int i = 0; i < keywords.Count; i += maxKeywordsPerEstimate)
                        {
                            if (i >= keywords.Count)
                                break;

                            KeywordRequest[] keywordsRequestArray = new KeywordRequest[] { new KeywordRequest() };
                            keywordsRequestArray = keywords.GetRange(i, keywords.Count - i >= maxKeywordsPerEstimate ? maxKeywordsPerEstimate : keywords.Count - i).ToArray();
                            KeywordEstimate[] KeywordEstimates = null;

                            try
                            {
                                KeywordEstimates = trafficEstimatorService.estimateKeywordList(keywordsRequestArray);

                                foreach (KeywordRequest kr in keywordsRequestArray)
                                {
                                    Trace.TraceInformation("Accepted keyword :" + kr.text);
                                }

                                //apiUsage += DataRepository.PpcApiRequestTypesProvider.GetByName("").ApiUnitCostPerItem; //((decimal)keywordsRequestArray.Length * (decimal).20);

                                //Trace.TraceInformation("API Usage :" + apiUsage.ToString("{0:c}"));

                            }
                            catch (Exception ex)
                            {
                                //do nothing
                                Trace.TraceError("***Get Keyword Traffic Estimates Failed: " + ex.Message);
                                foreach (KeywordRequest kr in keywordsRequestArray)
                                {
                                    Trace.TraceInformation("Possible bad keyword :" + kr.text);
                                }

                                // TODO: now go thru and do them individually

                                continue;

                            }

                            if (KeywordEstimates.Length > 0)
                            {
                                int c = 0;
                                foreach (KeywordEstimate keywordEstimate in KeywordEstimates)
                                {
                                    //Trace.TraceInformation("Checking Site Keyword " + maxVariations + ":" + sitekeyword.text);
                                    // check for low compitition and high search volumes

                                    if (UseSandbox || (keywordEstimate.lowerClicksPerDay >= seop.MinEstimateClicksPerDay && keywordEstimate.lowerCpc <= seop.MaxEstimateCpc))
                                    {
                                        // mark MeetsSeoParm on all keyword records with this keyword
                                        TList<Keywords> updateList = DataRepository.KeywordsProvider.GetByKeywords(keywordsRequestArray[c].text);
                                        foreach (Keywords ukw in updateList)
                                        {
                                            ukw.MeetsSeoCriteria = true;
                                        }

                                        DataRepository.KeywordsProvider.Update(updateList);
                                    }

                                    c++;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        //do nothing
                        Trace.TraceError("***Get Keyword Traffic Estimates Failed: " + ex.Message);
                    }
                }

                #endregion

                //go get the updated list again
                reserachList = DataRepository.SiteCategoryKeywordsProvider.GetDistinct(AffiliateSiteRefId);

                return reserachList;

            }
            catch (Exception ex)
            {
                Trace.TraceError("Error:" + ex.Message);
                throw ex;
            }
        }
        /// <summary>
        /// Creates the keywords.
        /// </summary>
        /// <param name="user">The Google Ads user.</param>
        /// <param name="adGroupId">The ad group ID.</param>
        /// <param name="keywords">The keywords to create.</param>
        /// <returns>The newly created ad group criteria.</returns>
        public aw::AdGroupCriterion[] CreateKeywords(AdWordsUser user, long adGroupId,
                                                     string[] keywords)
        {
            // Get the AdGroupCriterionService.
            using (aw::AdGroupCriterionService adGroupCriterionService =
                       (aw::AdGroupCriterionService)user.GetService(AdWordsService.v201809
                                                                    .AdGroupCriterionService))
            {
                List <aw::AdGroupCriterionOperation> operations =
                    new List <aw::AdGroupCriterionOperation>();

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

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

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

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

                    // Create the operations.
                    aw::AdGroupCriterionOperation operation = new aw::AdGroupCriterionOperation
                    {
                        @operator = aw::Operator.ADD,
                        operand   = keywordCriterion
                    };

                    operations.Add(operation);
                }

                // Create the keywords.
                aw::AdGroupCriterionReturnValue retVal =
                    adGroupCriterionService.mutate(operations.ToArray());

                // Display the results.
                foreach (aw::AdGroupCriterion adGroupCriterion in retVal.value)
                {
                    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 aw::Keyword).text,
                        (adGroupCriterion.criterion as aw::Keyword).matchType);
                }

                // Return the newly created keywords.
                return(retVal.value);
            }
        }