Example #1
0
        /// <summary>
        /// Creates the campaign draft.
        /// </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="baseCampaignId">The base campaign ID.</param>
        /// <returns>The resource name of the newly created campaign draft.</returns>
        internal static string CreateCampaignDraft(GoogleAdsClient client, long customerId,
                                                   long baseCampaignId)
        {
            // Get the CampaignDraftService.
            CampaignDraftServiceClient campaignDraftService =
                client.GetService(Services.V6.CampaignDraftService);

            CampaignDraft campaignDraft = new CampaignDraft()
            {
                BaseCampaign = ResourceNames.Campaign(customerId, baseCampaignId),
                Name         = "Campaign Draft #" + ExampleUtilities.GetRandomString(),
            };

            CampaignDraftOperation operation = new CampaignDraftOperation()
            {
                Create = campaignDraft
            };

            MutateCampaignDraftsResponse response = campaignDraftService.MutateCampaignDrafts(
                customerId.ToString(), new CampaignDraftOperation[] { operation });

            return(response.Results[0].ResourceName);
        }
Example #2
0
        /// <summary>
        /// Creates a new CampaignGroup in the specified client account.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <returns>resource name of the newly created campaign group.</returns>
        private static String CreateCampaignGroup(GoogleAdsClient client, long customerId)
        {
            CampaignGroupServiceClient campaignGroupService = client.GetService(
                Services.V0.CampaignGroupService);

            CampaignGroup campaignGroup = new CampaignGroup()
            {
                Name = "Mars campaign group #" + ExampleUtilities.GetRandomString()
            };

            CampaignGroupOperation op = new CampaignGroupOperation()
            {
                Create = campaignGroup
            };

            MutateCampaignGroupsResponse response =
                campaignGroupService.MutateCampaignGroups(
                    customerId.ToString(), new CampaignGroupOperation[] { op });
            String groupResourceName = response.Results[0].ResourceName;

            Console.WriteLine($"Added campaign group with resource name: {groupResourceName}");
            return(groupResourceName);
        }
        /// <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="baseCampaignId">ID of the base campaign.</param>
        /// <param name="draftId">ID of the draft campaign.</param>
        public void Run(GoogleAdsClient client, long customerId, long baseCampaignId, long draftId)
        {
            try
            {
                string campaignDraftResourceName = ResourceNames.CampaignDraft(
                    customerId, baseCampaignId, draftId);
                Operation <Empty, CreateCampaignExperimentMetadata> operation =
                    CreateExperiment(client, customerId, campaignDraftResourceName);

                Console.WriteLine("Waiting until operation completes...");
                operation.PollUntilCompleted();

                DisplayExperimentDetails(client, customerId, operation.Metadata.CampaignExperiment);
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Example #4
0
        /// <summary>
        /// Creates a keyword.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="adGroupResourceName">The resource name of the ad group to which keyword
        /// is added.</param>
        /// <returns>The resource name of the newly created keyword.</returns>
        internal static string CreateKeyword(GoogleAdsClient client, string adGroupResourceName)
        {
            AdGroupCriterion criterion = new AdGroupCriterion()
            {
                AdGroup = adGroupResourceName,
                Status  = AdGroupCriterionStatus.Enabled,
                Keyword = new KeywordInfo()
                {
                    Text      = $"mars cruise #{DateTime.Now.Ticks}",
                    MatchType = KeywordMatchType.Exact
                }
            };
            MutateOperation mutateOperation = new MutateOperation()
            {
                AdGroupCriterionOperation = new AdGroupCriterionOperation()
                {
                    Create = criterion
                }
            };

            return(ExecuteOperations(client, new[] { mutateOperation }).First()
                   .AdGroupCriterionResult.ResourceName);
        }
        /// <summary>
        /// Gets the Affiliate Location Extension feed mapping.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="feedResourceName">The feed resource name.</param>
        /// <returns>The newly created feed mapping.</returns>
        private static FeedMapping GetAffiliateLocationExtensionFeedMapping(GoogleAdsClient client,
                                                                            long customerId, string feedResourceName)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V4.GoogleAdsService);

            // Create the query.
            string query = $"SELECT feed_mapping.resource_name, " +
                           $"feed_mapping.attribute_field_mappings, feed_mapping.status FROM " +
                           $"feed_mapping WHERE feed_mapping.feed = '{feedResourceName}' and " +
                           $"feed_mapping.status = ENABLED and feed_mapping.placeholder_type = " +
                           "AFFILIATE_LOCATION LIMIT 1";

            // Issue a search request.
            PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> result =
                googleAdsService.Search(customerId.ToString(), query);

            // Display the results.
            GoogleAdsRow googleAdsRow = result.FirstOrDefault();

            return((googleAdsRow == null) ? null : googleAdsRow.FeedMapping);
        }
        /// <summary>
        /// Retrieves a feed item and its attribute values given a resource name.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The client customer ID.</param>
        /// <param name="feedId">The feed ID that contains the target feed item.</param>
        /// <param name="feedItemId">The feed item ID that will be updated.</param>
        /// <returns>FeedItem with the given resource name.</returns>
        private FeedItem GetFeedItem(GoogleAdsClient client, long customerId,
                                     long feedId, long feedItemId)
        {
            // Gets the Google Ads service.
            GoogleAdsServiceClient googleAdsServiceClient = client.GetService(
                Services.V5.GoogleAdsService);

            // Constructs the resource name for the feed item.
            string feedItemResourceName = ResourceNames.FeedItem(customerId, feedId, feedItemId);

            // Constructs the query.
            string query = $@"
                SELECT feed_item.attribute_values
                FROM feed_item
                WHERE feed_item.resource_name = '{feedItemResourceName}'";

            // Issues the search request.
            PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchResponse =
                googleAdsServiceClient.Search(customerId.ToString(), query);

            // Returns the feed item attribute values.
            return(searchResponse.First().FeedItem);
        }
