Beispiel #1
0
        /// <summary>
        /// Builds new ad group operations for the specified customer ID.
        /// </summary>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignOperations">The campaign operations to be used to create ad
        /// groups.</param>
        /// <returns>The ad group operations.</returns>
        private static List <AdGroupOperation> BuildAdGroupOperations(
            long customerId, List <CampaignOperation> campaignOperations)
        {
            List <AdGroupOperation> operations = new List <AdGroupOperation>();

            foreach (CampaignOperation campaignOperation in campaignOperations)
            {
                for (int i = 0; i < NUMBER_OF_AD_GROUPS_TO_ADD; i++)
                {
                    // Creates an ad group.
                    long    adGroupId = GetNextTemporaryId();
                    AdGroup adGroup   = new AdGroup()
                    {
                        ResourceName = ResourceNames.AdGroup(customerId, adGroupId),
                        Name         = "Mutate job ad group #" + ExampleUtilities.GetShortRandomString(),
                        Campaign     = campaignOperation.Create.ResourceName,
                        Type         = AdGroupType.SearchStandard,
                        CpcBidMicros = 10_000_000
                    };

                    // Creates an ad group operation and adds it to the operations list.
                    AdGroupOperation op = new AdGroupOperation()
                    {
                        Create = adGroup
                    };
                    operations.Add(op);
                }
            }

            return(operations);
        }
Beispiel #2
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group to be removed.</param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            using (AdGroupService adGroupService = (AdGroupService)user.GetService(
                       AdWordsService.v201802.AdGroupService)) {
                // Create ad group with REMOVED status.
                AdGroup adGroup = new AdGroup();
                adGroup.id     = adGroupId;
                adGroup.status = AdGroupStatus.REMOVED;

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

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

                    // Display the results.
                    if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                    {
                        AdGroup removedAdGroup = retVal.value[0];
                        Console.WriteLine("Ad group with id = \"{0}\" and name = \"{1}\" was removed.",
                                          removedAdGroup.id, removedAdGroup.name);
                    }
                    else
                    {
                        Console.WriteLine("No ad groups were removed.");
                    }
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to remove ad group.", e);
                }
            }
        }
        /// <summary>Adds an ad group.</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="campaignResourceName">The campaign resource name.</param>
        /// <returns>The ad group resource name.</returns>
        private static string AddAdGroup(GoogleAdsClient client, long customerId,
                                         string campaignResourceName)
        {
            // Get the AdGroupService.
            AdGroupServiceClient adGroupService = client.GetService(Services.V5.AdGroupService);

            // Create the ad group.
            AdGroup adGroup = new AdGroup()
            {
                Name                = "Earth to Mars Cruises #" + ExampleUtilities.GetRandomString(),
                Campaign            = campaignResourceName,
                Type                = AdGroupType.SearchDynamicAds,
                Status              = AdGroupStatus.Paused,
                TrackingUrlTemplate = "http://tracker.examples.com/traveltracker/{escapedlpurl}",
                CpcBidMicros        = 50_000
            };

            // Create the operation.
            AdGroupOperation operation = new AdGroupOperation()
            {
                Create = adGroup
            };

            // Add the ad group.
            MutateAdGroupsResponse response =
                adGroupService.MutateAdGroups(customerId.ToString(),
                                              new AdGroupOperation[] { operation });

            // Display the results.
            string adGroupResourceName = response.Results[0].ResourceName;

            Console.WriteLine($"Added ad group with resource name '{adGroupResourceName}'.");

            return(adGroupResourceName);
        }
        /// <summary>
        /// Creates a new product shopping ad group in the specified campaign.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The client customer ID.</param>
        /// <param name="campaignResourceName">Resource name of the shopping campaign that the
        /// new ad group will belong to.</param>
        /// <returns>Resource name of the newly created ad group.</returns>
        /// <exception cref="GoogleAdsException">Thrown if an API request failed with one or more
        /// service errors.</exception>
        private string AddProductShoppingAdGroup(GoogleAdsClient client, long customerId,
                                                 string campaignResourceName)
        {
            // Get the AdGroupService.
            AdGroupServiceClient adGroupService = client.GetService(Services.V0.AdGroupService);

            // Creates an ad group.
            AdGroup adGroup = new AdGroup()
            {
                Name     = "Earth to Mars Cruises #" + ExampleUtilities.GetRandomString(),
                Campaign = campaignResourceName,
                // Sets the ad group type to SHOPPING_PRODUCT_ADS. This is the only value possible
                // for ad groups that contain shopping product ads.
                Type         = AdGroupType.ShoppingProductAds,
                CpcBidMicros = 1_000_000L,
                Status       = AdGroupStatus.Enabled
            };

            // Creates an ad group operation.
            AdGroupOperation operation = new AdGroupOperation()
            {
                Create = adGroup
            };

            // Issues a mutate request to add an ad group.
            MutateAdGroupResult mutateAdGroupResult =
                adGroupService
                .MutateAdGroups(customerId.ToString(), new AdGroupOperation[] { operation })
                .Results[0];

            Console.WriteLine("Added a product shopping ad group with resource name: '{0}'.",
                              mutateAdGroupResult.ResourceName);
            return(mutateAdGroupResult.ResourceName);
        }
        /// <summary>
        /// Creates the ad group in a Shopping campaign.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">The campaign ID.</param>
        /// <returns>The ad group.</returns>
        private static AdGroup CreateAdGroup(AdWordsUser user, long campaignId)
        {
            using (AdGroupService adGroupService =
                       (AdGroupService)user.GetService(AdWordsService.v201806.AdGroupService))
            {
                // Create ad group.
                AdGroup adGroup = new AdGroup
                {
                    campaignId = campaignId,
                    name       = "Ad Group #" + ExampleUtilities.GetRandomString()
                };

                // Create operation.
                AdGroupOperation operation = new AdGroupOperation
                {
                    operand   = adGroup,
                    @operator = Operator.ADD
                };

                // Make the mutate request.
                AdGroupReturnValue retval = adGroupService.mutate(new AdGroupOperation[]
                {
                    operation
                });
                return(retval.value[0]);
            }
        }
        /// <summary>
        /// Adds the hotel ad group.
        /// </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="campaignResourceName">The resource name of campaign that a new ad group
        /// will belong to.</param>
        /// <returns>The resource name of the newly created ad group.</returns>
        // [START add_hotel_ad_2]
        private static string AddHotelAdGroup(GoogleAdsClient client, long customerId,
                                              string campaignResourceName)
        {
            // Get the AdGroupService.
            AdGroupServiceClient service = client.GetService(Services.V10.AdGroupService);

            // Create an ad group.
            AdGroup adGroup = new AdGroup()
            {
                Name = "Earth to Mars Cruise #" + ExampleUtilities.GetRandomString(),

                // Sets the campaign.
                Campaign = campaignResourceName,

                // Optional: Sets the ad group type to HOTEL_ADS.
                // This cannot be set to other types.
                Type = AdGroupType.HotelAds,

                CpcBidMicros = 10000000,
                Status       = AdGroupStatus.Enabled
            };

            // Create an ad group operation.
            AdGroupOperation adGroupOperation = new AdGroupOperation()
            {
                Create = adGroup
            };

            // Issue a mutate request to add an ad group.
            MutateAdGroupsResponse response = service.MutateAdGroups(customerId.ToString(),
                                                                     new AdGroupOperation[] { adGroupOperation });

            return(response.Results[0].ResourceName);
        }
