/// <summary>
        /// Adds multiple campaigns to a campaign group.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignGroupId">The campaign group ID.</param>
        /// <param name="campaignIds">IDs of the campaigns to be added to the campaign group.</param>
        private static void AddCampaignsToGroup(AdWordsUser user, long campaignGroupId,
                                                long[] campaignIds)
        {
            using (CampaignService campaignService = (CampaignService)user.GetService(
                       AdWordsService.v201806.CampaignService)) {
                List <CampaignOperation> operations = new List <CampaignOperation>();

                for (int i = 0; i < campaignIds.Length; i++)
                {
                    Campaign campaign = new Campaign {
                        id = campaignIds[i],
                        campaignGroupId = campaignGroupId
                    };

                    CampaignOperation operation = new CampaignOperation {
                        operand   = campaign,
                        @operator = Operator.SET
                    };
                    operations.Add(operation);
                }

                try {
                    CampaignReturnValue retval             = campaignService.mutate(operations.ToArray());
                    List <long>         updatedCampaignIds = new List <long>();
                    retval.value.ToList().ForEach(
                        updatedCampaign => updatedCampaignIds.Add(updatedCampaign.id));

                    // Display the results.
                    Console.WriteLine("The following campaign IDs were added to the campaign group " +
                                      "with ID '{0}':\n\t{1}'", campaignGroupId, string.Join(", ", updatedCampaignIds));
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to add campaigns to campaign group.", e);
                }
            }
        }
Beispiel #2
0
        /// <summary>
        ///  Adds campaigns to a CampaignGroup in the specified client account.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignGroupResourceName">The resource name of the campaign
        /// group.</param>
        /// <param name="campaignIds">The IDs of the campaigns to add to the campaign
        /// group.</param>
        private static void AddCampaignsToGroup(GoogleAdsClient client, long customerId,
                                                String campaignGroupResourceName, long[] campaignIds)
        {
            CampaignServiceClient campaignServiceClient = client.GetService(
                Services.V0.CampaignService);
            List <CampaignOperation> operations = new List <CampaignOperation>();

            foreach (long campaignId in campaignIds)
            {
                Campaign campaign = new Campaign()
                {
                    ResourceName  = ResourceNames.Campaign(customerId, campaignId),
                    CampaignGroup = campaignGroupResourceName
                };

                CampaignOperation op = new CampaignOperation()
                {
                    Update     = campaign,
                    UpdateMask = FieldMasks.AllSetFieldsOf(campaign)
                };
                operations.Add(op);
            }

            MutateCampaignsResponse response =
                campaignServiceClient.MutateCampaigns(customerId.ToString(), operations);

            Console.WriteLine($"Added {response.Results.Count} campaigns to campaign group " +
                              $"with resource name {campaignGroupResourceName}:");
            foreach (MutateCampaignResult campaignResponse in response.Results)
            {
                Console.WriteLine($"\t{campaignResponse.ResourceName}");
            }
        }
Beispiel #3
0
        // [END createBudget] MOE:strip_line

        /// <summary>
        /// Creates the campaign.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="budget">The campaign budget.</param>
        /// <returns>The newly created campaign.</returns>
        // [START createCampaign] MOE:strip_line
        private static Campaign CreateCampaign(AdWordsUser user, Budget budget)
        {
            // Get the CampaignService.
            CampaignService campaignService =
                (CampaignService)user.GetService(AdWordsService.v201705.CampaignService);

            // Create a Dynamic Search Ads campaign.
            Campaign campaign = new Campaign();

            campaign.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString();
            campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;

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

            BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();

            biddingConfig.biddingStrategyType     = BiddingStrategyType.MANUAL_CPC;
            campaign.biddingStrategyConfiguration = biddingConfig;

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

            // Required: Set the campaign's Dynamic Search Ads settings.
            DynamicSearchAdsSetting dynamicSearchAdsSetting = new DynamicSearchAdsSetting();

            // Required: Set the domain name and language.
            dynamicSearchAdsSetting.domainName   = "example.com";
            dynamicSearchAdsSetting.languageCode = "en";

            // Set the campaign settings.
            campaign.settings = new Setting[] { dynamicSearchAdsSetting };

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

            // 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.
                Campaign newCampaign = retVal.value[0];
                Console.WriteLine("Campaign with id = '{0}' and name = '{1}' was added.",
                                  newCampaign.id, newCampaign.name);
                return(newCampaign);
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to add campaigns.", e);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to be removed.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            using (CampaignService campaignService = (CampaignService)user.GetService(
                       AdWordsService.v201708.CampaignService)) {
                // Create campaign with REMOVED status.
                Campaign campaign = new Campaign();
                campaign.id     = campaignId;
                campaign.status = CampaignStatus.REMOVED;

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

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

                    // Display the results.
                    if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                    {
                        Campaign removedCampaign = retVal.value[0];
                        Console.WriteLine("Campaign with id = \"{0}\" was renamed to \"{1}\" and removed.",
                                          removedCampaign.id, removedCampaign.name);
                    }
                    else
                    {
                        Console.WriteLine("No campaigns were removed.");
                    }
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to remove campaign.", e);
                }
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to be updated.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            // Get the CampaignService.
              CampaignService campaignService =
              (CampaignService)user.GetService(AdWordsService.v201601.CampaignService);

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

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

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

            // Display the results.
            if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
              Campaign updatedCampaign = retVal.value[0];
              Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was updated.",
              updatedCampaign.name, updatedCampaign.id);
            } else {
              Console.WriteLine("No campaigns were updated.");
            }
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to update campaign.", e);
              }
        }