Example #7
0
        /// <summary>
        /// Creates feed items, which fill out the feed table with data.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="feed">The feed for which the operation will be created.</param>
        /// <returns>A list of string Feed Item Resource Names.</returns>
        private List <string> CreateFeedItems(GoogleAdsClient client, long customerId, Feed feed)
        {
            FeedItemServiceClient feedItemService = client.GetService(Services.V4.FeedItemService);

            List <FeedItemOperation> operations = new List <FeedItemOperation>
            {
                NewFeedItemOperation(feed, "Home", "http://www.example.com",
                                     "Home line 1", "Home line 2"),
                NewFeedItemOperation(feed, "Stores",
                                     "http://www.example.com/stores", "Stores line 1", "Stores line 2"),
                NewFeedItemOperation(feed, "On Sale",
                                     "http://www.example.com/sale", "On Sale line 1", "On Sale line 2"),
                NewFeedItemOperation(feed, "Support",
                                     "http://www.example.com/support", "Support line 1", "Support line 2"),
                NewFeedItemOperation(feed, "Products",
                                     "http://www.example.com/catalogue",
                                     "Products line 1", "Products line 2"),
                NewFeedItemOperation(feed, "About Us", "http://www.example.com/about",
                                     "About Us line 1", "About Us line 2")
            };

            MutateFeedItemsResponse response =
                feedItemService.MutateFeedItems(customerId.ToString(), operations);

            // We will need the resource name of each feed item to use in targeting.
            List <string> feedItemResourceNames = new List <string>();

            Console.WriteLine("Created the following feed items:");
            foreach (MutateFeedItemResult feedItemResult in response.Results)
            {
                Console.WriteLine($"\t{feedItemResult.ResourceName}");

                feedItemResourceNames.Add(feedItemResult.ResourceName);
            }

            return(feedItemResourceNames);
        }
        /// <summary>Adds an expanded dynamic search ad.</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="adGroupResourceName">The ad group resource name.</param>
        private static void AddExpandedDSA(GoogleAdsClient client, long customerId,
                                           string adGroupResourceName)
        {
            // Get the AdGroupAdService.
            AdGroupAdServiceClient adGroupAdService =
                client.GetService(Services.V4.AdGroupAdService);

            // Create an ad group ad.
            AdGroupAd adGroupAd = new AdGroupAd()
            {
                AdGroup = adGroupResourceName,
                Status  = AdGroupAdStatus.Paused,

                // Set the ad as an expanded dynamic search ad.
                Ad = new Ad()
                {
                    ExpandedDynamicSearchAd = new ExpandedDynamicSearchAdInfo()
                    {
                        Description = "Buy tickets now!"
                    }
                }
            };

            // Create the operation.
            AdGroupAdOperation operation = new AdGroupAdOperation()
            {
                Create = adGroupAd
            };

            // Add the dynamic search ad.
            MutateAdGroupAdsResponse response = adGroupAdService.MutateAdGroupAds(
                customerId.ToString(), new AdGroupAdOperation[] { operation });

            // Display the response.
            Console.WriteLine($"Added ad group ad with resource name " +
                              $"'{response.Results[0].ResourceName}'.");
        }
        // [END add_shopping_product_ad]

        /// <summary>
        /// Creates a new default shopping listing group for the specified ad group. A listing
        /// group is the Google Ads API representation of a "product group" described in the
        /// Google Ads user interface. The listing group will be added to the ad group using an
        /// "ad group criterion".
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The client customer ID.</param>
        /// <param name="adGroupResourceName">The resource name of the ad group that the new
        /// listing group will belong to.</param>
        /// <returns>Resource name of the newly created ad group criterion containing the
        /// listing group.</returns>
        /// <exception cref="GoogleAdsException">Thrown if an API request failed with one or more
        /// service errors.</exception>
        private string AddDefaultShoppingListingGroup(GoogleAdsClient client, long customerId,
                                                      string adGroupResourceName)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionServiceClient adGroupCriterionService = client.GetService(
                Services.V10.AdGroupCriterionService);

            // Creates a new ad group criterion. This will contain the "default" listing group (All
            // products).
            AdGroupCriterion adGroupCriterion = new AdGroupCriterion()
            {
                AdGroup = adGroupResourceName,
                Status  = AdGroupCriterionStatus.Enabled,

                // Creates a new listing group. This will be the top-level "root" node.
                // Set the type of the listing group to be a biddable unit.
                ListingGroup = new ListingGroupInfo()
                {
                    Type = ListingGroupType.Unit
                },
                // Set the bid for products in this listing group unit.
                CpcBidMicros = 500_000L
            };

            AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
            {
                Create = adGroupCriterion
            };

            MutateAdGroupCriterionResult mutateAdGroupCriteriaResult =
                adGroupCriterionService.MutateAdGroupCriteria(customerId.ToString(),
                                                              new AdGroupCriterionOperation[] { operation }).Results[0];

            Console.WriteLine("Added an ad group criterion containing a listing group with " +
                              "resource name: '{0}'.", mutateAdGroupCriteriaResult.ResourceName);
            return(mutateAdGroupCriteriaResult.ResourceName);
        }