Beispiel #7
0
        /// <summary>
        /// Builds the operations for creating ad groups within a campaign.
        /// </summary>
        /// <param name="campaignId">ID of the campaign for which ad groups are
        /// created.</param>
        /// <returns>A list of operations for creating ad groups.</returns>
        private static List <AdGroupOperation> BuildAdGroupOperations(long campaignId)
        {
            List <AdGroupOperation> operations = new List <AdGroupOperation>();

            for (int i = 0; i < NUMBER_OF_ADGROUPS_TO_ADD; i++)
            {
                AdGroup adGroup = new AdGroup()
                {
                    campaignId = campaignId,
                    id         = NextId(),
                    name       = "Batch Ad Group # " + ExampleUtilities.GetRandomString(),
                    biddingStrategyConfiguration = new BiddingStrategyConfiguration()
                    {
                        bids = new Bids[] {
                            new CpcBid()
                            {
                                bid = new Money()
                                {
                                    microAmount = 10000000L
                                }
                            }
                        }
                    }
                };

                AdGroupOperation operation = new AdGroupOperation()
                {
                    operand   = adGroup,
                    @operator = Operator.ADD
                };

                operations.Add(operation);
            }
            return(operations);
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group to be updated.</param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            // Get the AdGroupService.
              AdGroupService adGroupService =
              (AdGroupService) user.GetService(AdWordsService.v201601.AdGroupService);

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

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

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

            // Display the results.
            if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
              AdGroup pausedAdGroup = retVal.value[0];
              Console.WriteLine("Ad group with id = '{0}' was successfully updated.",
              pausedAdGroup.id);
            } else {
              Console.WriteLine("No ad groups were updated.");
            }
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to update ad group.", e);
              }
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group to be removed.</param>
    public void Run(AdWordsUser user, long adGroupId) {
      // Get the AdGroupService.
      AdGroupService adGroupService = (AdGroupService) user.GetService(
          AdWordsService.v201509.AdGroupService);

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

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

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

        // Display the results.
        if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
          AdGroup removedAdGroup = retVal.value[0];
          Console.WriteLine("Ad group with id = \"{0}\" and name = \"{1}\" was removed.",
              removedAdGroup.id, removedAdGroup.name);
        } else {
          Console.WriteLine("No ad groups were removed.");
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to remove ad group.", e);
      }
    }