Beispiel #6
0
        public static CampaignReturnValue SetCampaignStatus(AdWordsUser user, long campaignId, CampaignStatus campaignStatus)
        {
            CampaignReturnValue retVal;

            using (CampaignService campaignService =
                       (CampaignService)user.GetService(AdWordsService.v201710.CampaignService))
            {
                // Create the campaign.
                Campaign campaign = new Campaign();
                campaign.id     = campaignId;
                campaign.status = campaignStatus;

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

                try
                {
                    // Update the campaign.
                    retVal = campaignService.mutate(
                        new CampaignOperation[] { operation });
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to update campaign.", e);
                }
                return(retVal);
            }
        }
        /// <summary>
        /// Builds new campaign operations for the specified customer ID.
        /// </summary>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignBudgetResourceName">The resource name of campaign budget to be
        /// used to create campaigns.</param>
        /// <returns>The campaign operations.</returns>
        private static List <CampaignOperation> BuildCampaignOperations(long customerId,
                                                                        string campaignBudgetResourceName)
        {
            List <CampaignOperation> operations = new List <CampaignOperation>();

            for (int i = 0; i < NUMBER_OF_CAMPAIGNS_TO_ADD; i++)
            {
                // Creates a campaign.
                long     campaignId = GetNextTemporaryId();
                Campaign campaign   = new Campaign()
                {
                    ResourceName           = ResourceNames.Campaign(customerId, campaignId),
                    Name                   = "batch job campaign #" + ExampleUtilities.GetRandomString(),
                    AdvertisingChannelType = AdvertisingChannelType.Search,

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

                    // Sets the bidding strategy and budget.
                    ManualCpc      = new ManualCpc(),
                    CampaignBudget = campaignBudgetResourceName
                };

                // Creates a campaign operation and adds it to the operations list.
                CampaignOperation op = new CampaignOperation()
                {
                    Create = campaign
                };
                operations.Add(op);
            }

            return(operations);
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to be updated.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            using (CampaignService campaignService =
                       (CampaignService)user.GetService(AdWordsService.v201702.CampaignService)) {
                // Create the campaign.
                Campaign campaign = new Campaign();
                campaign.id     = campaignId;
                campaign.status = CampaignStatus.PAUSED;

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

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

                    // Display the results.
                    if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                    {
                        Campaign updatedCampaign = retVal.value[0];
                        Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was updated.",
                                          updatedCampaign.name, updatedCampaign.id);
                    }
                    else
                    {
                        Console.WriteLine("No campaigns were updated.");
                    }
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to update campaign.", e);
                }
            }
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign to be removed.</param>
    public void Run(AdWordsUser user, long campaignId) {
      // Get the CampaignService.
      CampaignService campaignService = (CampaignService) user.GetService(
          AdWordsService.v201509.CampaignService);

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

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

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

        // Display the results.
        if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
          Campaign removedCampaign = retVal.value[0];
          Console.WriteLine("Campaign with id = \"{0}\" was renamed to \"{1}\" and removed.",
              removedCampaign.id, removedCampaign.name);
        } else {
          Console.WriteLine("No campaigns were removed.");
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to remove campaign.", e);
      }
    }