Example #10
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V4.GoogleAdsService);

            // Create a query that will retrieve all campaigns.
            string query = @"SELECT
                            campaign.id,
                            campaign.name,
                            campaign.network_settings.target_content_network
                        FROM campaign
                        ORDER BY campaign.id";

            try
            {
                // Issue a search request.
                googleAdsService.SearchStream(customerId.ToString(), query,
                                              delegate(SearchGoogleAdsStreamResponse resp)
                {
                    foreach (GoogleAdsRow googleAdsRow in resp.Results)
                    {
                        Console.WriteLine("Campaign with ID {0} and name '{1}' was found.",
                                          googleAdsRow.Campaign.Id, googleAdsRow.Campaign.Name);
                    }
                }
                                              );
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Example #11
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="merchantCenterAccountId">The Merchant Center account ID.</param>
        /// <param name="createDefaultListingGroup">The boolean to indicate if a default listing
        /// group should be created for the ad group. Set to false if the listing group will be
        /// constructed elsewhere.
        ///
        /// See AddShoppingListingGroupTree for a more comprehensive example.</param>
        public void Run(GoogleAdsClient client, long customerId, long merchantCenterAccountId,
                        bool createDefaultListingGroup)
        {
            try
            {
                // Creates a budget to be used by the campaign that will be created below.
                string budgetResourceName = AddCampaignBudget(client, customerId);

                // Creates a Smart Shopping campaign.
                string campaignResourceName = AddSmartShoppingCampaign(
                    client, customerId, budgetResourceName, merchantCenterAccountId);

                // Creates a Smart Shopping ad group.
                string adGroupResourceName = AddSmartShoppingAdGroup(
                    client, customerId, campaignResourceName);

                // Creates a Smart Shopping ad group ad.
                AddSmartShoppingAdGroupAd(client, customerId, adGroupResourceName);

                if (createDefaultListingGroup)
                {
                    // A product group is a subset of inventory. Listing groups are the equivalent
                    // of product groups in the API and allow you to bid on the chosen group or
                    // exclude a group from bidding. This method creates an ad group criterion
                    // containing a listing group.
                    AddDefaultShoppingListingGroup(client, customerId, adGroupResourceName);
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Example #12
0
        // [END setup_remarketing_2]

        /// <summary>
        /// Creates a campaign criterion that targets a user list with a campaign.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">The campaign on which the user list will be targeted.</param>
        /// <param name="userListResourceName">The resource name of the user list to be
        /// targeted.</param>
        /// <returns>The resource name of the newly created campaign criterion.</returns>
        // [START setup_remarketing_4]
        private string TargetAdsInCampaignToUserList(
            GoogleAdsClient client, long customerId, long campaignId, string userListResourceName)
        {
            // Get the CampaignCriterionService client.
            CampaignCriterionServiceClient campaignCriterionServiceClient =
                client.GetService(Services.V10.CampaignCriterionService);

            // Create the campaign criterion.
            CampaignCriterion campaignCriterion = new CampaignCriterion
            {
                Campaign = ResourceNames.Campaign(customerId, campaignId),
                UserList = new UserListInfo
                {
                    UserList = userListResourceName
                }
            };

            // Create the operation.
            CampaignCriterionOperation campaignCriterionOperation = new CampaignCriterionOperation
            {
                Create = campaignCriterion
            };

            // Add the campaign criterion and print the resulting criterion's resource name.
            MutateCampaignCriteriaResponse mutateCampaignCriteriaResponse =
                campaignCriterionServiceClient.MutateCampaignCriteria(customerId.ToString(),
                                                                      new[] { campaignCriterionOperation });

            string campaignCriterionResourceName =
                mutateCampaignCriteriaResponse.Results.First().ResourceName;

            Console.WriteLine("Successfully created campaign criterion with resource name " +
                              $"'{campaignCriterionResourceName}' targeting user list with resource name " +
                              $"'{userListResourceName}' with campaign with ID {campaignId}.");

            return(campaignCriterionResourceName);
        }
Example #13
0
        /// <summary>
        /// Runs the examples from command line arguments.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        /// <returns>The application's exit code. The valid return codes are:
        /// /// <list type="bullet">
        /// <item><description>0. The code example ran successfully.</description></item>
        /// <item><description>1. The code example threw an exception and did not complete
        /// successfully.</description></item>
        /// <item><description>2. The application was invoked with an incorrect command line
        /// argument.</description></item>
        /// </list>
        /// </returns>
        private static int RunExamplesFromCommandLineArguments(string[] args)
        {
            ExampleRunner runner = new ExampleRunner();

            runner.LoadCodeExamples(Assembly.GetExecutingAssembly());

            if (args.Length == 0)
            {
                // Bad command line parameter.
                ShowUsage(runner);
                return(2);
            }

            GoogleAdsClient session     = new GoogleAdsClient();
            string          exampleName = args[0];

            try
            {
                runner.Run(exampleName, session, args.Skip(1));
                return(0);
            }
            catch (TargetInvocationException)
            {
                // Indicates a failure due to an unhandled exception.
                return(1);
            }
            catch (Exception e) when(e is KeyNotFoundException || e is ArgumentException ||
                                     e is TargetParameterCountException)
            {
                // Bad command line parameter.
                // Note: There are a couple more exceptions that the runner may throw, but all
                // those indicate a failure with the runner implementation than a code example
                // failure.
                ShowUsage(runner);
                return(2);
            }
        }
Example #14
0
        /// <summary>
        /// Creates a new hotel ad group ad in the specified 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="adGroupResourceName">The resource name of ad group that a new ad group
        /// ad will belong to</param>
        private static void AddHotelAdGroupAd(GoogleAdsClient client, long customerId,
                                              string adGroupResourceName)
        {
            // Get the AdGroupAdService.
            AdGroupAdServiceClient service = client.GetService(Services.V4.AdGroupAdService);

            // Create a new ad group ad and sets the hotel ad to it.
            AdGroupAd adGroupAd = new AdGroupAd()
            {
                // Create a new hotel ad.
                Ad = new Ad()
                {
                    HotelAd = new HotelAdInfo(),
                },
                // Set the ad group.
                AdGroup = adGroupResourceName,
                // Set the ad group ad to enabled.  Setting this to paused will cause an error
                // for hotel campaigns.  For hotels pausing should happen at either the ad group or
                // campaign level.
                Status = AdGroupAdStatus.Enabled
            };

            // Create an ad group ad operation.
            AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation()
            {
                Create = adGroupAd
            };

            // Issue a mutate request to add an ad group ad.
            MutateAdGroupAdsResponse response = service.MutateAdGroupAds(customerId.ToString(),
                                                                         new AdGroupAdOperation[] { adGroupAdOperation });

            MutateAdGroupAdResult addedAdGroupAd = response.Results[0];

            Console.WriteLine($"Added a hotel ad group ad with resource name " +
                              $"{addedAdGroupAd.ResourceName}.");
        }
Example #15
0
        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            AddGoogleMyBusinessLocationExtensions codeExample =
                new AddGoogleMyBusinessLocationExtensions();

            Console.WriteLine(codeExample.Description);

            GoogleAdsClient client = new GoogleAdsClient();

            // The customer ID for which the call is made.
            int customerId = int.Parse("INSERT_CUSTOMER_ID_HERE");

            // The email address of either an owner or a manager of the GMB account.
            string gmbEmailAddress = "INSERT_GMB_EMAIL_ADDRESS_HERE";

            // If the gmbEmailAddress above is the same user you used to generate
            // your Google Ads API refresh token, leave the assignment below unchanged.
            // Otherwise, to obtain an access token for your GMB account, run the
            // AuthenticateInStandaloneApplication code example while logged in as the same
            // user as gmbEmailAddress. Copy and paste the AccessToken value into the
            // assignment below and delete the line after it.

            // string gmbAccessToken = "INSERT_GMB_ACCESS_TOKEN_HERE";
            string gmbAccessToken = client.Config.OAuth2AccessToken;

            // If the gmbEmailAddress above is for a GMB manager instead of the GMB
            // account owner, then set businessAccountIdentifier to the Google+ Page ID of
            // a location for which the manager has access. This information is available
            // through the Google My Business API. See
            // https://developers.google.com/my-business/reference/rest/v4/accounts.locations#locationkey
            // for details.
            string businessAccountId = null;

            codeExample.Run(new GoogleAdsClient(), customerId, gmbEmailAddress,
                            businessAccountId, gmbAccessToken);
        }
        /// <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="merchantCenterAccountId">The Merchant Center account ID.</param>
        /// <param name="createDefaultListingGroup">The boolean to indicate if a default listing
        /// group should be created for the ad group. Set to false if the listing group will be
        /// constructed elsewhere.
        ///
        /// See AddShoppingListingGroupTree for a more comprehensive example.</param>
        public void Run(GoogleAdsClient client, long customerId, long merchantCenterAccountId,
                        bool createDefaultListingGroup)
        {
            try
            {
                // Creates a budget to be used by the campaign that will be created below.
                string budgetResourceName = AddCampaignBudget(client, customerId);

                // Creates a standard shopping campaign.
                string campaignResourceName = AddStandardShoppingCampaign(
                    client, customerId, budgetResourceName, merchantCenterAccountId);

                // Creates a product shopping ad group.
                string adGroupResourceName = AddProductShoppingAdGroup(
                    client, customerId, campaignResourceName);

                // Creates a product shopping ad group ad.
                AddProductShoppingAdGroupAd(client, customerId, adGroupResourceName);

                if (createDefaultListingGroup)
                {
                    // Creates an ad group criterion containing a listing group.
                    // This will be the listing group tree for 'All products' and will contain
                    // a single biddable unit node.
                    AddDefaultShoppingListingGroup(client, customerId, adGroupResourceName);
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <summary>
        /// Updates a campaign to set the DSA feed.
        /// </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="feedResourceName">The DSA feed resource name</param>
        /// <param name="campaignId">ID of the campaign for which DSA settings are updated.</param>
        private void UpdateCampaignDsaSetting(GoogleAdsClient client, long customerId,
                                              string feedResourceName, long campaignId)
        {
            // Get the CampaignService.
            CampaignServiceClient campaignService = client.GetService(
                Services.V3.CampaignService);

            DynamicSearchAdsSetting dsaSetting = GetDsaSetting(client, customerId, campaignId);

            dsaSetting.Feeds.Add(feedResourceName);

            // Create the campaign.
            Campaign campaign = new Campaign()
            {
                ResourceName            = ResourceNames.Campaign(customerId, campaignId),
                DynamicSearchAdsSetting = dsaSetting
            };

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

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

            // Display the results.
            foreach (MutateCampaignResult mutateCampaignResult in response.Results)
            {
                Console.WriteLine($"Updated campaign with resourceName: " +
                                  $"'{mutateCampaignResult.ResourceName}'.");
            }
        }
Example #18
0
        /// <summary>
        /// Runs the examples from command line arguments.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        private static void RunExamplesFromCommandLineArguments(string[] args)
        {
            ExampleRunner runner = new ExampleRunner();

            runner.LoadCodeExamples(Assembly.GetExecutingAssembly());

            if (args.Length == 0)
            {
                ShowUsage(runner);
                return;
            }

            GoogleAdsClient session     = new GoogleAdsClient();
            string          exampleName = args[0];

            try
            {
                runner.Run(exampleName, session, args.Skip(1));
            }
            catch (KeyNotFoundException)
            {
                ShowUsage(runner);
            }
        }
        /// <summary>
        /// Fetches the draft campaign associated with a campaign draft.
        /// </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="draftResourceName">Resource name of the draft.</param>
        /// <returns></returns>
        private static string FetchDraftCampaign(GoogleAdsClient client, long customerId,
                                                 string draftResourceName)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService =
                client.GetService(Services.V10.GoogleAdsService);

            // Once the draft is created, you can modify the draft campaign as if it were
            // a real campaign. For example, you may add criteria, adjust bids, or even
            // include additional ads. Adding a criterion is shown here.
            string query = $@"
                SELECT
                    campaign_draft.draft_campaign
                FROM
                    campaign_draft
                WHERE
                    campaign_draft.resource_name = '{draftResourceName}'";

            // Get the draft campaign resource name.
            string draftCampaignResourceName = googleAdsService.Search(
                customerId.ToString(), query).First().CampaignDraft.DraftCampaign;

            return(draftCampaignResourceName);
        }
Example #20
0
        /// <summary>
        /// Creates the budget.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <returns>The newly created budget instance.</returns>
        private static gagvr::CampaignBudget CreateBudget(GoogleAdsClient client, long customerId)
        {
            // Get the CampaignBudgetService.
            gagvs::CampaignBudgetServiceClient budgetService = client.GetService(
                Services.V6.CampaignBudgetService);

            // Create the campaign budget.
            gagvr::CampaignBudget budget = new gagvr::CampaignBudget()
            {
                Name           = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString(),
                DeliveryMethod = gag__BudgetDeliveryMethod.Standard,
                AmountMicros   = 500000
            };

            // Create the operation.
            gagvs::CampaignBudgetOperation budgetOperation = new gagvs::CampaignBudgetOperation()
            {
                Create = budget
            };

            // Create the campaign budget.
            gagvs::MutateCampaignBudgetsResponse response = budgetService.MutateCampaignBudgets(
                customerId.ToString(), new gagvs::CampaignBudgetOperation[] { budgetOperation });

            // Retrieve the newly created budget.
            string newResourceName = response.Results[0].ResourceName;
            gagvr::CampaignBudget newCampaignBudget =
                GetBudget(client, customerId, newResourceName);

            // Display the results.
            Console.WriteLine($"Budget with ID={newCampaignBudget.Id} and name=" +
                              $"'{newCampaignBudget.Name}' was created.");

            // Return the newly created budget.
            return(newCampaignBudget);
        }
Example #21
0
        /// <summary>
        /// Creates the campaign experiment.
        /// </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="campaignDraftResourceName">The campaign draft resource name.</param>
        /// <returns>The resource name of the newly created campaign experiment.</returns>
        internal static string CreateCampaignExperiment(GoogleAdsClient client, long customerId,
                                                        string campaignDraftResourceName)
        {
            // Get the CampaignExperimentService.
            CampaignExperimentServiceClient campaignExperimentService =
                client.GetService(Services.V6.CampaignExperimentService);

            CampaignExperiment experiment = new CampaignExperiment()
            {
                CampaignDraft       = campaignDraftResourceName,
                Name                = "Campaign Experiment - " + ExampleUtilities.GetRandomString(),
                TrafficSplitPercent = 50,
                TrafficSplitType    = CampaignExperimentTrafficSplitType.RandomQuery
            };

            Operation <Empty, CreateCampaignExperimentMetadata> operation =
                campaignExperimentService.CreateCampaignExperiment(
                    customerId.ToString(), experiment);

            string experimentResourceName = operation.Metadata.CampaignExperiment;

            operation.PollUntilCompleted();
            return(experimentResourceName);
        }
Example #22
0
        /// <summary>
        /// Targets the feed items to the given ad group.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="adGroupId">The ID of the Ad Group being targeted.</param>
        /// <param name="feedItem">The feed item that was added to the feed.</param>
        private void CreateAdGroupTargeting(GoogleAdsClient client, long customerId, long adGroupId,
                                            string feedItem)
        {
            FeedItemTargetServiceClient feedItemTargetServiceClient =
                client.GetService(Services.V4.FeedItemTargetService);

            FeedItemTarget feedItemTarget = new FeedItemTarget()
            {
                FeedItem = feedItem,
                AdGroup  = ResourceNames.AdGroup(customerId, adGroupId)
            };

            FeedItemTargetOperation operation = new FeedItemTargetOperation()
            {
                Create = feedItemTarget
            };

            MutateFeedItemTargetsResponse response = feedItemTargetServiceClient
                                                     .MutateFeedItemTargets(customerId.ToString(), new[] { operation });

            Console.WriteLine(
                $"Created feed item target '{response.Results.First().ResourceName}' " +
                $"for feed item '{feedItem}'.");
        }
        /// <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>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Gets the BatchJobService.
            BatchJobServiceClient batchJobService =
                client.GetService(Services.V4.BatchJobService);

            try
            {
                string batchJobResourceName = CreateBatchJob(batchJobService, customerId);
                AddAllBatchJobOperations(batchJobService, customerId, batchJobResourceName);
                Operation <Empty, BatchJobMetadata> operationResponse =
                    RunBatchJob(batchJobService, batchJobResourceName);
                PollBatchJob(operationResponse);
                FetchAndPrintResults(batchJobService, batchJobResourceName);
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
Example #24
0
        // [END migrate_promotion_feed_to_asset_2]

        /// <summary>
        /// Associates the specified Promotion asset with the specified ad groups.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="promotionAssetResourceName">The string resource name of the Promotion
        /// Asset.</param>
        /// <param name="adGroupIds">A list of ad group IDs with which the Asset should be
        /// associated.</param>
        private void AssociateAssetWithAdGroups(GoogleAdsClient client, long customerId,
                                                string promotionAssetResourceName, List <long> adGroupIds)
        {
            if (adGroupIds.Count == 0)
            {
                Console.WriteLine("Asset was not associated with any ad groups.");
                return;
            }

            AdGroupAssetServiceClient adGroupAssetServiceClient = client.GetService(Services.V10
                                                                                    .AdGroupAssetService);

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

            foreach (long adGroupId in adGroupIds)
            {
                operations.Add(new AdGroupAssetOperation
                {
                    Create = new AdGroupAsset
                    {
                        Asset     = promotionAssetResourceName,
                        FieldType = AssetFieldTypeEnum.Types.AssetFieldType.Promotion,
                        AdGroup   = ResourceNames.AdGroup(customerId, adGroupId),
                    }
                });
            }

            MutateAdGroupAssetsResponse response = adGroupAssetServiceClient.MutateAdGroupAssets(
                customerId.ToString(), operations);

            foreach (MutateAdGroupAssetResult result in response.Results)
            {
                Console.WriteLine($"Created ad group asset with resource name " +
                                  $"{result.ResourceName}.");
            }
        }
Example #25
0
        // [END setup_remarketing]

        /// <summary>
        /// Creates an ad group criterion that targets a user list with an ad group.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupId">The ad group on which the user list will be targeted.</param>
        /// <param name="userListResourceName">The resource name of the user list to be
        /// targeted.</param>
        /// <returns>The resource name of the newly created ad group criterion.</returns>
        // [START setup_remarketing_1]
        private string TargetAdsInAdGroupToUserList(
            GoogleAdsClient client, long customerId, long adGroupId, string userListResourceName)
        {
            // Get the AdGroupCriterionService client.
            AdGroupCriterionServiceClient adGroupCriterionServiceClient = client.GetService
                                                                              (Services.V10.AdGroupCriterionService);

            // Create the ad group criterion targeting members of the user list.
            AdGroupCriterion adGroupCriterion = new AdGroupCriterion
            {
                AdGroup  = ResourceNames.AdGroup(customerId, adGroupId),
                UserList = new UserListInfo
                {
                    UserList = userListResourceName
                }
            };

            // Create the operation.
            AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation
            {
                Create = adGroupCriterion
            };

            // Add the ad group criterion, then print and return the new criterion's resource name.
            MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
                adGroupCriterionServiceClient.MutateAdGroupCriteria(customerId.ToString(),
                                                                    new[] { adGroupCriterionOperation });

            string adGroupCriterionResourceName =
                mutateAdGroupCriteriaResponse.Results.First().ResourceName;

            Console.WriteLine("Successfully created ad group criterion with resource name " +
                              $"'{adGroupCriterionResourceName}' targeting user list with resource name " +
                              $"'{userListResourceName}' with ad group with ID {adGroupId}.");
            return(adGroupCriterionResourceName);
        }
Example #26
0
 /// <summary>
 /// Runs the code example.
 /// </summary>
 /// <param name="client">The Google Ads client.</param>
 /// <param name="customerId">The customer ID for which the call is made.</param>
 /// <param name="chainId">The retail chain ID.</param>
 /// <param name="campaignId">The campaign ID for which the affiliate location extensions
 /// are added.</param>
 public void Run(GoogleAdsClient client, long customerId, long chainId, long campaignId)
 {
     try
     {
         string feedResourceName = CreateAffiliateLocationExtensionFeed(
             client, customerId, chainId);
         // After the completion of the feed creation operation above the added feed will not
         // be available for usage in a campaign feed until the feed mappings are created.
         // We will wait with an exponential back-off policy until the feed mappings have
         // been created.
         FeedMapping feedMapping = WaitForFeedToBeReady(client, customerId,
                                                        feedResourceName);
         CreateCampaignFeed(client, customerId, campaignId, feedMapping,
                            feedResourceName, chainId);
     }
     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 an image extension.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The client customer ID.</param>
        /// <param name="imageAssetId">The ID of the image asset to be used for creating image
        /// extension.</param>
        /// <returns>Resource name of the newly created image extension.</returns>
        private static string CreateImageExtension(GoogleAdsClient client, long customerId,
                                                   long imageAssetId)
        {
            // Get the ExtensionFeedItemServiceClient.
            ExtensionFeedItemServiceClient extensionFeedItemService =
                client.GetService(Services.V10.ExtensionFeedItemService);

            // Creates the image feed item using the provided image.
            ImageFeedItem imageFeedItem = new ImageFeedItem()
            {
                ImageAsset = ResourceNames.Asset(customerId, imageAssetId)
            };

            // Creates an ExtensionFeedItem from the ImageFeedItem.
            ExtensionFeedItem extensionFeedItem = new ExtensionFeedItem()
            {
                ImageFeedItem = imageFeedItem
            };

            ExtensionFeedItemOperation operation = new ExtensionFeedItemOperation()
            {
                Create = extensionFeedItem
            };

            // Adds the ExtensionFeedItem.
            MutateExtensionFeedItemsResponse response =
                extensionFeedItemService.MutateExtensionFeedItems(customerId.ToString(),
                                                                  new[] { operation });

            // Displays the result.
            string resourceName = response.Results.First().ResourceName;

            Console.WriteLine($"Created an image extension with resource name '{resourceName}'.");

            return(resourceName);
        }
Example #28
0
        // [END migrate_promotion_feed_to_asset]

        /// <summary>
        /// Associates the specified Promotion asset with the specified campaigns.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="promotionAssetResourceName">The string resource name of the Promotion
        /// Asset.</param>
        /// <param name="campaignIds">A list of campaign IDs with which the Asset should be
        /// associated.</param>
        // [START migrate_promotion_feed_to_asset_2]
        private void AssociateAssetWithCampaigns(GoogleAdsClient client, long customerId,
                                                 string promotionAssetResourceName, List <long> campaignIds)
        {
            if (campaignIds.Count == 0)
            {
                Console.WriteLine("Asset was not associated with any campaigns.");
                return;
            }

            CampaignAssetServiceClient campaignAssetServiceClient = client.GetService(Services.V10
                                                                                      .CampaignAssetService);

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

            foreach (long campaignId in campaignIds)
            {
                operations.Add(new CampaignAssetOperation
                {
                    Create = new CampaignAsset
                    {
                        Asset     = promotionAssetResourceName,
                        FieldType = AssetFieldTypeEnum.Types.AssetFieldType.Promotion,
                        Campaign  = ResourceNames.Campaign(customerId, campaignId),
                    }
                });
            }

            MutateCampaignAssetsResponse response = campaignAssetServiceClient.MutateCampaignAssets(
                customerId.ToString(), operations);

            foreach (MutateCampaignAssetResult result in response.Results)
            {
                Console.WriteLine($"Created campaign asset with resource name " +
                                  $"{result.ResourceName}.");
            }
        }
Example #29
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>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsServiceClient.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V4.GoogleAdsService);

            // Construct a GAQL query which will retrieve AccountBudgetProposals.
            String searchQuery =
                @"SELECT account_budget_proposal.id,
                     account_budget_proposal.account_budget,
                     account_budget_proposal.billing_setup,
                     account_budget_proposal.status,
                     account_budget_proposal.proposed_name,
                     account_budget_proposal.proposed_notes,
                     account_budget_proposal.proposed_purchase_order_number,
                     account_budget_proposal.proposal_type,
                     account_budget_proposal.approval_date_time,
                     account_budget_proposal.creation_date_time
                 FROM 
                     account_budget_proposal";

            // Creates a request that will retrieve all account budget proposals using pages of the
            // specified page size.
            SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
            {
                PageSize   = PAGE_SIZE,
                Query      = searchQuery,
                CustomerId = customerId.ToString()
            };

            try
            {
                // Issues the search request.
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
                    googleAdsService.Search(request);

                // Iterates over all rows in all pages and prints the requested field values for
                // the account budget in each row.
                foreach (GoogleAdsRow googleAdsRow in searchPagedResponse)
                {
                    AccountBudgetProposal proposal = googleAdsRow.AccountBudgetProposal;
                    Console.WriteLine($"Account budget proposal with ID '{proposal.Id}' " +
                                      $"status '{proposal.Status}', account_budget '{proposal.AccountBudget}' " +
                                      $"billing_setup '{proposal.BillingSetup}', " +
                                      $"proposed_name '{proposal.ProposedName}', " +
                                      $"proposed_notes '{proposal.ProposedNotes}', " +
                                      $"proposed_po_number '{proposal.ProposedPurchaseOrderNumber}', " +
                                      $"proposal_type '{proposal.ProposalType}', " +
                                      $"approval_date_time '{proposal.ApprovalDateTime}', " +
                                      $"creation_date_time '{proposal.CreationDateTime}'.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <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">The ad group to which bid modifiers are set.</param>
        public void Run(GoogleAdsClient client, long customerId, long adGroupId)
        {
            // Get the AdGroupBidModifierService.
            AdGroupBidModifierServiceClient service = client.GetService(
                Services.V2.AdGroupBidModifierService);

            // Constructs the ad group resource name to use for each bid modifier.
            string adGroupResourceName = ResourceNames.AdGroup(customerId, adGroupId);

            // 1) Create an ad group bid modifier based on the hotel check-in day.
            AdGroupBidModifier checkInDayAdGroupBidModifier = new AdGroupBidModifier()
            {
                // Sets the resource name to the ad group resource name joined with the criterion
                // ID whose value corresponds to the desired check-in day.
                AdGroup         = adGroupResourceName,
                HotelCheckInDay = new HotelCheckInDayInfo()
                {
                    DayOfWeek = DayOfWeek.Monday
                },

                // Set the bid modifier value to 150%.
                BidModifier = 1.5,
            };

            // Creates an ad group bid modifier operation.
            var checkInDayAdGroupBidModifierOperation = new AdGroupBidModifierOperation()
            {
                Create = checkInDayAdGroupBidModifier
            };

            // 2) Create an ad group bid modifier based on the hotel length of stay.
            AdGroupBidModifier lengthOfStayAdGroupBidModifier = new AdGroupBidModifier()
            {
                // Set the ad group.
                AdGroup = ResourceNames.AdGroup(customerId, adGroupId),

                // Set the hotel length of stay info.
                HotelLengthOfStay = new HotelLengthOfStayInfo()
                {
                    MinNights = 3,
                    MaxNights = 7
                },

                // Set the bid modifier value to 170%.
                BidModifier = 1.7
            };

            // Create an ad group bid modifier operation.
            var lengthOfStayAdGroupBidModifierOperation = new AdGroupBidModifierOperation()
            {
                Create = lengthOfStayAdGroupBidModifier
            };

            try
            {
                // Issue a mutate request to add an ad group bid modifiers.
                MutateAdGroupBidModifiersResponse response = service.MutateAdGroupBidModifiers(
                    customerId.ToString(),
                    new AdGroupBidModifierOperation[] {
                    checkInDayAdGroupBidModifierOperation,
                    lengthOfStayAdGroupBidModifierOperation
                }
                    );

                // Display the resource names of the added ad group bid modifiers.
                Console.WriteLine($"Added {response.Results.Count} hotel ad group bid modifiers:");

                foreach (MutateAdGroupBidModifierResult result in response.Results)
                {
                    Console.WriteLine($"- {result.ResourceName}");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
            }
        }