Beispiel #10
0
        /// <summary>
        /// Updates the given TargetingSetting of an ad group.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID.</param>
        /// <param name="adGroupId">The ad group ID for which to update the audience targeting
        ///     restriction.</param>
        /// <param name="targetingSetting">The updated targeting setting.</param>
        private void UpdateTargetingSetting(GoogleAdsClient client, long customerId, long
                                            adGroupId, TargetingSetting targetingSetting)
        {
            // Get the AdGroupService client.
            AdGroupServiceClient adGroupServiceClient =
                client.GetService(Services.V6.AdGroupService);

            // Create an ad group object with the updated targeting setting.
            AdGroup adGroup = new AdGroup
            {
                ResourceName     = ResourceNames.AdGroup(customerId, adGroupId),
                TargetingSetting = targetingSetting
            };

            // Construct an operation that will update the ad group, using the FieldMasks utility
            // to derive the update mask. This mask tells the Google Ads API which attributes of the
            // ad group you want to change.
            AdGroupOperation operation = new AdGroupOperation
            {
                Update     = adGroup,
                UpdateMask = FieldMasks.AllSetFieldsOf(adGroup)
            };

            // Send the operation in a mutate request.
            MutateAdGroupsResponse response =
                adGroupServiceClient.MutateAdGroups(customerId.ToString(), new[] { operation });

            // Print the resource name of the updated object.
            Console.WriteLine("Updated targeting setting of ad group with resource name " +
                              $"'{response.Results.First().ResourceName}'; set the AUDIENCE target restriction " +
                              "to 'Observation'.");
        }
        /// <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="adGroupId">ID of the ad group to remove.</param>
        public void Run(GoogleAdsClient client, long customerId, long adGroupId)
        {
            // Get the AdGroupService.
            AdGroupServiceClient service = client.GetService(Services.V5.AdGroupService);

            // Construct an operation that will remove the ad group with the specified
            // resource name.
            AdGroupOperation operation = new AdGroupOperation
            {
                Remove = ResourceNames.AdGroup(customerId, adGroupId)
            };

            try
            {
                // Send the operation in a mutate request.
                MutateAdGroupsResponse response = service.MutateAdGroups(customerId.ToString(),
                                                                         new AdGroupOperation[] { operation });

                // Display the result.
                foreach (MutateAdGroupResult result in response.Results)
                {
                    Console.WriteLine($"Removed ad group with resourceName: " +
                                      $"{result.ResourceName}.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <summary>
        /// Attempts to create 3 ad groups with partial failure enabled. One of the ad groups
        /// will succeed, while the other will fail.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="campaignId">ID of the campaign to which ad groups are added.</param>
        /// <returns>The mutate response from the Google Ads server.</returns>
        private static MutateAdGroupsResponse CreateAdGroups(GoogleAdsClient client,
                                                             long customerId, long campaignId)
        {
            // Get the AdGroupServiceClient.
            AdGroupServiceClient adGroupService = client.GetService(Services.V5.AdGroupService);

            string validAdGroupName = "Valid AdGroup: " + ExampleUtilities.GetRandomString();

            AdGroupOperation[] operations = new AdGroupOperation[]
            {
                // This operation will be successful, assuming the campaign specified in
                // campaignId parameter is correct.
                new AdGroupOperation()
                {
                    Create = new AdGroup()
                    {
                        Campaign = ResourceNames.Campaign(customerId, campaignId),
                        Name     = validAdGroupName
                    }
                },
                // This operation will fail since we are using campaign ID = 0, which results
                // in an invalid resource name.
                new AdGroupOperation()
                {
                    Create = new AdGroup()
                    {
                        Campaign = ResourceNames.Campaign(customerId, 0),
                        Name     = "Broken AdGroup: " + ExampleUtilities.GetRandomString()
                    },
                },
                // This operation will fail since the ad group is using the same name as the ad
                // group from the first operation. Duplicate ad group names are not allowed.
                new AdGroupOperation()
                {
                    Create = new AdGroup()
                    {
                        Campaign = ResourceNames.Campaign(customerId, campaignId),
                        Name     = validAdGroupName
                    }
                }
            };

            // Add the ad groups.
            MutateAdGroupsResponse response =
                adGroupService.MutateAdGroups(new MutateAdGroupsRequest()
            {
                CustomerId     = customerId.ToString(),
                Operations     = { operations },
                PartialFailure = true,
                ValidateOnly   = false
            });

            return(response);
        }
Beispiel #13
0
        /// <summary>
        /// Creates an ad group.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">The campaign ID.</param>
        /// <returns>the newly created ad group.</returns>
        private static AdGroup CreateAdGroup(AdWordsUser user, long campaignId)
        {
            using (AdGroupService adGroupService =
                       (AdGroupService)user.GetService(AdWordsService.v201806.AdGroupService)) {
                // Create the ad group.
                AdGroup adGroup = new AdGroup {
                    // Required: Set the ad group's type to Dynamic Search Ads.
                    adGroupType = AdGroupType.SEARCH_DYNAMIC_ADS,

                    name = string.Format("Earth to Mars Cruises #{0}",
                                         ExampleUtilities.GetRandomString()),
                    campaignId = campaignId,
                    status     = AdGroupStatus.PAUSED,

                    // Recommended: Set a tracking URL template for your ad group if you want to use URL
                    // tracking software.
                    trackingUrlTemplate = "http://tracker.example.com/traveltracker/{escapedlpurl}"
                };

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

                CpcBid cpcBid = new CpcBid {
                    bid = new Money {
                        microAmount = 3000000
                    }
                };

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

                adGroup.biddingStrategyConfiguration = biddingConfig;

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

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

                    // Display the results.
                    AdGroup newAdGroup = retVal.value[0];
                    Console.WriteLine("Ad group with id = '{0}' and name = '{1}' was created.",
                                      newAdGroup.id, newAdGroup.name);
                    return(newAdGroup);
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to create ad group.", e);
                }
            }
        }
Beispiel #14
0
        /// <summary>
        /// Creates a test ad group for running further tests.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">The campaign id for which the adgroup is created.</param>
        /// <param name="adGroupType">The ad group type.</param>
        /// <param name="isCpmBid">True, if a ManualCPM bid is to be used.</param>
        /// <returns>The ad group ID.</returns>
        public long CreateAdGroup(AdWordsUser user, long campaignId, AdGroupType adGroupType,
                                  bool isCpmBid)
        {
            AdGroupService adGroupService =
                (AdGroupService)user.GetService(AdWordsService.v201806.AdGroupService);

            AdGroupOperation adGroupOperation = new AdGroupOperation();

            adGroupOperation.@operator          = Operator.ADD;
            adGroupOperation.operand            = new AdGroup();
            adGroupOperation.operand.campaignId = campaignId;
            adGroupOperation.operand.name       = string.Format("AdGroup {0}",
                                                                DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff"));
            adGroupOperation.operand.status = AdGroupStatus.ENABLED;

            if (adGroupType != AdGroupType.UNKNOWN)
            {
                adGroupOperation.operand.adGroupType = adGroupType;
            }

            if (isCpmBid)
            {
                BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
                CpmBid cpmBid = new CpmBid();
                cpmBid.bid             = new Money();
                cpmBid.bid.microAmount = 10000000;
                biddingConfig.bids     = new Bids[]
                {
                    cpmBid
                };
                adGroupOperation.operand.biddingStrategyConfiguration = biddingConfig;
            }
            else
            {
                BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
                CpcBid cpcBid = new CpcBid();
                cpcBid.bid             = new Money();
                cpcBid.bid.microAmount = 10000000;
                biddingConfig.bids     = new Bids[]
                {
                    cpcBid
                };
                adGroupOperation.operand.biddingStrategyConfiguration = biddingConfig;
            }

            AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[]
            {
                adGroupOperation
            });

            return(retVal.value[0].id);
        }
 /// <summary>Snippet for MutateAdGroups</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void MutateAdGroups()
 {
     // Create client
     AdGroupServiceClient adGroupServiceClient = AdGroupServiceClient.Create();
     // Initialize request argument(s)
     string customerId = "";
     IEnumerable <AdGroupOperation> operations = new AdGroupOperation[]
     {
         new AdGroupOperation(),
     };
     // Make the request
     MutateAdGroupsResponse response = adGroupServiceClient.MutateAdGroups(customerId, operations);
 }
Beispiel #16
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 which ad groups are added.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId)
        {
            // Get the AdGroupService.
            AdGroupServiceClient adGroupService = client.GetService(Services.V6.AdGroupService);

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

            for (int i = 0; i < NUM_ADGROUPS_TO_CREATE; i++)
            {
                // Create the ad group.
                AdGroup adGroup = new AdGroup()
                {
                    Name     = $"Earth to Mars Cruises #{ExampleUtilities.GetRandomString()}",
                    Status   = AdGroupStatusEnum.Types.AdGroupStatus.Enabled,
                    Campaign = ResourceNames.Campaign(customerId, campaignId),

                    // Set the ad group bids.
                    CpcBidMicros = 10000000
                };

                // Create the operation.
                AdGroupOperation operation = new AdGroupOperation()
                {
                    Create = adGroup
                };
                operations.Add(operation);
            }

            try
            {
                // Create the ad groups.
                MutateAdGroupsResponse response = adGroupService.MutateAdGroups(
                    customerId.ToString(), operations);

                // Display the results.
                foreach (MutateAdGroupResult newAdGroup in response.Results)
                {
                    Console.WriteLine("Ad group with resource name '{0}' was created.",
                                      newAdGroup.ResourceName);
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <summary>
        /// Creates the ad group in a Shopping campaign.
        /// </summary>
        /// <param name="user">The AdWords user for which the ad group is created.</param>
        /// <param name="campaign">The Shopping campaign.</param>
        /// <returns>The newly created ad group.</returns>
        private static AdGroup CreateAdGroup(AdWordsUser user, Campaign campaign)
        {
            using (AdGroupService adGroupService =
                       (AdGroupService)user.GetService(AdWordsService.v201809.AdGroupService))
            {
                // Create ad group.
                AdGroup adGroup = new AdGroup
                {
                    campaignId = campaign.id,
                    name       = "Ad Group #" + ExampleUtilities.GetRandomString(),

                    // Required: Set the ad group type to SHOPPING_SHOWCASE_ADS.
                    adGroupType = AdGroupType.SHOPPING_SHOWCASE_ADS
                };

                // Required: Set the ad group's bidding strategy configuration.
                BiddingStrategyConfiguration biddingConfiguration = new BiddingStrategyConfiguration
                {
                    // Optional: Set the bids.
                    bids = new Bids[]
                    {
                        new CpcBid()
                        {
                            bid = new Money()
                            {
                                microAmount = 100000
                            }
                        }
                    }
                };

                adGroup.biddingStrategyConfiguration = biddingConfiguration;

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

                // Make the mutate request.
                AdGroupReturnValue retval = adGroupService.mutate(new AdGroupOperation[]
                {
                    operation
                });
                return(retval.value[0]);
            }
        }
Beispiel #18
0
        /// <summary>
        /// Creates an ad group in the specified campaign.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaign">The campaign to which the ad group should be attached.</param>
        /// <returns>The ad group that was created.</returns>
        private static AdGroup CreateAdGroup(AdWordsUser user, Campaign campaign)
        {
            using (AdGroupService adGroupService =
                       (AdGroupService)user.GetService(AdWordsService.v201806.AdGroupService)) {
                AdGroup group = new AdGroup();
                group.name       = "Dynamic remarketing ad group";
                group.campaignId = campaign.id;
                group.status     = AdGroupStatus.ENABLED;

                AdGroupOperation op = new AdGroupOperation();
                op.operand   = group;
                op.@operator = Operator.ADD;
                AdGroupReturnValue result = adGroupService.mutate(new AdGroupOperation[] { op });
                return(result.value[0]);
            }
        }
Beispiel #19
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="adGroupId">Id of the ad group to be updated.</param>
        /// <param name="cpcBidMicroAmount">The CPC bid amount for the ad group in micros.</param>
        public void Run(GoogleAdsClient client, long customerId, long adGroupId,
                        long?cpcBidMicroAmount)
        {
            AdGroupServiceClient adGroupService = client.GetService(Services.V4.AdGroupService);

            // Create an ad group with the specified ID.
            AdGroup adGroup = new AdGroup();

            adGroup.ResourceName = ResourceNames.AdGroup(customerId, adGroupId);

            // Pause the ad group.
            adGroup.Status = AdGroupStatusEnum.Types.AdGroupStatus.Paused;

            // Update the CPC bid if specified.
            if (cpcBidMicroAmount != null)
            {
                adGroup.CpcBidMicros = cpcBidMicroAmount;
            }

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

            try
            {
                // Update the ad group.
                MutateAdGroupsResponse retVal = adGroupService.MutateAdGroups(
                    customerId.ToString(), new AdGroupOperation[] { operation });

                // Display the results.
                MutateAdGroupResult adGroupResult = retVal.Results[0];

                Console.WriteLine($"Ad group with resource name '{adGroupResult.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;
            }
        }
        /// <summary>Snippet for MutateAdGroupsAsync</summary>
        public async Task MutateAdGroupsAsync()
        {
            // Snippet: MutateAdGroupsAsync(string, IEnumerable<AdGroupOperation>, CallSettings)
            // Additional: MutateAdGroupsAsync(string, IEnumerable<AdGroupOperation>, CancellationToken)
            // Create client
            AdGroupServiceClient adGroupServiceClient = await AdGroupServiceClient.CreateAsync();

            // Initialize request argument(s)
            string customerId = "";
            IEnumerable <AdGroupOperation> operations = new AdGroupOperation[]
            {
                new AdGroupOperation(),
            };
            // Make the request
            MutateAdGroupsResponse response = await adGroupServiceClient.MutateAdGroupsAsync(customerId, operations);

            // End snippet
        }
Beispiel #21
0
        /// <summary>
        /// Creates the ad group in a Shopping campaign.
        /// </summary>
        /// <param name="adGroupService">The AdGroupService instance.</param>
        /// <param name="campaign">The Shopping campaign.</param>
        /// <returns>The ad group.</returns>
        private static AdGroup CreateAdGroup(AdGroupService adGroupService, Campaign campaign)
        {
            // Create ad group.
            AdGroup adGroup = new AdGroup();

            adGroup.campaignId = campaign.id;
            adGroup.name       = "Ad Group #" + ExampleUtilities.GetRandomString();

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

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

            // Make the mutate request.
            AdGroupReturnValue retval = adGroupService.mutate(new AdGroupOperation[] { operation });

            return(retval.value[0]);
        }
        /// <summary>
        /// Creates the ad group in a Shopping campaign.
        /// </summary>
        /// <param name="user">The AdWords user for which the ad group is created.</param>
        /// <param name="campaign">The Shopping campaign.</param>
        /// <returns>The newly created ad group.</returns>
        private static AdGroup CreateAdGroup(AdWordsUser user, Campaign campaign)
        {
            AdGroupService adGroupService = (AdGroupService)user.GetService(
                AdWordsService.v201702.AdGroupService);
            // Create ad group.
            AdGroup adGroup = new AdGroup();

            adGroup.campaignId = campaign.id;
            adGroup.name       = "Ad Group #" + ExampleUtilities.GetRandomString();

            // Required: Set the ad group type to SHOPPING_SHOWCASE_ADS.
            adGroup.adGroupType = AdGroupType.SHOPPING_SHOWCASE_ADS;

            // Required: Set the ad group's bidding strategy configuration.
            BiddingStrategyConfiguration biddingConfiguration = new BiddingStrategyConfiguration();

            // Showcase ads require either ManualCpc or EnhancedCpc.
            biddingConfiguration.biddingStrategyType = BiddingStrategyType.MANUAL_CPC;

            // Optional: Set the bids.
            biddingConfiguration.bids = new Bids[] {
                new CpcBid()
                {
                    bid = new Money()
                    {
                        microAmount = 100000
                    }
                }
            };

            adGroup.biddingStrategyConfiguration = biddingConfiguration;

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

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

            // Make the mutate request.
            AdGroupReturnValue retval = adGroupService.mutate(new AdGroupOperation[] { operation });

            return(retval.value[0]);
        }
        /// <summary>
        /// Creates the ad group in a Shopping campaign.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">The campaign ID.</param>
        /// <returns>The ad group.</returns>
        private static AdGroup CreateAdGroup(AdWordsUser user, long campaignId)
        {
            AdGroupService adGroupService = (AdGroupService)user.GetService(
                AdWordsService.v201710.AdGroupService);

            // Create ad group.
            AdGroup adGroup = new AdGroup();

            adGroup.campaignId = campaignId;
            adGroup.name       = "Ad Group #" + ExampleUtilities.GetRandomString();

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

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

            // Make the mutate request.
            AdGroupReturnValue retval = adGroupService.mutate(new AdGroupOperation[] { operation });

            adGroupService.Close();
            return(retval.value[0]);
        }
Beispiel #24
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group to be updated.</param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            // Get the AdGroupService.
            AdGroupService adGroupService =
                (AdGroupService)user.GetService(AdWordsService.v201603.AdGroupService);

            // Create the ad group.
            AdGroup adGroup = new AdGroup();

            adGroup.status = AdGroupStatus.PAUSED;
            adGroup.id     = adGroupId;

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

            operation.@operator = Operator.SET;
            operation.operand   = adGroup;

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

                // Display the results.
                if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                {
                    AdGroup pausedAdGroup = retVal.value[0];
                    Console.WriteLine("Ad group with id = '{0}' was successfully updated.",
                                      pausedAdGroup.id);
                }
                else
                {
                    Console.WriteLine("No ad groups were updated.");
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to update ad group.", e);
            }
        }
        /// <summary>
        /// Creates a test adgroup for running further tests.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">The campaign id for which the adgroup is created.</param>
        /// <param name="isCpmBid">True, if a ManualCPM bid is to be used.</param>
        /// <returns>The adgroup id.</returns>
        public long CreateAdGroup(AdWordsUser user, long campaignId, bool isCpmBid)
        {
            AdGroupService adGroupService =
              (AdGroupService) user.GetService(AdWordsService.v201601.AdGroupService);

              AdGroupOperation adGroupOperation = new AdGroupOperation();
              adGroupOperation.@operator = Operator.ADD;
              adGroupOperation.operand = new AdGroup();
              adGroupOperation.operand.campaignId = campaignId;
              adGroupOperation.operand.name =
              string.Format("AdGroup {0}", DateTime.Now.ToString("yyyy-M-d H:m:s.ffffff"));
              adGroupOperation.operand.status = AdGroupStatus.ENABLED;

              if (isCpmBid) {
            BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
            CpmBid cpmBid = new CpmBid();
            cpmBid.bid = new Money();
            cpmBid.bid.microAmount = 10000000;
            biddingConfig.bids = new Bids[] { cpmBid };
            adGroupOperation.operand.biddingStrategyConfiguration = biddingConfig;
              } else {
            BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
            CpcBid cpcBid = new CpcBid();
            cpcBid.bid = new Money();
            cpcBid.bid.microAmount = 10000000;
            biddingConfig.bids = new Bids[] { cpcBid };
            adGroupOperation.operand.biddingStrategyConfiguration = biddingConfig;
              }
              AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[] { adGroupOperation });
              return retVal.value[0].id;
        }
        /// <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;
            }
        }
Beispiel #27
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group to be updated.</param>
        /// <param name="bidMicroAmount">The CPC bid amount in micros.</param>
        public void Run(AdWordsUser user, long adGroupId, long?bidMicroAmount)
        {
            using (AdGroupService adGroupService =
                       (AdGroupService)user.GetService(AdWordsService.v201710.AdGroupService)) {
                // Create an ad group with the specified ID.
                AdGroup adGroup = new AdGroup();
                adGroup.id = adGroupId;

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

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

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

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

                    // Display the results.
                    if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                    {
                        AdGroup adGroupResult = retVal.value[0];
                        BiddingStrategyConfiguration bsConfig = adGroupResult.biddingStrategyConfiguration;

                        // Find the CpcBid in the bidding strategy configuration's bids collection.
                        long cpcBidMicros = 0L;
                        if (bsConfig != null && bsConfig.bids != null)
                        {
                            foreach (Bids bid in bsConfig.bids)
                            {
                                if (bid is CpcBid)
                                {
                                    cpcBidMicros = ((CpcBid)bid).bid.microAmount;
                                    break;
                                }
                            }
                        }
                        Console.WriteLine("Ad group with ID {0} and name '{1}' updated to have status '{2}'" +
                                          " and CPC bid {3}", adGroupResult.id, adGroupResult.name,
                                          adGroupResult.status, cpcBidMicros);
                    }
                    else
                    {
                        Console.WriteLine("No ad groups were updated.");
                    }
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to update ad group.", e);
                }
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which ad groups are
        /// added.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            // Get the AdGroupService.
              AdGroupService adGroupService =
              (AdGroupService) user.GetService(AdWordsService.v201509.AdGroupService);

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

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

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

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

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

            adGroup.biddingStrategyConfiguration = biddingConfig;

            // Optional: Set targeting restrictions.
            // Depending on the criterionTypeGroup value, most TargetingSettingDetail
            // only affect Display campaigns. However, the USER_INTEREST_AND_LIST value
            // works for RLSA campaigns - Search campaigns targeting using a
            // remarketing list.
            TargetingSetting targetingSetting = new TargetingSetting();

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

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

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

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

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

            operations.Add(operation);
              }

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

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

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

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

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

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

                    adGroup.biddingStrategyConfiguration = biddingConfig;

                    // Optional: Set targeting restrictions.
                    // Depending on the criterionTypeGroup value, most TargetingSettingDetail
                    // only affect Display campaigns. However, the USER_INTEREST_AND_LIST value
                    // works for RLSA campaigns - Search campaigns targeting using a
                    // remarketing list.
                    TargetingSetting targetingSetting = new TargetingSetting();

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

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

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

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

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

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

                    operations.Add(operation);
                }

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

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

            // Get the AdGroupService.
            AdGroupService adGroupService =
                (AdGroupService)user.GetService(AdWordsService.v201607.AdGroupService);

            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(AdWordsService.v201607.AdGroupCriterionService);

            // Create the experiment.
            Experiment experiment = new Experiment();

            experiment.campaignId      = campaignId;
            experiment.name            = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString();
            experiment.queryPercentage = 10;
            experiment.startDateTime   = DateTime.Now.AddDays(1).ToString("yyyyMMdd HHmmss");

            // Optional: Set the end date.
            experiment.endDateTime = DateTime.Now.AddDays(30).ToString("yyyyMMdd HHmmss");

            // Optional: Set the status.
            experiment.status = ExperimentStatus.ENABLED;

            // Create the operation.
            ExperimentOperation experimentOperation = new ExperimentOperation();

            experimentOperation.@operator = Operator.ADD;
            experimentOperation.operand   = experiment;

            try {
                // Add the experiment.
                ExperimentReturnValue experimentRetVal = experimentService.mutate(
                    new ExperimentOperation[] { experimentOperation });

                // Display the results.
                if (experimentRetVal != null && experimentRetVal.value != null && experimentRetVal.value.
                    Length > 0)
                {
                    long experimentId = 0;

                    Experiment newExperiment = experimentRetVal.value[0];

                    Console.WriteLine("Experiment with name = \"{0}\" and id = \"{1}\" was added.\n",
                                      newExperiment.name, newExperiment.id);
                    experimentId = newExperiment.id;

                    // Set ad group for the experiment.
                    AdGroup adGroup = new AdGroup();
                    adGroup.id = adGroupId;

                    // Create experiment bid multiplier rule that will modify ad group bid
                    // for the experiment.
                    ManualCPCAdGroupExperimentBidMultipliers adGroupBidMultiplier =
                        new ManualCPCAdGroupExperimentBidMultipliers();
                    adGroupBidMultiplier.maxCpcMultiplier            = new BidMultiplier();
                    adGroupBidMultiplier.maxCpcMultiplier.multiplier = 1.5;

                    // Set experiment data to the ad group.
                    AdGroupExperimentData adGroupExperimentData = new AdGroupExperimentData();
                    adGroupExperimentData.experimentId             = experimentId;
                    adGroupExperimentData.experimentDeltaStatus    = ExperimentDeltaStatus.MODIFIED;
                    adGroupExperimentData.experimentBidMultipliers = adGroupBidMultiplier;

                    adGroup.experimentData = adGroupExperimentData;

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

                    // Update the ad group.
                    AdGroupReturnValue adGroupRetVal = adGroupService.mutate(new AdGroupOperation[] {
                        adGroupOperation
                    });

                    // Display the results.
                    if (adGroupRetVal != null && adGroupRetVal.value != null &&
                        adGroupRetVal.value.Length > 0)
                    {
                        AdGroup updatedAdGroup = adGroupRetVal.value[0];
                        Console.WriteLine("Ad group with name = \"{0}\", id = \"{1}\" and status = \"{2}\" " +
                                          "was updated for the experiment.\n", updatedAdGroup.name, updatedAdGroup.id,
                                          updatedAdGroup.status);
                    }
                    else
                    {
                        Console.WriteLine("No ad groups were updated.");
                    }

                    // Set ad group criteria for the experiment.
                    Criterion criterion = new Criterion();
                    criterion.id = criterionId;

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

                    // Create experiment bid multiplier rule that will modify criterion bid
                    // for the experiment.
                    ManualCPCAdGroupCriterionExperimentBidMultiplier bidMultiplier =
                        new ManualCPCAdGroupCriterionExperimentBidMultiplier();
                    bidMultiplier.maxCpcMultiplier            = new BidMultiplier();
                    bidMultiplier.maxCpcMultiplier.multiplier = 1.5;

                    // Set experiment data to the criterion.
                    BiddableAdGroupCriterionExperimentData adGroupCriterionExperimentData =
                        new BiddableAdGroupCriterionExperimentData();
                    adGroupCriterionExperimentData.experimentId            = experimentId;
                    adGroupCriterionExperimentData.experimentDeltaStatus   = ExperimentDeltaStatus.MODIFIED;
                    adGroupCriterionExperimentData.experimentBidMultiplier = bidMultiplier;

                    adGroupCriterion.experimentData = adGroupCriterionExperimentData;

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

                    // Update the ad group criteria.
                    AdGroupCriterionReturnValue adGroupCriterionRetVal = adGroupCriterionService.mutate(
                        new AdGroupCriterionOperation[] { adGroupCriterionOperation });

                    // Display the results.
                    if (adGroupCriterionRetVal != null && adGroupCriterionRetVal.value != null &&
                        adGroupCriterionRetVal.value.Length > 0)
                    {
                        AdGroupCriterion updatedAdGroupCriterion = adGroupCriterionRetVal.value[0];
                        Console.WriteLine("Ad group criterion with ad group id = \"{0}\", criterion id = "
                                          + "\"{1}\" and type = \"{2}\" was updated for the experiment.\n",
                                          updatedAdGroupCriterion.adGroupId, updatedAdGroupCriterion.criterion.id,
                                          updatedAdGroupCriterion.criterion.CriterionType);
                    }
                    else
                    {
                        Console.WriteLine("No ad group criteria were updated.");
                    }
                }
                else
                {
                    Console.WriteLine("No experiments were added.");
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to add experiment.", e);
            }
        }
Beispiel #31
0
        public static AdGroupReturnValue CreateAdGroup(AdWordsUser user, AdGroupLo adGroupLo)
        {
            using (AdGroupService adGroupService =
                       (AdGroupService)user.GetService(AdWordsService.v201710.AdGroupService))
            {
                List <AdGroupOperation> operations = new List <AdGroupOperation>();

                // Create the ad group.
                AdGroup adGroup = new AdGroup();
                adGroup.name       = adGroupLo.Name;
                adGroup.status     = AdGroupStatus.PAUSED;
                adGroup.campaignId = adGroupLo.CampaignId;

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

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

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

                adGroup.biddingStrategyConfiguration = biddingConfig;

                // Optional: Set targeting restrictions.
                // Depending on the criterionTypeGroup value, most TargetingSettingDetail
                // only affect Display campaigns. However, the USER_INTEREST_AND_LIST value
                // works for RLSA campaigns - Search campaigns targeting using a
                // remarketing list.
                TargetingSetting targetingSetting = new TargetingSetting();

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

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

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

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

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

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

                operations.Add(operation);


                AdGroupReturnValue returnDGroup;
                try
                {
                    // Create the ad group.
                    returnDGroup = adGroupService.mutate(operations.ToArray());
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to create ad group.", e);
                }
                return(returnDGroup);
            }
        }
        /// <summary>
        /// Builds the operations for creating ad groups within a campaign.
        /// </summary>
        /// <param name="campaignId">ID of the campaign for which ad groups are
        /// created.</param>
        /// <returns>A list of operations for creating ad groups.</returns>
        private static List<AdGroupOperation> BuildAdGroupOperations(long campaignId)
        {
            List<AdGroupOperation> operations = new List<AdGroupOperation>();
              for (int i = 0; i < NUMBER_OF_ADGROUPS_TO_ADD; i++) {
            AdGroup adGroup = new AdGroup() {
              campaignId = campaignId,
              id = NextId(),
              name = "Batch Ad Group # " + ExampleUtilities.GetRandomString(),
              biddingStrategyConfiguration = new BiddingStrategyConfiguration() {
            bids = new Bids[] {
                new CpcBid() {
                  bid = new Money() {
                    microAmount = 10000000L
                  }
                }
              }
              }
            };

            AdGroupOperation operation = new AdGroupOperation() {
              operand = adGroup,
              @operator = Operator.ADD
            };

            operations.Add(operation);
              }
              return operations;
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which experiments are
        /// added.</param>
        /// <param name="adGroupId">Id of the ad group to which experiments are
        /// added.</param>
        /// <param name="criterionId">Id of the criterion for which experiments
        /// are added.</param>
        public void Run(AdWordsUser user, long campaignId, long adGroupId, long criterionId)
        {
            // Get the ExperimentService.
              ExperimentService experimentService =
              (ExperimentService) user.GetService(AdWordsService.v201601.ExperimentService);

              // Get the AdGroupService.
              AdGroupService adGroupService =
              (AdGroupService) user.GetService(AdWordsService.v201601.AdGroupService);

              // Get the AdGroupCriterionService.
              AdGroupCriterionService adGroupCriterionService =
              (AdGroupCriterionService) user.GetService(AdWordsService.v201601.AdGroupCriterionService);

              // Create the experiment.
              Experiment experiment = new Experiment();
              experiment.campaignId = campaignId;
              experiment.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString();
              experiment.queryPercentage = 10;
              experiment.startDateTime = DateTime.Now.AddDays(1).ToString("yyyyMMdd HHmmss");

              // Optional: Set the end date.
              experiment.endDateTime = DateTime.Now.AddDays(30).ToString("yyyyMMdd HHmmss");

              // Optional: Set the status.
              experiment.status = ExperimentStatus.ENABLED;

              // Create the operation.
              ExperimentOperation experimentOperation = new ExperimentOperation();
              experimentOperation.@operator = Operator.ADD;
              experimentOperation.operand = experiment;

              try {
            // Add the experiment.
            ExperimentReturnValue experimentRetVal = experimentService.mutate(
            new ExperimentOperation[] {experimentOperation});

            // Display the results.
            if (experimentRetVal != null && experimentRetVal.value != null && experimentRetVal.value.
            Length > 0) {
              long experimentId = 0;

              Experiment newExperiment = experimentRetVal.value[0];

              Console.WriteLine("Experiment with name = \"{0}\" and id = \"{1}\" was added.\n",
              newExperiment.name, newExperiment.id);
              experimentId = newExperiment.id;

              // Set ad group for the experiment.
              AdGroup adGroup = new AdGroup();
              adGroup.id = adGroupId;

              // Create experiment bid multiplier rule that will modify ad group bid
              // for the experiment.
              ManualCPCAdGroupExperimentBidMultipliers adGroupBidMultiplier =
              new ManualCPCAdGroupExperimentBidMultipliers();
              adGroupBidMultiplier.maxCpcMultiplier = new BidMultiplier();
              adGroupBidMultiplier.maxCpcMultiplier.multiplier = 1.5;

              // Set experiment data to the ad group.
              AdGroupExperimentData adGroupExperimentData = new AdGroupExperimentData();
              adGroupExperimentData.experimentId = experimentId;
              adGroupExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED;
              adGroupExperimentData.experimentBidMultipliers = adGroupBidMultiplier;

              adGroup.experimentData = adGroupExperimentData;

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

              // Update the ad group.
              AdGroupReturnValue adGroupRetVal = adGroupService.mutate(new AdGroupOperation[] {
              adGroupOperation});

              // Display the results.
              if (adGroupRetVal != null && adGroupRetVal.value != null &&
              adGroupRetVal.value.Length > 0) {
            AdGroup updatedAdGroup = adGroupRetVal.value[0];
            Console.WriteLine("Ad group with name = \"{0}\", id = \"{1}\" and status = \"{2}\" " +
                "was updated for the experiment.\n", updatedAdGroup.name, updatedAdGroup.id,
                updatedAdGroup.status);
              } else {
            Console.WriteLine("No ad groups were updated.");
              }

              // Set ad group criteria for the experiment.
              Criterion criterion = new Criterion();
              criterion.id = criterionId;

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

              // Create experiment bid multiplier rule that will modify criterion bid
              // for the experiment.
              ManualCPCAdGroupCriterionExperimentBidMultiplier bidMultiplier =
              new ManualCPCAdGroupCriterionExperimentBidMultiplier();
              bidMultiplier.maxCpcMultiplier = new BidMultiplier();
              bidMultiplier.maxCpcMultiplier.multiplier = 1.5;

              // Set experiment data to the criterion.
              BiddableAdGroupCriterionExperimentData adGroupCriterionExperimentData =
              new BiddableAdGroupCriterionExperimentData();
              adGroupCriterionExperimentData.experimentId = experimentId;
              adGroupCriterionExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED;
              adGroupCriterionExperimentData.experimentBidMultiplier = bidMultiplier;

              adGroupCriterion.experimentData = adGroupCriterionExperimentData;

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

              // Update the ad group criteria.
              AdGroupCriterionReturnValue adGroupCriterionRetVal = adGroupCriterionService.mutate(
              new AdGroupCriterionOperation[] {adGroupCriterionOperation});

              // Display the results.
              if (adGroupCriterionRetVal != null && adGroupCriterionRetVal.value != null &&
              adGroupCriterionRetVal.value.Length > 0) {
            AdGroupCriterion updatedAdGroupCriterion = adGroupCriterionRetVal.value[0];
            Console.WriteLine("Ad group criterion with ad group id = \"{0}\", criterion id = "
                + "\"{1}\" and type = \"{2}\" was updated for the experiment.\n",
                updatedAdGroupCriterion.adGroupId, updatedAdGroupCriterion.criterion.id,
                updatedAdGroupCriterion.criterion.CriterionType);
              } else {
            Console.WriteLine("No ad group criteria were updated.");
              }
            } else {
              Console.WriteLine("No experiments were added.");
            }
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to add experiment.", e);
              }
        }
    /// <summary>
    /// Creates the ad group in a Shopping campaign.
    /// </summary>
    /// <param name="adGroupService">The AdGroupService instance.</param>
    /// <param name="campaign">The Shopping campaign.</param>
    /// <returns>The ad group.</returns>
    private static AdGroup CreateAdGroup(AdGroupService adGroupService, Campaign campaign) {
      // Create ad group.
      AdGroup adGroup = new AdGroup();
      adGroup.campaignId = campaign.id;
      adGroup.name = "Ad Group #" + ExampleUtilities.GetRandomString();

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

      // Make the mutate request.
      AdGroupReturnValue retval = adGroupService.mutate(new AdGroupOperation[] { operation });
      return retval.value[0];
    }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which ad groups are
        /// added.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            // Get the AdGroupService.
            AdGroupService adGroupService =
                (AdGroupService)user.GetService(AdWordsService.v201402.AdGroupService);

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

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

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

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

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

                adGroup.biddingStrategyConfiguration = biddingConfig;

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

                TargetingSettingDetail placementDetail = new TargetingSettingDetail();
                placementDetail.criterionTypeGroup = CriterionTypeGroup.PLACEMENT;
                placementDetail.targetAll          = true;

                TargetingSettingDetail verticalDetail = new TargetingSettingDetail();
                verticalDetail.criterionTypeGroup = CriterionTypeGroup.VERTICAL;
                verticalDetail.targetAll          = false;

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

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

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

                operations.Add(operation);
            }

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

                // Display the results.
                if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                {
                    foreach (AdGroup newAdGroup in retVal.value)
                    {
                        Console.WriteLine("Ad group with id = '{0}' and name = '{1}' was created.",
                                          newAdGroup.id, newAdGroup.name);
                    }
                }
                else
                {
                    Console.WriteLine("No ad groups were created.");
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to create ad groups.", ex);
            }
        }