Beispiel #10
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">ID of the campaign to be removed.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId)
        {
            // Get the CampaignService.
            CampaignServiceClient campaignService = client.GetService(Services.V4.CampaignService);

            // Create the operation, and set the Remove field to the resource name of the
            // campaign to be removed.
            CampaignOperation operation = new CampaignOperation()
            {
                Remove = ResourceNames.Campaign(customerId, campaignId)
            };

            try
            {
                // Remove the campaign.
                MutateCampaignsResponse retVal = campaignService.MutateCampaigns(
                    customerId.ToString(), new CampaignOperation[] { operation });

                // Display the results.
                foreach (MutateCampaignResult removedCampaign in retVal.Results)
                {
                    Console.WriteLine($"Campaign with resource name = '{0}' was removed.",
                                      removedCampaign.ResourceName);
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Beispiel #11
0
 public Scenario()
 {
     productOperation      = new ProductOperation();
     campaignOperation     = new CampaignOperation();
     orderOperation        = new OrderOperation();
     increaseTimeOperation = new IncreaseTimeOperation();
     scenarioOperation     = new ScenarioOperation();
 }
Beispiel #12
0
        /// <summary>
        /// Creates a Shopping dynamic remarketing campaign object (not including ad group level and
        /// below). This creates a Display campaign with the merchant center feed attached.
        /// Merchant Center is used for the product information in combination with a user list
        /// which contains hits with <code>ecomm_prodid</code> specified. See
        /// <a href="https://developers.google.com/adwords-remarketing-tag/parameters#retail">
        /// the guide</a> for more detail.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="merchantId">The ID of the Merchant Center account.</param>
        /// <param name="budgetId">The ID of the budget to use for the campaign.</param>
        /// <returns>The campaign that was created.</returns>
        private static Campaign CreateCampaign(AdWordsUser user, long merchantId, long budgetId)
        {
            using (CampaignService campaignService =
                       (CampaignService)user.GetService(AdWordsService.v201802.CampaignService)) {
                Campaign campaign = new Campaign {
                    name = "Shopping campaign #" + ExampleUtilities.GetRandomString(),
                    // Dynamic remarketing campaigns are only available on the Google Display Network.
                    advertisingChannelType = AdvertisingChannelType.DISPLAY,
                    status = CampaignStatus.PAUSED
                };

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

                // This example uses a Manual CPC bidding strategy, but you should select the strategy
                // that best aligns with your sales goals. More details here:
                //   https://support.google.com/adwords/answer/2472725
                BiddingStrategyConfiguration biddingStrategyConfiguration =
                    new BiddingStrategyConfiguration {
                    biddingStrategyType = BiddingStrategyType.MANUAL_CPC
                };
                campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;

                ShoppingSetting setting = new ShoppingSetting {
                    // Campaigns with numerically higher priorities take precedence over those with lower
                    // priorities.
                    campaignPriority = 0,

                    // Set the Merchant Center account ID from which to source products.
                    merchantId = merchantId,

                    // Display Network campaigns do not support partition by country. The only supported
                    // value is "ZZ". This signals that products from all countries are available in the
                    // campaign. The actual products which serve are based on the products tagged in the
                    // user list entry.
                    salesCountry = "ZZ",

                    // Optional: Enable local inventory ads (items for sale in physical stores.)
                    enableLocal = true,

                    // Optional: Declare whether purchases are only made on the merchant store, or
                    // completed on Google.
                    purchasePlatform = ShoppingPurchasePlatform.MERCHANT
                };

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

                CampaignOperation op = new CampaignOperation {
                    operand   = campaign,
                    @operator = Operator.ADD
                };

                CampaignReturnValue result = campaignService.mutate(new CampaignOperation[] { op });
                return(result.value[0]);
            }
        }
Beispiel #13
0
        public void TestGetAllCampaignsMockAndCallServer()
        {
            ServiceSignature mockSignature = MockUtilities.RegisterMockService(user,
                                                                               AdWordsService.v201605.CampaignService, typeof(MockCampaignServiceEx));

            CampaignService campaignService = (CampaignService)user.GetService(mockSignature);

            Assert.That(campaignService is MockCampaignServiceEx);

            Campaign campaign = new Campaign();

            campaign.name = "Interplanetary Cruise #" + new TestUtils().GetTimeStamp();

            // Set the test campaign to PAUSED when creating it to prevent the ads from serving.
            campaign.status = CampaignStatus.PAUSED;

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

            Budget budget = new Budget();

            budget.budgetId = budgetId;

            campaign.budget = budget;

            campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;

            // Set the campaign network options to GoogleSearch and SearchNetwork
            // only. Set ContentNetwork, PartnerSearchNetwork and ContentContextual
            // to false.
            campaign.networkSetting = new NetworkSetting()
            {
                targetGoogleSearch         = true,
                targetSearchNetwork        = true,
                targetContentNetwork       = false,
                targetPartnerSearchNetwork = false
            };

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

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

            CampaignReturnValue retVal = null;

            Assert.DoesNotThrow(delegate() {
                retVal = campaignService.mutate((new CampaignOperation[] { operation }));
            });

            Assert.NotNull(retVal);
            Assert.NotNull(retVal.value);
            Assert.AreEqual(retVal.value.Length, 1);
            Assert.AreEqual(retVal.value[0].name, campaign.name);
            Assert.AreNotEqual(retVal.value[0].id, 0);
            Assert.True((campaignService as MockCampaignServiceEx).MutateCalled);
        }
        public void TestGetAllCampaignsMockAndCallServer()
        {
            MockUtilities.RegisterMockService(user, AdWordsService.v201406.CampaignService,
                                              typeof(MockCampaignServiceEx));
            CampaignService campaignService = (CampaignService)user.GetService(
                AdWordsService.v201406.CampaignService);

            Assert.That(campaignService is MockCampaignServiceEx);

            Campaign campaign = new Campaign();

            campaign.name   = "Interplanetary Cruise #" + new TestUtils().GetTimeStamp();
            campaign.status = CampaignStatus.PAUSED;

            BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();

            biddingConfig.biddingStrategyType     = BiddingStrategyType.MANUAL_CPC;
            campaign.biddingStrategyConfiguration = biddingConfig;

            Budget budget = new Budget();

            budget.period             = BudgetBudgetPeriod.DAILY;
            budget.deliveryMethod     = BudgetBudgetDeliveryMethod.STANDARD;
            budget.amount             = new Money();
            budget.amount.microAmount = 50000000;

            campaign.budget = budget;

            // Set the campaign network options to GoogleSearch and SearchNetwork
            // only. Set ContentNetwork, PartnerSearchNetwork and ContentContextual
            // to false.
            campaign.networkSetting = new NetworkSetting();
            campaign.networkSetting.targetGoogleSearch         = true;
            campaign.networkSetting.targetSearchNetwork        = true;
            campaign.networkSetting.targetContentNetwork       = false;
            campaign.networkSetting.targetPartnerSearchNetwork = false;

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

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

            CampaignReturnValue retVal = null;

            Assert.DoesNotThrow(delegate() {
                retVal = campaignService.mutate((new CampaignOperation[] { operation }));
            });

            Assert.NotNull(retVal);
            Assert.NotNull(retVal.value);
            Assert.AreEqual(retVal.value.Length, 1);
            Assert.AreEqual(retVal.value[0].name, campaign.name);
            Assert.AreNotEqual(retVal.value[0].id, 0);
            Assert.True((campaignService as MockCampaignServiceEx).MutateCalled);
        }
Beispiel #15
0
        /// <summary>
        /// Creates a new hotel campaign in the specified client account.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="budgetResourceName">The resource name of budget for a new campaign.
        /// </param>
        /// <param name="hotelCenterAccountId">The Hotel Center account ID.</param>
        /// <param name="cpcBidCeilingMicroAmount">The CPC bid ceiling micro amount.</param>
        /// <returns>The resource name of the newly created campaign.</returns>
        private static string AddHotelCampaign(GoogleAdsClient client, long customerId,
                                               string budgetResourceName, long hotelCenterAccountId, long cpcBidCeilingMicroAmount)
        {
            // Get the CampaignService.
            CampaignServiceClient service = client.GetService(Services.V6.CampaignService);

            // [START AddHotelAd_2]
            // Create a campaign.
            Campaign campaign = new Campaign()
            {
                Name = "Interplanetary Cruise Campaign #" + ExampleUtilities.GetRandomString(),

                // Configure settings related to hotel campaigns including advertising channel type
                // and hotel setting info.
                AdvertisingChannelType = AdvertisingChannelType.Hotel,
                HotelSetting           = new HotelSettingInfo()
                {
                    HotelCenterId = hotelCenterAccountId
                },

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

                // Sets the bidding strategy to PercentCpc. Only Manual CPC and Percent CPC can
                // be used for hotel campaigns.
                PercentCpc = new PercentCpc()
                {
                    CpcBidCeilingMicros = cpcBidCeilingMicroAmount
                },

                // Set the budget.
                CampaignBudget = budgetResourceName,

                // Configure the campaign network options. Only Google Search is allowed for
                // hotel campaigns.
                NetworkSettings = new NetworkSettings()
                {
                    TargetGoogleSearch = true
                }
            };
            // [END AddHotelAd_2]

            // Create a campaign operation.
            CampaignOperation campaignOperation = new CampaignOperation()
            {
                Create = campaign
            };

            // Issue a mutate request to add campaigns.
            MutateCampaignsResponse response = service.MutateCampaigns(customerId.ToString(),
                                                                       new CampaignOperation[] { campaignOperation });

            return(response.Results[0].ResourceName);
        }
        /// <summary>
        /// Creates the Shopping campaign.
        /// </summary>
        /// <param name="user">The AdWords user for which the campaign is created.</param>
        /// <param name="budgetId">The budget ID.</param>
        /// <param name="merchantId">The Merchant Center ID.</param>
        /// <returns>The newly created Shopping campaign.</returns>
        private static Campaign CreateCampaign(AdWordsUser user, long budgetId, long merchantId)
        {
            using (CampaignService campaignService = (CampaignService)user.GetService(
                       AdWordsService.v201806.CampaignService)) {
                // Create the campaign.
                Campaign campaign = new Campaign {
                    name = "Shopping campaign #" + ExampleUtilities.GetRandomString(),

                    // The advertisingChannelType is what makes this a Shopping campaign.
                    advertisingChannelType = AdvertisingChannelType.SHOPPING,

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

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

                // Set bidding strategy (required).
                BiddingStrategyConfiguration biddingStrategyConfiguration =
                    new BiddingStrategyConfiguration {
                    // Note: Showcase ads require that the campaign has a ManualCpc
                    // BiddingStrategyConfiguration.
                    biddingStrategyType = BiddingStrategyType.MANUAL_CPC
                };

                campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;

                // All Shopping campaigns need a ShoppingSetting.
                ShoppingSetting shoppingSetting = new ShoppingSetting {
                    salesCountry     = "US",
                    campaignPriority = 0,
                    merchantId       = merchantId,

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

                // Create operation.
                CampaignOperation campaignOperation = new CampaignOperation {
                    operand   = campaign,
                    @operator = Operator.ADD
                };

                // Make the mutate request.
                CampaignReturnValue retval = campaignService.mutate(
                    new CampaignOperation[] { campaignOperation });
                return(retval.value[0]);
            }
        }
        /// <summary>
        /// Creates the campaign with a portfolio bidding strategy.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="name">The campaign name.</param>
        /// <param name="biddingStrategyId">The bidding strategy id.</param>
        /// <param name="sharedBudgetId">The shared budget id.</param>
        /// <returns>The campaign object.</returns>
        private Campaign CreateCampaignWithBiddingStrategy(AdWordsUser user, string name,
                                                           long biddingStrategyId, long sharedBudgetId)
        {
            using (CampaignService campaignService =
                       (CampaignService)user.GetService(AdWordsService.v201806.CampaignService))
            {
                // Create campaign.
                Campaign campaign = new Campaign
                {
                    name = name,
                    advertisingChannelType = AdvertisingChannelType.SEARCH,

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

                    // Set the budget.
                    budget = new Budget
                    {
                        budgetId = sharedBudgetId
                    }
                };

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

                campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;

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

                // Create operation.
                CampaignOperation operation = new CampaignOperation
                {
                    operand   = campaign,
                    @operator = Operator.ADD
                };

                return(campaignService.mutate(new CampaignOperation[]
                {
                    operation
                }).value[0]);
            }
        }
Beispiel #18
0
        /// <summary>
        /// Creates the smart display campaign.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="budgetResourceName">The campaign budget resource name.</param>
        /// <returns>Resource name of the newly created campaign.</returns>
        private string CreateSmartDisplayCampaign(GoogleAdsClient client, long customerId,
                                                  string budgetResourceName)
        {
            // Get the CampaignService.
            CampaignServiceClient campaignService = client.GetService(Services.V3.CampaignService);

            // Create the campaign.
            Campaign campaign = new Campaign()
            {
                Name = "Smart Display Campaign #" + ExampleUtilities.GetRandomString(),

                // Smart Display campaign requires the advertising_channel_type as 'DISPLAY'.
                AdvertisingChannelType = AdvertisingChannelType.Display,

                // Smart Display campaign requires the advertising_channel_sub_type as
                // 'DISPLAY_SMART_CAMPAIGN'.
                AdvertisingChannelSubType = AdvertisingChannelSubType.DisplaySmartCampaign,

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

                // Smart Display campaign requires the TargetCpa bidding strategy.
                TargetCpa = new TargetCpa()
                {
                    TargetCpaMicros = 5000000
                },

                CampaignBudget = budgetResourceName,

                // Optional: Set the start date.
                StartDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd"),

                // Optional: Set the end date.
                EndDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd"),
            };

            // Create the operation.
            CampaignOperation operation = new CampaignOperation()
            {
                Create = campaign
            };

            // Add the campaign.
            MutateCampaignsResponse response = campaignService.MutateCampaigns(
                customerId.ToString(), new[] { operation });

            string campaignResourceName = response.Results.First().ResourceName;

            // Print out some information about the added campaign.
            Console.WriteLine($"Added campaign with resource name = '{campaignResourceName}'.");

            return(campaignResourceName);
        }
        /// <summary>
        /// Creates the shopping campaign.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="budgetId">The budget id.</param>
        /// <param name="merchantId">The Merchant Center id.</param>
        /// <returns>The Shopping campaign.</returns>
        private static Campaign CreateCampaign(AdWordsUser user, long budgetId, long merchantId)
        {
            CampaignService campaignService = (CampaignService)user.GetService(
                AdWordsService.v201710.CampaignService);

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

            campaign.name = "Shopping campaign #" + ExampleUtilities.GetRandomString();

            // The advertisingChannelType is what makes this a Shopping campaign.
            campaign.advertisingChannelType = AdvertisingChannelType.SHOPPING;

            // 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 shared budget (required).
            campaign.budget          = new Budget();
            campaign.budget.budgetId = budgetId;

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

            biddingStrategyConfiguration.biddingStrategyType = BiddingStrategyType.MANUAL_CPC;

            campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;

            // All Shopping campaigns need a ShoppingSetting.
            ShoppingSetting shoppingSetting = new ShoppingSetting();

            shoppingSetting.salesCountry     = "US";
            shoppingSetting.campaignPriority = 0;
            shoppingSetting.merchantId       = merchantId;

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

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

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

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

            campaignService.Close();
            return(retval.value[0]);
        }
 /// <summary>Snippet for MutateCampaigns</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void MutateCampaigns()
 {
     // Create client
     CampaignServiceClient campaignServiceClient = CampaignServiceClient.Create();
     // Initialize request argument(s)
     string customerId = "";
     IEnumerable <CampaignOperation> operations = new CampaignOperation[]
     {
         new CampaignOperation(),
     };
     // Make the request
     MutateCampaignsResponse response = campaignServiceClient.MutateCampaigns(customerId, operations);
 }
Beispiel #21
0
        /// <summary>
        /// Creates a test campaign for running further tests.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="biddingStrategy">The bidding strategy to be used.</param>
        /// <returns>The campaign id.</returns>
        public long CreateCampaign(AdWordsUser user, AdvertisingChannelType channelType,
                                   BiddingStrategyType strategyType)
        {
            CampaignService campaignService =
                (CampaignService)user.GetService(AdWordsService.v201406.CampaignService);

            BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();

            biddingConfig.biddingStrategyType = strategyType;

            CampaignOperation campaignOperation = new CampaignOperation();

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

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

            matchSetting.optIn = true;
            settings.Add(matchSetting);

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

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

            CampaignReturnValue retVal =
                campaignService.mutate(new CampaignOperation[] { campaignOperation });

            return(retVal.value[0].id);
        }
Beispiel #22
0
        // [END use_portfolio_bidding_strategy]

        /// <summary>
        /// Creates the campaign with a portfolio bidding strategy.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="name">The campaign name.</param>
        /// <param name="biddingStrategyResourceName">The bidding strategy id.</param>
        /// <param name="campaignBudgetResourceName">The campaign budget resource name.</param>
        /// <returns>The campaign resource name.</returns>
        private string CreateCampaignWithBiddingStrategy(GoogleAdsClient client,
                                                         long customerId, string name, string biddingStrategyResourceName,
                                                         string campaignBudgetResourceName)
        {
            // Get the CampaignService.
            CampaignServiceClient campaignService = client.GetService(Services.V10.CampaignService);

            // [START use_portfolio_bidding_strategy_2]
            // Create the campaign.
            Campaign campaign = new Campaign()
            {
                Name = name,
                AdvertisingChannelType = AdvertisingChannelType.Search,

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

                // Set the campaign budget.
                CampaignBudget = campaignBudgetResourceName,

                // Set bidding strategy (required).
                BiddingStrategy = biddingStrategyResourceName,

                // Set the campaign network options.
                NetworkSettings = new NetworkSettings()
                {
                    TargetGoogleSearch         = true,
                    TargetSearchNetwork        = true,
                    TargetContentNetwork       = true,
                    TargetPartnerSearchNetwork = false
                }
            };
            // [END use_portfolio_bidding_strategy_2]

            // Create the operation.
            CampaignOperation operation = new CampaignOperation()
            {
                Create = campaign
            };

            // Create the campaign.
            MutateCampaignsResponse retVal = campaignService.MutateCampaigns(
                customerId.ToString(), new CampaignOperation[] { operation });

            return(retVal.Results[0].ResourceName);
        }
Beispiel #23
0
        /// <summary>
        /// Verifies whether UpdateCampaign example is serializing the request
        /// correctly.
        /// </summary>
        /// <param name="requestUri">The request URI.</param>
        /// <param name="headers">The headers.</param>
        /// <param name="body">The body.</param>
        private void VerifyUpdateCampaignRequest(Uri requestUri, WebHeaderCollection headers,
                                                 string body)
        {
            XmlDocument       doc  = XmlUtilities.CreateDocument(body);
            XmlElement        node = (XmlElement)doc.GetElementsByTagName("operations")[0];
            CampaignOperation campaignOperation =
                (CampaignOperation)SerializationUtilities.DeserializeFromXmlTextCustomRootNs(
                    node.OuterXml, typeof(CampaignOperation),
                    "https://adwords.google.com/api/adwords/cm/v201605", "operations");

            Assert.AreEqual(campaignOperation.@operator, Operator.SET);
            Campaign campaign = campaignOperation.operand;

            Assert.AreEqual(campaign.id, 12345);
            Assert.AreEqual(campaign.status, CampaignStatus.PAUSED);
        }
        /// <summary>
        /// Creates the shopping campaign.
        /// </summary>
        /// <param name="budgetId">The budget id.</param>
        /// <param name="merchantId">The Merchant Center id.</param>
        /// <param name="campaignService">The CampaignService instance.</param>
        /// <returns>The Shopping campaign.</returns>
        private static Campaign CreateCampaign(long budgetId, long merchantId,
                                               CampaignService campaignService)
        {
            // Create campaign.
            Campaign campaign = new Campaign();

            campaign.name = "Shopping campaign #" + ExampleUtilities.GetRandomString();
            // The advertisingChannelType is what makes this a Shopping campaign.
            campaign.advertisingChannelType = AdvertisingChannelType.SHOPPING;

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

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

            biddingStrategyConfiguration.biddingStrategyType = BiddingStrategyType.MANUAL_CPC;

            campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;

            // Set keyword matching setting (required).
            KeywordMatchSetting keywordMatchSetting = new KeywordMatchSetting();

            keywordMatchSetting.optIn = false;

            // All Shopping campaigns need a ShoppingSetting.
            ShoppingSetting shoppingSetting = new ShoppingSetting();

            shoppingSetting.salesCountry     = "US";
            shoppingSetting.campaignPriority = 0;
            shoppingSetting.merchantId       = merchantId;
            campaign.settings = new Setting[] { keywordMatchSetting, shoppingSetting };

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

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

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

            return(retval.value[0]);
        }
Beispiel #25
0
        // [END AddMerchantCenterDynamicRemarketingCampaign]

        /// <summary>
        /// Creates a campaign linked to a Merchant Center product feed.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The client customer ID.</param>
        /// <param name="merchantCenterAccountId">The Merchant Center account ID.</param>
        /// <param name="campaignBudgetId">The campaign budget ID.</param>
        /// <returns>The string resource name for the newly created campaign.</returns>
        private string CreateCampaign(GoogleAdsClient client, long customerId,
                                      long merchantCenterAccountId, long campaignBudgetId)
        {
            // Creates the Campaign Service client.
            CampaignServiceClient campaignServiceClient =
                client.GetService(Services.V6.CampaignService);

            string budgetResourceName = ResourceNames.CampaignBudget(customerId, campaignBudgetId);

            // Creates the campaign.
            Campaign campaign = new Campaign()
            {
                Name = "Shopping campaign #" + ExampleUtilities.GetRandomString(),
                // Dynamic remarketing campaigns are only available on the Google Display Network.
                AdvertisingChannelType = AdvertisingChannelType.Display,
                Status         = CampaignStatus.Paused,
                CampaignBudget = budgetResourceName,
                ManualCpc      = new ManualCpc(),
                // The settings for the shopping campaign.
                // This connects the campaign to the Merchant Center account.
                ShoppingSetting = new Campaign.Types.ShoppingSetting()
                {
                    CampaignPriority = 0,
                    MerchantId       = merchantCenterAccountId,
                    // Display Network campaigns do not support partition by country. The only
                    // supported value is "ZZ". This signals that products from all countries are
                    // available in the campaign. The actual products which serve are based on
                    // the products tagged in the user list entry.
                    SalesCountry = "ZZ",
                    EnableLocal  = true
                }
            };

            // Creates the campaign operation.
            CampaignOperation operation = new CampaignOperation()
            {
                Create = campaign
            };

            // Adds the campaign.
            MutateCampaignsResponse response = campaignServiceClient.MutateCampaigns(customerId
                                                                                     .ToString(), new[] { operation });
            string campaignResourceName = response.Results.First().ResourceName;

            Console.WriteLine($"Created campaign with resource name '{campaignResourceName}'.");
            return(campaignResourceName);
        }
Beispiel #26
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">ID of the campaign to be updated.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId)
        {
            // Get the CampaignService.
            CampaignServiceClient campaignService = client.GetService(Services.V6.CampaignService);

            // Update campaign by setting its status to paused, and "Search network" to false.
            Campaign campaignToUpdate = new Campaign()
            {
                ResourceName    = ResourceNames.Campaign(customerId, campaignId),
                Status          = CampaignStatus.Paused,
                NetworkSettings = new NetworkSettings()
                {
                    TargetSearchNetwork = false
                }
            };

            // Create the operation.
            CampaignOperation operation = new CampaignOperation()
            {
                Update     = campaignToUpdate,
                UpdateMask = FieldMasks.AllSetFieldsOf(campaignToUpdate)
            };

            try
            {
                // Update the campaign.
                MutateCampaignsResponse response = campaignService.MutateCampaigns(
                    customerId.ToString(), new [] { operation });

                // Display the results.
                foreach (MutateCampaignResult updatedCampaign in response.Results)
                {
                    Console.WriteLine($"Campaign with resource ID = " +
                                      $"'{updatedCampaign.ResourceName}' was updated.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Beispiel #27
0
        /// <summary>Snippet for MutateCampaignsAsync</summary>
        public async Task MutateCampaignsAsync()
        {
            // Snippet: MutateCampaignsAsync(string, IEnumerable<CampaignOperation>, CallSettings)
            // Additional: MutateCampaignsAsync(string, IEnumerable<CampaignOperation>, CancellationToken)
            // Create client
            CampaignServiceClient campaignServiceClient = await CampaignServiceClient.CreateAsync();

            // Initialize request argument(s)
            string customerId = "";
            IEnumerable <CampaignOperation> operations = new CampaignOperation[]
            {
                new CampaignOperation(),
            };
            // Make the request
            MutateCampaignsResponse response = await campaignServiceClient.MutateCampaignsAsync(customerId, operations);

            // End snippet
        }
Beispiel #28
0
        /// <summary>
        /// Creates the campaign with a shared bidding strategy.
        /// </summary>
        /// <param name="campaignService">The campaign service.</param>
        /// <param name="name">The campaign name.</param>
        /// <param name="biddingStrategyId">The bidding strategy id.</param>
        /// <param name="sharedBudgetId">The shared budget id.</param>
        /// <returns>The campaign object.</returns>
        private Campaign CreateCampaignWithBiddingStrategy(CampaignService campaignService, string name,
                                                           long biddingStrategyId, long sharedBudgetId)
        {
            // Create campaign.
            Campaign campaign = new Campaign();

            campaign.name = name;
            campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;

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

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

            biddingStrategyConfiguration.biddingStrategyId = biddingStrategyId;

            campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;

            // Set keyword matching setting (required).
            KeywordMatchSetting keywordMatchSetting = new KeywordMatchSetting();

            keywordMatchSetting.optIn = true;
            campaign.settings         = new Setting[] { keywordMatchSetting };

            // Set network targeting (recommended).
            NetworkSetting networkSetting = new NetworkSetting();

            networkSetting.targetGoogleSearch   = true;
            networkSetting.targetSearchNetwork  = true;
            networkSetting.targetContentNetwork = true;
            campaign.networkSetting             = networkSetting;

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

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

            return(campaignService.mutate(new CampaignOperation[] { operation }).value[0]);
        }
        /// <summary>
        /// Adds a campaign.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="budgetResourceName">The campaign budget resource name.</param>
        /// <returns>The campaign resource name.</returns>
        private static string AddCampaign(GoogleAdsClient client, long customerId,
                                          string budgetResourceName)
        {
            // Get the CampaignService.
            CampaignServiceClient campaignService = client.GetService(Services.V4.CampaignService);

            // Create the campaign.
            Campaign campaign = new Campaign()
            {
                Name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(),
                AdvertisingChannelType = AdvertisingChannelType.Search,
                Status         = CampaignStatus.Paused,
                ManualCpc      = new ManualCpc(),
                CampaignBudget = budgetResourceName,

                // Enable the campaign for DSAs.
                DynamicSearchAdsSetting = new DynamicSearchAdsSetting()
                {
                    DomainName   = "example.com",
                    LanguageCode = "en"
                },

                StartDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd"),
                EndDate   = DateTime.Now.AddDays(30).ToString("yyyyMMdd")
            };

            // Create the operation.
            CampaignOperation operation = new CampaignOperation()
            {
                Create = campaign
            };

            // Add the campaign.
            MutateCampaignsResponse response =
                campaignService.MutateCampaigns(customerId.ToString(),
                                                new CampaignOperation[] { operation });

            // Displays the result.
            string campaignResourceName = response.Results[0].ResourceName;

            Console.WriteLine($"Added campaign with resource name '{campaignResourceName}'.");
            return(campaignResourceName);
        }
        /// <summary>
        /// Builds the operations for creating new campaigns.
        /// </summary>
        /// <param name="budgetId">ID of the budget to be used for the campaign.
        /// </param>
        /// <returns>A list of operations for creating campaigns.</returns>
        private static List <CampaignOperation> BuildCampaignOperations(long budgetId)
        {
            List <CampaignOperation> operations = new List <CampaignOperation>();

            for (int i = 0; i < NUMBER_OF_CAMPAIGNS_TO_ADD; i++)
            {
                Campaign campaign = new Campaign()
                {
                    name = "Batch Campaign " + 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.
                    status = CampaignStatus.PAUSED,

                    id = NextId(),
                    advertisingChannelType = AdvertisingChannelType.SEARCH,
                    budget = new Budget()
                    {
                        budgetId = budgetId
                    },
                    biddingStrategyConfiguration = new BiddingStrategyConfiguration()
                    {
                        biddingStrategyType = BiddingStrategyType.MANUAL_CPC,

                        // You can optionally provide a bidding scheme in place of the type.
                        biddingScheme = new ManualCpcBiddingScheme()
                        {
                            enhancedCpcEnabled = false
                        }
                    }
                };

                CampaignOperation operation = new CampaignOperation()
                {
                    operand   = campaign,
                    @operator = Operator.ADD
                };
                operations.Add(operation);
            }
            return(operations);
        }
        /// <summary>
        /// Creates the campaign with a portfolio bidding strategy.
        /// </summary>
        /// <param name="campaignService">The campaign service.</param>
        /// <param name="name">The campaign name.</param>
        /// <param name="biddingStrategyId">The bidding strategy id.</param>
        /// <param name="sharedBudgetId">The shared budget id.</param>
        /// <returns>The campaign object.</returns>
        private Campaign CreateCampaignWithBiddingStrategy(CampaignService campaignService, string name,
                                                           long biddingStrategyId, long sharedBudgetId)
        {
            // Create campaign.
            Campaign campaign = new Campaign();

            campaign.name = name;
            campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;

            // 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 budget.
            campaign.budget          = new Budget();
            campaign.budget.budgetId = sharedBudgetId;

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

            biddingStrategyConfiguration.biddingStrategyId = biddingStrategyId;

            campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;

            // Set network targeting (recommended).
            NetworkSetting networkSetting = new NetworkSetting();

            networkSetting.targetGoogleSearch   = true;
            networkSetting.targetSearchNetwork  = true;
            networkSetting.targetContentNetwork = true;
            campaign.networkSetting             = networkSetting;

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

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

            return(campaignService.mutate(new CampaignOperation[] { operation }).value[0]);
        }
Beispiel #32
0
        /// <summary>
        /// Builds the operations for creating new campaigns.
        /// </summary>
        /// <param name="budgetId">ID of the budget to be used for the campaign.
        /// </param>
        /// <returns>A list of operations for creating campaigns.</returns>
        private static List <CampaignOperation> BuildCampaignOperations(long budgetId)
        {
            List <CampaignOperation> operations = new List <CampaignOperation>();

            for (int i = 0; i < NUMBER_OF_CAMPAIGNS_TO_ADD; i++)
            {
                Campaign campaign = new Campaign()
                {
                    name   = "Batch Campaign " + ExampleUtilities.GetRandomString(),
                    status = CampaignStatus.PAUSED,
                    id     = NextId(),
                    advertisingChannelType = AdvertisingChannelType.SEARCH,
                    budget = new Budget()
                    {
                        budgetId = budgetId
                    },
                    biddingStrategyConfiguration = new BiddingStrategyConfiguration()
                    {
                        biddingStrategyType = BiddingStrategyType.MANUAL_CPC,

                        // You can optionally provide a bidding scheme in place of the type.
                        biddingScheme = new ManualCpcBiddingScheme()
                        {
                            enhancedCpcEnabled = false
                        }
                    }
                };

                CampaignOperation operation = new CampaignOperation()
                {
                    operand   = campaign,
                    @operator = Operator.ADD
                };
                operations.Add(operation);
            }
            return(operations);
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the BudgetService.
              BudgetService budgetService =
              (BudgetService) user.GetService(AdWordsService.v201601.BudgetService);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            operations.Add(operation);
              }

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

            // Display the results.
            if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
              foreach (Campaign newCampaign in retVal.value) {
            Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was added.",
                newCampaign.name, newCampaign.id);
              }
            } else {
              Console.WriteLine("No campaigns were added.");
            }
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to add campaigns.", e);
              }
        }
        /// <summary>
        /// 
        /// </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;
            }
        }
    /// <summary>
    /// Creates the shopping campaign.
    /// </summary>
    /// <param name="budgetId">The budget id.</param>
    /// <param name="merchantId">The Merchant Center id.</param>
    /// <param name="campaignService">The CampaignService instance.</param>
    /// <returns>The Shopping campaign.</returns>
    private static Campaign CreateCampaign(long budgetId, long merchantId,
        CampaignService campaignService) {
      // Create campaign.
      Campaign campaign = new Campaign();
      campaign.name = "Shopping campaign #" + ExampleUtilities.GetRandomString();
      // The advertisingChannelType is what makes this a Shopping campaign.
      campaign.advertisingChannelType = AdvertisingChannelType.SHOPPING;

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

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

      campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;

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

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

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

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

      return retval.value[0];
    }
        public void TestGetAllCampaignsMockAndCallServer()
        {
            ServiceSignature mockSignature = MockUtilities.RegisterMockService(user,
              AdWordsService.v201601.CampaignService, typeof(MockCampaignServiceEx));

              CampaignService campaignService = (CampaignService) user.GetService(mockSignature);
              Assert.That(campaignService is MockCampaignServiceEx);

              Campaign campaign = new Campaign();
              campaign.name = "Interplanetary Cruise #" + new TestUtils().GetTimeStamp();
              campaign.status = CampaignStatus.PAUSED;
              campaign.biddingStrategyConfiguration = new BiddingStrategyConfiguration();
              campaign.biddingStrategyConfiguration.biddingStrategyType = BiddingStrategyType.MANUAL_CPC;

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

              campaign.budget = budget;

              campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;

              // Set the campaign network options to GoogleSearch and SearchNetwork
              // only. Set ContentNetwork, PartnerSearchNetwork and ContentContextual
              // to false.
              campaign.networkSetting = new NetworkSetting() {
            targetGoogleSearch = true,
            targetSearchNetwork = true,
            targetContentNetwork = false,
            targetPartnerSearchNetwork = false
              };

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

              CampaignReturnValue retVal = null;

              Assert.DoesNotThrow(delegate() {
            retVal = campaignService.mutate((new CampaignOperation[] { operation }));
              });

              Assert.NotNull(retVal);
              Assert.NotNull(retVal.value);
              Assert.AreEqual(retVal.value.Length, 1);
              Assert.AreEqual(retVal.value[0].name, campaign.name);
              Assert.AreNotEqual(retVal.value[0].id, 0);
              Assert.True((campaignService as MockCampaignServiceEx).MutateCalled);
        }
        /// <summary>
        /// Creates a test campaign for running further tests.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="channelType">The advertising channel type for this
        /// campaign.</param>
        /// <param param name="strategyType">The bidding strategy to be used for
        /// this campaign.</param>
        /// <param name="isMobile">True, if this campaign is mobile-only, false
        /// otherwise.</param>
        /// <returns>The campaign id.</returns>
        public long CreateCampaign(AdWordsUser user, AdvertisingChannelType channelType,
        BiddingStrategyType strategyType, bool isMobile)
        {
            CampaignService campaignService =
              (CampaignService) user.GetService(AdWordsService.v201601.CampaignService);

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

              if (isMobile) {
            switch (campaign.advertisingChannelType) {
              case AdvertisingChannelType.SEARCH:
            campaign.advertisingChannelSubType = AdvertisingChannelSubType.SEARCH_MOBILE_APP;
            break;

              case AdvertisingChannelType.DISPLAY:
            campaign.advertisingChannelSubType = AdvertisingChannelSubType.DISPLAY_MOBILE_APP;
            break;
            }
              }

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

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

              CampaignOperation campaignOperation = new CampaignOperation() {
            @operator = Operator.ADD,
            operand = campaign
              };

              CampaignReturnValue retVal =
              campaignService.mutate(new CampaignOperation[] { campaignOperation });
              return retVal.value[0].id;
        }
    /// <summary>
    /// Creates the campaign with a shared bidding strategy.
    /// </summary>
    /// <param name="campaignService">The campaign service.</param>
    /// <param name="name">The campaign name.</param>
    /// <param name="biddingStrategyId">The bidding strategy id.</param>
    /// <param name="sharedBudgetId">The shared budget id.</param>
    /// <returns>The campaign object.</returns>
    private Campaign CreateCampaignWithBiddingStrategy(CampaignService campaignService, string name,
        long biddingStrategyId, long sharedBudgetId) {
      // Create campaign.
      Campaign campaign = new Campaign();
      campaign.name = name;
      campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;

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

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

      campaign.biddingStrategyConfiguration = biddingStrategyConfiguration;

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

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

      return campaignService.mutate(new CampaignOperation[] {operation}).value[0];
    }
        /// <summary>
        /// Builds the operations for creating new campaigns.
        /// </summary>
        /// <param name="budgetId">ID of the budget to be used for the campaign.
        /// </param>
        /// <returns>A list of operations for creating campaigns.</returns>
        private static List<CampaignOperation> BuildCampaignOperations(long budgetId)
        {
            List<CampaignOperation> operations = new List<CampaignOperation>();

              for (int i = 0; i < NUMBER_OF_CAMPAIGNS_TO_ADD; i++) {
            Campaign campaign = new Campaign() {
              name = "Batch Campaign " + ExampleUtilities.GetRandomString(),
              status = CampaignStatus.PAUSED,
              id = NextId(),
              advertisingChannelType = AdvertisingChannelType.SEARCH,
              budget = new Budget() {
            budgetId = budgetId
              },
              biddingStrategyConfiguration = new BiddingStrategyConfiguration() {
            biddingStrategyType = BiddingStrategyType.MANUAL_CPC,

            // You can optionally provide a bidding scheme in place of the type.
            biddingScheme = new ManualCpcBiddingScheme() {
              enhancedCpcEnabled = false
            }
              }
            };

            CampaignOperation operation = new CampaignOperation() {
              operand = campaign,
              @operator = Operator.ADD
            };
            operations.Add(operation);
              }
              return operations;
        }