示例#1
0
        /// <summary>
        /// Accepts the invitation.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="clientCustomerId">The client customer ID.</param>
        /// <param name="managerLinkResourceName">The manager link resource name.</param>
        private void AcceptInvitation(GoogleAdsClient client, long clientCustomerId,
                                      string managerLinkResourceName)
        {
            // Get the CustomerManagerLinkService.
            CustomerManagerLinkServiceClient customerManagerLinkService =
                client.GetService(Services.V1.CustomerManagerLinkService);

            // Create a client with the manager customer ID as login customer ID.
            client.Config.LoginCustomerId = clientCustomerId.ToString();

            // Creates the customer manager link with the updated status.
            CustomerManagerLink customerManagerLink = new CustomerManagerLink()
            {
                ResourceName = managerLinkResourceName,
                Status       = ManagerLinkStatus.Active
            };

            // Creates a customer manager link operation for updating the one above.
            CustomerManagerLinkOperation customerManagerLinkOperation =
                new CustomerManagerLinkOperation()
            {
                Update     = customerManagerLink,
                UpdateMask = FieldMasks.AllSetFieldsOf(customerManagerLink)
            };

            // Issue a mutate request to update the customer manager link.
            MutateCustomerManagerLinkResponse response =
                customerManagerLinkService.MutateCustomerManagerLink(
                    clientCustomerId.ToString(), new[] { customerManagerLinkOperation }
                    );

            // Prints the result.
            Console.WriteLine($"The client {clientCustomerId} accepted the invitation with " +
                              $"the resource name '{response.Results[0].ResourceName}");
        }
示例#2
0
        /// <summary>
        ///  Adds campaigns to a CampaignGroup in the specified client account.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignGroupResourceName">The resource name of the campaign
        /// group.</param>
        /// <param name="campaignIds">The IDs of the campaigns to add to the campaign
        /// group.</param>
        private static void AddCampaignsToGroup(GoogleAdsClient client, long customerId,
                                                String campaignGroupResourceName, long[] campaignIds)
        {
            CampaignServiceClient campaignServiceClient = client.GetService(
                Services.V0.CampaignService);
            List <CampaignOperation> operations = new List <CampaignOperation>();

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

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

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

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

        /// <summary>
        /// Updates the bid modifier on an ad group criterion.
        /// </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="adGroupCriterionResourceName">The resource name of the ad group criterion to update.</param>
        /// <param name="bidModifierValue">The bid modifier value.</param>
        private void ModifyAdGroupBids(
            GoogleAdsClient client,
            long customerId,
            string adGroupCriterionResourceName,
            double bidModifierValue)
        {
            // Get the AdGroupCriterionService client.
            AdGroupCriterionServiceClient adGroupCriterionServiceClient =
                client.GetService(Services.V10.AdGroupCriterionService);

            // Create the ad group criterion with a bid modifier. You may alternatively set the bid
            // for the ad group criterion directly.
            AdGroupCriterion adGroupCriterion = new AdGroupCriterion
            {
                ResourceName = adGroupCriterionResourceName,
                BidModifier  = bidModifierValue
            };

            // Create the update operation.
            AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation
            {
                Update     = adGroupCriterion,
                UpdateMask = FieldMasks.AllSetFieldsOf(adGroupCriterion)
            };

            // Update the ad group criterion and print the results.
            MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
                adGroupCriterionServiceClient.MutateAdGroupCriteria(customerId.ToString(),
                                                                    new[] { adGroupCriterionOperation });

            Console.WriteLine("Successfully updated the bid for ad group criterion with resource " +
                              $"name '{mutateAdGroupCriteriaResponse.Results.First().ResourceName}'.");
        }
        /// <summary>
        /// Updates the status of a Merchant Center link request for a given resource name.
        /// </summary>
        /// <param name="customerId">The customer identifier.</param>
        /// <param name="merchantCenterLinkService">The merchant center link service.</param>
        /// <param name="merchantCenterLink">The merchant center link.</param>
        /// <param name="status"></param>
        private static void UpdateMerchantCenterLinkStatus(long customerId,
                                                           MerchantCenterLinkServiceClient merchantCenterLinkService,
                                                           MerchantCenterLink merchantCenterLink, MerchantCenterLinkStatus status)
        {
            // Enables the pending link.
            MerchantCenterLink linkToUpdate = new MerchantCenterLink()
            {
                ResourceName = merchantCenterLink.ResourceName,
                Status       = status
            };

            // Creates an operation.
            MerchantCenterLinkOperation operation = new MerchantCenterLinkOperation()
            {
                Update     = linkToUpdate,
                UpdateMask = FieldMasks.AllSetFieldsOf(linkToUpdate)
            };

            // Updates the link.
            MutateMerchantCenterLinkResponse mutateResponse =
                merchantCenterLinkService.MutateMerchantCenterLink(
                    customerId.ToString(), operation);

            // Displays the result.
            Console.WriteLine($"The status of Merchant Center Link with resource name " +
                              $"'{mutateResponse.Result.ResourceName}' to Google Ads account : " +
                              $"{customerId} was updated to {status}.");
        }
示例#5
0
        public void TestFromChanges(TestCase testCase)
        {
            FieldMask actual = FieldMasks.FromChanges(testCase.OriginalResource,
                                                      testCase.ModifiedResource);

            Assert.AreEqual(testCase.ExpectedMask, actual);
        }
示例#6
0
        // [END list_accessible_strategies]

        // [START attach_strategy]
        /// <summary>
        /// Attaches a specified cross-account bidding strategy to a campaign owned by a specified
        /// client customer account.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads client customer ID for which the call is
        /// made.</param>
        /// <param name="campaignId">The ID of the campaign owned by the customer ID to which the
        /// cross-account bidding strategy will be attached.</param>
        /// <param name="biddingStrategyResourceName">A cross-account bidding strategy resource
        /// name.</param>
        private void AttachCrossAccountBiddingStrategyToCampaign(GoogleAdsClient client,
                                                                 long customerId, long campaignId, string biddingStrategyResourceName)
        {
            CampaignServiceClient campaignServiceClient =
                client.GetService(Services.V10.CampaignService);

            Campaign campaign = new Campaign
            {
                ResourceName    = ResourceNames.Campaign(customerId, campaignId),
                BiddingStrategy = biddingStrategyResourceName
            };

            // Mutate the campaign and print the resource name of the updated campaign.
            MutateCampaignsResponse mutateCampaignsResponse =
                campaignServiceClient.MutateCampaigns(customerId.ToString(), new[]
            {
                new CampaignOperation
                {
                    Update     = campaign,
                    UpdateMask = FieldMasks.AllSetFieldsOf(campaign)
                }
            });

            Console.WriteLine("Updated campaign with resource name " +
                              $"'{mutateCampaignsResponse.Results.First().ResourceName}'.");
        }
示例#7
0
        /// <summary>
        /// Modifies the user access role to a specified value.
        /// </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="userId">ID of the user whose access role is modified.</param>
        /// <param name="accessRole">The updated access role.</param>
        private void ModifyUserAccess(GoogleAdsClient client, long customerId, long userId,
                                      AccessRole accessRole)
        {
            // Get the CustomerUserAccessService.
            CustomerUserAccessServiceClient userAccessService = client.GetService(
                Services.V6.CustomerUserAccessService);

            // Creates the modified user access.
            CustomerUserAccess userAccess = new CustomerUserAccess()
            {
                ResourceName = ResourceNames.CustomerUserAccess(customerId, userId),
                AccessRole   = accessRole
            };

            // Creates the operation.
            CustomerUserAccessOperation operation = new CustomerUserAccessOperation()
            {
                Update     = userAccess,
                UpdateMask = FieldMasks.AllSetFieldsOf(userAccess)
            };

            // Updates the user access.
            MutateCustomerUserAccessResponse response =
                userAccessService.MutateCustomerUserAccess(
                    customerId.ToString(), operation);

            // Displays the result.
            Console.WriteLine($"Successfully modified customer user access with " +
                              $"resource name '{response.Result.ResourceName}'.");
        }
        /// <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>
        // [START update_audience_target_restriction_2]
        private void UpdateTargetingSetting(GoogleAdsClient client, long customerId, long
                                            adGroupId, TargetingSetting targetingSetting)
        {
            // Get the AdGroupService client.
            AdGroupServiceClient adGroupServiceClient =
                client.GetService(Services.V10.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'.");
        }
示例#9
0
        // [END setup_remarketing_4]

        /// <summary>
        /// Updates the bid modifier on a campaign criterion.
        /// </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="campaignCriterionResourceName">The resource name of the campaign criterion to update.</param>
        /// <param name="bidModifierValue">The bid modifier value.</param>
        private void ModifyCampaignBids(
            GoogleAdsClient client,
            long customerId,
            string campaignCriterionResourceName,
            double bidModifierValue)
        {
            // Get the CampaignCriterionService client.
            CampaignCriterionServiceClient campaignCriterionServiceClient =
                client.GetService(Services.V10.CampaignCriterionService);

            // Create the campaign criterion to update.
            CampaignCriterion campaignCriterion = new CampaignCriterion
            {
                ResourceName = campaignCriterionResourceName,
                BidModifier  = (float)bidModifierValue
            };

            // Create the update operation.
            CampaignCriterionOperation campaignCriterionOperation = new CampaignCriterionOperation
            {
                Update     = campaignCriterion,
                UpdateMask = FieldMasks.AllSetFieldsOf(campaignCriterion)
            };

            // Update the campaign criterion and print the results.
            MutateCampaignCriteriaResponse mutateCampaignCriteriaResponse =
                campaignCriterionServiceClient.MutateCampaignCriteria(customerId.ToString(),
                                                                      new[] { campaignCriterionOperation });

            Console.WriteLine("Successfully updated the bid for campaign criterion with resource " +
                              $"name '{mutateCampaignCriteriaResponse.Results.First().CampaignCriterion}'.");
        }
示例#10
0
        /// <summary>
        /// Updates attribute value of the feed item. In order to update a FeedItemAttributeValue
        /// you must update the FeedItem.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="feedId">ID of the feed containing the feed item to be updated.</param>
        /// <param name="feedItemId">ID of the feed item to be updated.</param>
        /// <param name="flightPlaceholderField">the placeholder type for the attribute to be
        /// updated.</param>
        /// <param name="attributeValue">String value with which to update the
        /// FeedAttributeValue.</param>
        private void UpdateFeedItem(GoogleAdsClient client, long customerId, long feedId,
                                    long feedItemId, string flightPlaceholderField, string attributeValue)
        {
            // Get the FeedItemServiceClient.
            FeedItemServiceClient feedItemService =
                client.GetService(Services.V2.FeedItemService);

            // Gets the feed resource name.
            string feedResourceName = ResourceNames.Feed(customerId, feedId);

            // Gets a map of the placeholder values and feed attributes.
            Dictionary <FlightPlaceholderField, FeedAttribute> feedAttributes =
                GetFeed(client, customerId, feedResourceName);

            // Gets the ID of the attribute to update. This is needed to specify which
            // FeedItemAttributeValue will be updated in the given FeedItem.
            FlightPlaceholderField placeholderField = (FlightPlaceholderField)Enum.Parse(
                typeof(FlightPlaceholderField), flightPlaceholderField);
            long attributeId = feedAttributes[placeholderField].Id.Value;

            // Gets the feed item resource name.
            string feedItemResourceName = ResourceNames.FeedItem(customerId, feedId, feedItemId);
            // Retrieves the feed item and its associated attributes based on its resource name.
            FeedItem feedItem = GetFeedItem(client, customerId, feedItemResourceName);
            // Creates the updated FeedItemAttributeValue.
            FeedItemAttributeValue feedItemAttributeValue = new FeedItemAttributeValue()
            {
                FeedAttributeId = attributeId,
                StringValue     = attributeValue
            };

            // Creates a new FeedItem from the existing FeedItem. Any FeedItemAttributeValues that are
            // not included in the updated FeedItem will be removed from the FeedItem, which is why you
            // must create the FeedItem from the existing FeedItem and set the field(s) that will be
            // updated.
            feedItem.AttributeValues[GetAttributeIndex(feedItem, feedItemAttributeValue)] =
                feedItemAttributeValue;

            // Creates the operation.
            FeedItemOperation operation = new FeedItemOperation()
            {
                Update     = feedItem,
                UpdateMask = FieldMasks.AllSetFieldsOf(feedItem)
            };

            // Updates the feed item.
            MutateFeedItemsResponse response =
                feedItemService.MutateFeedItems(customerId.ToString(), new[] { operation });

            foreach (MutateFeedItemResult result in response.Results)
            {
                Console.WriteLine($"Updated feed item with resource name '{result.ResourceName}'.");
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </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="feedId">The Feed ID to which the feed item belongs.</param>
        /// <param name="feedItemId">The ID of the feed item to be updated.</param>
        /// <param name="flightPlaceholderFieldName">
        /// The flight placeholder field name for the attribute to be removed.
        /// </param>
        public void Run(GoogleAdsClient client, long customerId, long feedId, long feedItemId,
                        string flightPlaceholderFieldName)
        {
            // Creates the Feed Item service client.
            FeedItemServiceClient feedItemServiceClient = client.GetService(
                Services.V10.FeedItemService);

            try
            {
                // Gets a map of the placeholder values to feed attributes.
                Dictionary <FlightPlaceholderField, FeedAttribute> placeholdersToFeedAttributesMap =
                    GetFeed(client, customerId, feedId);

                // Removes the attribute from the feed item.
                FlightPlaceholderField flightPlaceholderField =
                    (FlightPlaceholderField)Enum.Parse(typeof(FlightPlaceholderField),
                                                       flightPlaceholderFieldName, true);
                FeedItem feedItem = RemoveAttributeValueFromFeedItem(client, customerId, feedId,
                                                                     feedItemId, placeholdersToFeedAttributesMap, flightPlaceholderField);

                // [START remove_flights_feed_item_attribute_value_1] Creates the operation.
                FeedItemOperation operation = new FeedItemOperation
                {
                    Update     = feedItem,
                    UpdateMask = FieldMasks.AllSetFieldsOf(feedItem)
                };

                // Updates the feed item and prints the results.
                MutateFeedItemsResponse response = feedItemServiceClient.MutateFeedItems
                                                       (customerId.ToString(), new[] { operation });
                foreach (MutateFeedItemResult result in response.Results)
                {
                    Console.WriteLine("Updated feed item with resource name " +
                                      $"'{result.ResourceName}'.");
                }
                // [END remove_flights_feed_item_attribute_value_1]
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
            catch (Exception e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                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="campaignId">The campaign ID.</param>
        /// <param name="feedItemIds">The extension feed item IDs to replace.</param>
        // [START update_sitelink_campaign_extension_setting]
        public void Run(GoogleAdsClient client, long customerId, long campaignId,
                        long[] feedItemIds)
        {
            // Get the CampaignExtensionSettingService.
            CampaignExtensionSettingServiceClient campaignExtensionSettingService =
                client.GetService(Services.V10.CampaignExtensionSettingService);

            // Transform the specified extension feed item IDs to an array of resource names.
            IEnumerable <string> extensionFeedItems = feedItemIds.Select(feedItemId =>
                                                                         ResourceNames.ExtensionFeedItem(customerId, feedItemId));

            // Create a campaign extension setting using the specified campaign ID and extension
            // feed item resource names.
            CampaignExtensionSetting campaignExtensionSetting = new CampaignExtensionSetting
            {
                ResourceName = ResourceNames.CampaignExtensionSetting(customerId, campaignId,
                                                                      ExtensionType.Sitelink)
            };

            campaignExtensionSetting.ExtensionFeedItems.Add(extensionFeedItems);

            // Construct an operation that will update the extension feed item using the FieldMasks
            // utilities to derive the update mask. This mask tells the Google Ads API which
            // attributes of the extension feed item you want to change.
            CampaignExtensionSettingOperation campaignExtensionSettingOperation =
                new CampaignExtensionSettingOperation
            {
                Update     = campaignExtensionSetting,
                UpdateMask = FieldMasks.AllSetFieldsOf(campaignExtensionSetting)
            };

            try
            {
                // Issue a mutate request to update the campaign extension setting.
                MutateCampaignExtensionSettingsResponse response =
                    campaignExtensionSettingService.MutateCampaignExtensionSettings
                        (customerId.ToString(), new[] { campaignExtensionSettingOperation });

                // Print the resource name of the updated campaign extension setting.
                Console.WriteLine("Updated a campaign extension setting with resource name " +
                                  $"'{response.Results.First().ResourceName}'.");
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
示例#13
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="feedItemId">The feed item ID.</param>
        /// <param name="geoTargetConstantId">Geo target constant ID to add to the extension
        ///     feed item. Reverts to the United States (2840) if no value passed.</param>
        // [START AddGeoTarget]
        public void Run(GoogleAdsClient client, long customerId, long feedItemId,
                        long?geoTargetConstantId)
        {
            // Get the ExtensionFeedItemServiceClient.
            ExtensionFeedItemServiceClient extensionFeedItemServiceClient =
                client.GetService(Services.V6.ExtensionFeedItemService);

            // Apply the default geo target constant ID (USA) if none was passed to the function.
            if (!geoTargetConstantId.HasValue)
            {
                geoTargetConstantId = 2840L;
            }

            // Creates an extension feed item using the specified feed item ID and geo target
            // constant ID for targeting.
            ExtensionFeedItem extensionFeedItem = new ExtensionFeedItem()
            {
                ResourceName = ResourceNames.ExtensionFeedItem(customerId, feedItemId),
                TargetedGeoTargetConstant = ResourceNames.GeoTargetConstant(geoTargetConstantId.Value)
            };

            // Constructs an operation that will update the extension feed item, using the
            // FieldMasks utility to derive the update mask. This mask tells the Google Ads API
            // which attributes of the extension feed item you want to change.
            ExtensionFeedItemOperation operation = new ExtensionFeedItemOperation()
            {
                Update     = extensionFeedItem,
                UpdateMask = FieldMasks.AllSetFieldsOf(extensionFeedItem)
            };

            try
            {
                // Issues a mutate request to update the extension feed item.
                MutateExtensionFeedItemsResponse response =
                    extensionFeedItemServiceClient.MutateExtensionFeedItems(customerId.ToString(),
                                                                            new[] { operation });

                // Prints the resource name of the updated extension feed item.
                Console.WriteLine("Updated extension feed item with resource name " +
                                  $"{response.Results.First().ResourceName}.");
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
示例#14
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="adGroupId">The ad group ID that contains the ad.</param>
        /// <param name="adId">AdGroupAdService</param>
        public void Run(GoogleAdsClient client, long customerId, long adGroupId, long adId)
        {
            // Get the AdGroupAdService.
            AdGroupAdServiceClient adGroupAdService = client.GetService(
                Services.V4.AdGroupAdService);

            // Create the ad group ad.
            AdGroupAd adGroupAd = new AdGroupAd
            {
                ResourceName = ResourceNames.AdGroupAd(customerId, adGroupId, adId),
                Status       = AdGroupAdStatus.Paused
            };

            // Create the operation.
            AdGroupAdOperation operation = new AdGroupAdOperation
            {
                // Set the Update field to the ad group ad object.
                Update = adGroupAd,

                // Use the FieldMasks utility to set the UpdateMask field to  a list of all
                // modified fields of the ad group ad.
                UpdateMask = FieldMasks.AllSetFieldsOf(adGroupAd)
            };

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

                // Display the results.
                foreach (MutateAdGroupAdResult result in response.Results)
                {
                    Console.WriteLine($"Ad with resource name = {result.ResourceName} was " +
                                      "paused.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
示例#15
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>
        /// 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="adId"> ID of the ad to update.</param>
        // [START update_expanded_text_ad]
        public void Run(GoogleAdsClient client, long customerId, long adId)
        {
            // Get the AdService.
            AdServiceClient adService = client.GetService(Services.V10.AdService);

            Ad ad = new Ad()
            {
                ResourceName   = ResourceNames.Ad(customerId, adId),
                ExpandedTextAd = new ExpandedTextAdInfo()
                {
                    // Update some properties of the expanded text ad.
                    HeadlinePart1 = "Cruise to Pluto #" + ExampleUtilities.GetShortRandomString(),
                    HeadlinePart2 = "Tickets on sale now",
                    Description   = "Best space cruise ever.",
                },
                FinalUrls       = { "http://www.example.com/" },
                FinalMobileUrls = { "http://www.example.com/mobile" }
            };

            AdOperation operation = new AdOperation()
            {
                Update     = ad,
                UpdateMask = FieldMasks.AllSetFieldsOf(ad)
            };

            try
            {
                // Issue the update request.
                MutateAdsResponse response = adService.MutateAds(customerId.ToString(),
                                                                 new[] { operation });

                // Display the results.
                foreach (MutateAdResult updatedAd in response.Results)
                {
                    Console.WriteLine($"Ad with resource ID = '{updatedAd.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;
            }
        }
示例#17
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="feedItemId">The feed item ID to update.</param>
        /// <param name="sitelinkText">The new sitelink text.</param>
        // [START UpdateSitelink]
        public void Run(GoogleAdsClient client, long customerId, long feedItemId,
                        string sitelinkText)
        {
            // Get the ExtensionFeedItemService.
            ExtensionFeedItemServiceClient extensionFeedItemService =
                client.GetService(Services.V6.ExtensionFeedItemService);

            // Create an extension feed item using the specified feed item ID and sitelink text.
            ExtensionFeedItem extensionFeedItem = new ExtensionFeedItem
            {
                ResourceName     = ResourceNames.ExtensionFeedItem(customerId, feedItemId),
                SitelinkFeedItem = new SitelinkFeedItem
                {
                    LinkText = sitelinkText
                }
            };

            // Construct an operation that will update the extension feed item using the FieldMasks
            // utilities to derive the update mask. This mask tells the Google Ads API which
            // attributes of the extension feed item you want to change.
            ExtensionFeedItemOperation extensionFeedItemOperation = new ExtensionFeedItemOperation
            {
                Update     = extensionFeedItem,
                UpdateMask = FieldMasks.AllSetFieldsOf(extensionFeedItem)
            };

            try
            {
                // Issue a mutate request to update the extension feed item.
                MutateExtensionFeedItemsResponse response =
                    extensionFeedItemService.MutateExtensionFeedItems(
                        customerId.ToString(), new[] { extensionFeedItemOperation });

                // Print the resource name of the updated extension feed item.
                Console.WriteLine("Updated extension feed item with resource name " +
                                  $"'{response.Results.First().ResourceName}'.");
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
示例#18
0
        // [END add_smart_campaign_3]

        // [START add_smart_campaign_4]
        /// <summary>
        /// Creates a MutateOperation to create a new SmartCampaignSetting. SmartCampaignSettings
        /// are unique in that they only support UPDATE operations, which are used to update and
        /// create them. Below we will use a temporary ID in the resource name to associate it with
        /// the campaign created in the previous step.
        /// </summary>
        /// <param name="customerId">The Google Ads customer ID.</param>
        /// <param name="businessLocationId">The ID of a Business Profile location.</param>
        /// <param name="businessName">The name of a Business Profile business.</param>
        /// <returns>A MutateOperation that creates a SmartCampaignSetting.</returns>
        private MutateOperation CreateSmartCampaignSettingOperation(long customerId,
                                                                    ulong?businessLocationId, string businessName)
        {
            SmartCampaignSetting smartCampaignSetting = new SmartCampaignSetting
            {
                // Set a temporary ID in the campaign setting's resource name to associate it with
                // the campaign created in the previous step.
                ResourceName =
                    ResourceNames.SmartCampaignSetting(customerId, SMART_CAMPAIGN_TEMPORARY_ID),
                // Below we configure the SmartCampaignSetting using many of the same details used
                // to generate a budget suggestion.
                PhoneNumber = new SmartCampaignSetting.Types.PhoneNumber
                {
                    CountryCode  = COUNTRY_CODE,
                    PhoneNumber_ = PHONE_NUMBER
                },
                FinalUrl = LANDING_PAGE_URL,
                AdvertisingLanguageCode = LANGUAGE_CODE
            };

            // Either a business location ID or a business name must be added to the
            // SmartCampaignSetting.
            if (businessLocationId.HasValue)
            {
                // Transform Google Business Location ID to a compatible format before
                // passing it onto the API.
                smartCampaignSetting.BusinessLocationId =
                    ConvertBusinessLocationId(businessLocationId.Value);
            }
            else
            {
                smartCampaignSetting.BusinessName = businessName;
            }

            return(new MutateOperation
            {
                SmartCampaignSettingOperation = new SmartCampaignSettingOperation
                {
                    Update = smartCampaignSetting,
                    // Set the update mask on the operation. This is required since the smart
                    // campaign setting is created in an UPDATE operation. Here the update mask
                    // will be a list of all the fields that were set on the SmartCampaignSetting.
                    UpdateMask = FieldMasks.AllSetFieldsOf(smartCampaignSetting)
                }
            });
        }
示例#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="campaignId">ID of the campaign to be updated.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId)
        {
            // Get the CampaignService.
            CampaignServiceClient campaignService = client.GetService(Services.V6.CampaignService);

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

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

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

                // Display the results.
                foreach (MutateCampaignResult updatedCampaign in response.Results)
                {
                    Console.WriteLine($"Campaign with resource ID = " +
                                      $"'{updatedCampaign.ResourceName}' was updated.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <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 that contains the criterion.</param>
        /// <param name="criterionId">ID of the criterion for which bid modifier is updated.</param>
        /// <param name="bidModifierValue">The new value of the bid modifier to update.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId, long criterionId,
                        float?bidModifierValue)
        {
            // Get the CampaignCriterionServiceClient .
            CampaignCriterionServiceClient campaignCriterionService =
                client.GetService(Services.V10.CampaignCriterionService);

            string criterionResourceName = ResourceNames.CampaignCriteria(customerId,
                                                                          campaignId, criterionId);

            // Construct a campaign bid modifier.
            CampaignCriterion campaignCriterion = new CampaignCriterion()
            {
                ResourceName = criterionResourceName,
                BidModifier  = (bidModifierValue != null) ? bidModifierValue.Value : 1.5f,
            };

            // Construct an operation to create the campaign criterion.
            CampaignCriterionOperation op = new CampaignCriterionOperation()
            {
                Update     = campaignCriterion,
                UpdateMask = FieldMasks.AllSetFieldsOf(campaignCriterion)
            };

            // Send the operation in a mutate request.
            try
            {
                MutateCampaignCriteriaResponse response =
                    campaignCriterionService.MutateCampaignCriteria(customerId.ToString(),
                                                                    new CampaignCriterionOperation[] { op });
                foreach (MutateCampaignCriterionResult result in response.Results)
                {
                    Console.WriteLine($"Campaign criterion with resource name" +
                                      $" '{result.ResourceName}' was modified.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
示例#21
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer Id.</param>
        /// <param name="adGroupId">The Google Ads ad group Id.</param>
        /// <param name="keywordId">The Google Ads keyword Id.</param>
        public void Run(GoogleAdsClient client, long customerId, long adGroupId, long keywordId)
        {
            // Get the CampaignCriterionService.
            AdGroupCriterionServiceClient adGroupCriterionService =
                client.GetService(Services.V4.AdGroupCriterionService);

            // Create the keyword for update.
            AdGroupCriterion keyword = new AdGroupCriterion()
            {
                ResourceName = ResourceNames.AdGroupCriterion(customerId, adGroupId, keywordId),
                CriterionId  = keywordId,
                Status       = AdGroupCriterionStatus.Enabled,
                FinalUrls    = { "https://www.example.com" }
            };

            AdGroupCriterionOperation keywordOperation = new AdGroupCriterionOperation()
            {
                Update     = keyword,
                UpdateMask = FieldMasks.AllSetFieldsOf(keyword)
            };

            try
            {
                // Update the keyword.
                MutateAdGroupCriteriaResponse response =
                    adGroupCriterionService.MutateAdGroupCriteria(customerId.ToString(),
                                                                  new AdGroupCriterionOperation[] { keywordOperation });

                // Display the results.
                foreach (MutateAdGroupCriterionResult criterionResult in response.Results)
                {
                    Console.WriteLine($"Keyword with resource name = " +
                                      $"'{criterionResult.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>
        /// Creates a list of MutateOperations that override customer conversion goals.
        /// </summary>
        /// <param name="customerId">The customer's id.</param>
        /// <param name="conversionGoals">A list customer conversion goals.</param>
        /// <returns>A list customer conversion goal operations.</returns>
        private List <MutateOperation> CreateCustomerConversionGoalOperations(
            long customerId,
            List <CustomerConversionGoal> conversionGoals)
        {
            List <MutateOperation> operations =
                new List <MutateOperation>();

            foreach (CustomerConversionGoal conversionGoal in conversionGoals)
            {
                CustomerConversionGoal newConversionGoal = new CustomerConversionGoal()
                {
                    ResourceName = ResourceNames.CustomerConversionGoal(
                        customerId,
                        conversionGoal.Category,
                        conversionGoal.Origin
                        ),
                };

                // Change the biddability for the campaign conversion goal.
                // Set biddability to True for the desired (category, origin).
                // Set biddability to False for all other conversion goals.
                // Note:
                //  1- It is assumed that this Conversion Action
                //     (category=PURCHASE, origin=WEBSITE) exists in this account.
                //  2- More than one goal can be biddable if desired. This example
                //     shows only one.
                newConversionGoal.Biddable =
                    conversionGoal.Category == ConversionActionCategory.Purchase &&
                    conversionGoal.Origin == ConversionOrigin.Website;

                operations.Add(
                    new MutateOperation()
                {
                    CustomerConversionGoalOperation = new CustomerConversionGoalOperation()
                    {
                        Update     = newConversionGoal,
                        UpdateMask = FieldMasks.AllSetFieldsOf(newConversionGoal)
                    }
                }
                    );
            }

            return(operations);
        }
        /// <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}'.");
            }
        }
        /// <summary>
        /// Updates attribute value of the feed item. In order to update a FeedItemAttributeValue
        /// you must update the FeedItem.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="feedId">ID of the feed containing the feed item to be updated.</param>
        /// <param name="feedItemId">ID of the feed item to be updated.</param>
        /// <param name="flightPlaceholderFieldName">the placeholder type for the attribute to be
        /// updated.</param>
        /// <param name="attributeValue">String value with which to update the
        /// FeedAttributeValue.</param>
        private void UpdateFeedItem(GoogleAdsClient client, long customerId, long feedId,
                                    long feedItemId, string flightPlaceholderFieldName, string attributeValue)
        {
            // Get the FeedItemServiceClient.
            FeedItemServiceClient feedItemService =
                client.GetService(Services.V5.FeedItemService);

            // Gets the feed resource name.
            string feedResourceName = ResourceNames.Feed(customerId, feedId);

            // Gets a map of the placeholder values and feed attributes.
            Dictionary <FlightPlaceholderField, FeedAttribute> feedAttributes =
                GetFeed(client, customerId, feedResourceName);

            // Gets the ID of the attribute to update. This is needed to specify which
            // FeedItemAttributeValue will be updated in the given FeedItem.
            FlightPlaceholderField placeholderField = (FlightPlaceholderField)Enum.Parse(
                typeof(FlightPlaceholderField), flightPlaceholderFieldName);
            long attributeId = feedAttributes[placeholderField].Id.Value;

            // Gets the feed item resource name.
            string feedItemResourceName = ResourceNames.FeedItem(customerId, feedId, feedItemId);
            // Retrieves the feed item and its associated attributes based on its resource name.
            FeedItem feedItem = GetFeedItem(client, customerId, feedItemResourceName);
            // Creates the updated FeedItemAttributeValue.
            FeedItemAttributeValue feedItemAttributeValue = new FeedItemAttributeValue()
            {
                FeedAttributeId = attributeId,
                StringValue     = attributeValue
            };

            // Creates a new FeedItem from the existing FeedItem. Any FeedItemAttributeValues that
            // are not included in the updated FeedItem will be removed from the FeedItem, which is
            // why you must create the FeedItem from the existing FeedItem and set the field(s)
            // that will be updated.
            int attributeIndex = feedItem.AttributeValues
                                 .Select((item, index) => new { item, index })
                                 .Where(itemIndexPair =>
                                        itemIndexPair.item.FeedAttributeId.Value ==
                                        feedItemAttributeValue.FeedAttributeId.Value)
                                 .Select(itemIndexPair => itemIndexPair.index + 1)
                                 .FirstOrDefault() - 1;

            if (attributeIndex == -1)
            {
                throw new ArgumentException("No matching feed attribute found for " +
                                            $"value '{feedItemAttributeValue}'.");
            }

            feedItem.AttributeValues[attributeIndex] = feedItemAttributeValue;

            // Creates the operation.
            FeedItemOperation operation = new FeedItemOperation()
            {
                Update     = feedItem,
                UpdateMask = FieldMasks.AllSetFieldsOf(feedItem)
            };

            // Updates the feed item.
            MutateFeedItemsResponse response =
                feedItemService.MutateFeedItems(customerId.ToString(), new[] { operation });

            foreach (MutateFeedItemResult result in response.Results)
            {
                Console.WriteLine($"Updated feed item with resource name '{result.ResourceName}'.");
            }
        }
示例#25
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>
        // [START get_change_details]
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V10.GoogleAdsService);

            // Construct a query to find details for recent changes in your account.
            // The LIMIT clause is required for the change_event resource.
            // The maximum size is 10000, but a low limit was set here for demonstrative
            // purposes.
            // The WHERE clause on change_date_time is also required. It must specify a
            // window of at most 30 days within the past 30 days.

            string startDate   = DateTime.Today.Subtract(TimeSpan.FromDays(25)).ToString("yyyyMMdd");
            string endDate     = DateTime.Today.Add(TimeSpan.FromDays(1)).ToString("yyyyMMdd");
            string searchQuery = $@"
                SELECT
                    change_event.resource_name,
                    change_event.change_date_time,
                    change_event.change_resource_name,
                    change_event.user_email,
                    change_event.client_type,
                    change_event.change_resource_type,
                    change_event.old_resource,
                    change_event.new_resource,
                    change_event.resource_change_operation,
                    change_event.changed_fields
                FROM
                    change_event
                WHERE
                    change_event.change_date_time >= '{startDate}' AND
                    change_event.change_date_time <= '{endDate}'
                ORDER BY
                    change_event.change_date_time DESC
                LIMIT 5";

            try
            {
                // Issue a search request.
                googleAdsService.SearchStream(customerId.ToString(), searchQuery,
                                              delegate(SearchGoogleAdsStreamResponse resp)
                {
                    // Display the results.
                    foreach (GoogleAdsRow googleAdsRow in resp.Results)
                    {
                        ChangeEvent changeEvent     = googleAdsRow.ChangeEvent;
                        ChangedResource oldResource = changeEvent.OldResource;
                        ChangedResource newResource = changeEvent.NewResource;

                        bool knownResourceType     = true;
                        IMessage oldResourceEntity = null;
                        IMessage newResourceEntity = null;
                        switch (changeEvent.ChangeResourceType)
                        {
                        case ChangeEventResourceType.Ad:
                            oldResourceEntity = oldResource.Ad;
                            newResourceEntity = newResource.Ad;
                            break;

                        case ChangeEventResourceType.AdGroup:
                            oldResourceEntity = oldResource.AdGroup;
                            newResourceEntity = newResource.AdGroup;
                            break;

                        case ChangeEventResourceType.AdGroupAd:
                            oldResourceEntity = oldResource.AdGroupAd;
                            newResourceEntity = newResource.AdGroupAd;
                            break;

                        case ChangeEventResourceType.AdGroupAsset:
                            oldResourceEntity = oldResource.AdGroupAsset;
                            newResourceEntity = newResource.AdGroupAsset;
                            break;

                        case ChangeEventResourceType.AdGroupBidModifier:
                            oldResourceEntity = oldResource.AdGroupBidModifier;
                            newResourceEntity = newResource.AdGroupBidModifier;
                            break;

                        case ChangeEventResourceType.AdGroupCriterion:
                            oldResourceEntity = oldResource.AdGroupCriterion;
                            newResourceEntity = newResource.AdGroupCriterion;
                            break;

                        case ChangeEventResourceType.AdGroupFeed:
                            oldResourceEntity = oldResource.AdGroupFeed;
                            newResourceEntity = newResource.AdGroupFeed;
                            break;

                        case ChangeEventResourceType.Asset:
                            oldResourceEntity = oldResource.Asset;
                            newResourceEntity = newResource.Asset;
                            break;

                        case ChangeEventResourceType.AssetSet:
                            oldResourceEntity = oldResource.AssetSet;
                            newResourceEntity = newResource.AssetSet;
                            break;

                        case ChangeEventResourceType.AssetSetAsset:
                            oldResourceEntity = oldResource.AssetSetAsset;
                            newResourceEntity = newResource.AssetSetAsset;
                            break;

                        case ChangeEventResourceType.Campaign:
                            oldResourceEntity = oldResource.Campaign;
                            newResourceEntity = newResource.Campaign;
                            break;

                        case ChangeEventResourceType.CampaignAsset:
                            oldResourceEntity = oldResource.CampaignAsset;
                            newResourceEntity = newResource.CampaignAsset;
                            break;

                        case ChangeEventResourceType.CampaignAssetSet:
                            oldResourceEntity = oldResource.CampaignAssetSet;
                            newResourceEntity = newResource.CampaignAssetSet;
                            break;

                        case ChangeEventResourceType.CampaignBudget:
                            oldResourceEntity = oldResource.CampaignBudget;
                            newResourceEntity = newResource.CampaignBudget;
                            break;

                        case ChangeEventResourceType.CampaignCriterion:
                            oldResourceEntity = oldResource.CampaignCriterion;
                            newResourceEntity = newResource.CampaignCriterion;
                            break;

                        case ChangeEventResourceType.CampaignFeed:
                            oldResourceEntity = oldResource.CampaignFeed;
                            newResourceEntity = newResource.CampaignFeed;
                            break;

                        case ChangeEventResourceType.CustomerAsset:
                            oldResourceEntity = oldResource.CustomerAsset;
                            newResourceEntity = newResource.CustomerAsset;
                            break;

                        case ChangeEventResourceType.Feed:
                            oldResourceEntity = oldResource.Feed;
                            newResourceEntity = newResource.Feed;
                            break;

                        case ChangeEventResourceType.FeedItem:
                            oldResourceEntity = oldResource.FeedItem;
                            newResourceEntity = newResource.FeedItem;
                            break;

                        default:
                            knownResourceType = false;
                            break;
                        }

                        if (!knownResourceType)
                        {
                            Console.WriteLine($"Unknown change_resource_type " +
                                              $"'{changeEvent.ChangeResourceType}'.");
                            continue;
                        }

                        Console.WriteLine($"On #{changeEvent.ChangeDateTime}, user " +
                                          $"{changeEvent.UserEmail} used interface {changeEvent.ClientType} " +
                                          $"to perform a(n) '{changeEvent.ResourceChangeOperation}' " +
                                          $"operation on a '{changeEvent.ChangeResourceType}' with " +
                                          $"resource name {changeEvent.ChangeResourceName}.");

                        foreach (string fieldMaskPath in changeEvent.ChangedFields.Paths)
                        {
                            if (changeEvent.ResourceChangeOperation ==
                                ResourceChangeOperation.Create)
                            {
                                object newValue = FieldMasks.GetFieldValue(
                                    fieldMaskPath, newResourceEntity);
                                Console.WriteLine($"\t{fieldMaskPath} set to '{newValue}'.");
                            }
                            else if (changeEvent.ResourceChangeOperation ==
                                     ResourceChangeOperation.Update)
                            {
                                object oldValue = FieldMasks.GetFieldValue(fieldMaskPath,
                                                                           oldResourceEntity);
                                object newValue = FieldMasks.GetFieldValue(fieldMaskPath,
                                                                           newResourceEntity);

                                Console.WriteLine($"\t{fieldMaskPath} changed from " +
                                                  $"'{oldValue}' to '{newValue}'.");
                            }
                        }
                    }
                });
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
示例#26
0
        public void TestGetFieldValue()
        {
            Resource r1 = new Resource()
            {
                Foo = new Foo()
                {
                    Bar = new Bar()
                    {
                        Num = 5,
                    },
                    Num  = 25,
                    Text = "hello world",
                    Bars =
                    {
                        new Bar()
                        {
                            Num = 10
                        }
                    }
                },
                Foos =
                {
                    new Foo()
                    {
                        Num = 42
                    }
                },
                OptFoos = 45,
                Wrapper = "Test wrapper"
            };

            // Object references should be tested using AreSame.
            Assert.AreSame(FieldMasks.GetFieldValue("foo", r1), r1.Foo);
            Assert.AreSame(FieldMasks.GetFieldValue("foo.bar", r1), r1.Foo.Bar);
            Assert.AreSame(FieldMasks.GetFieldValue("foo.bars", r1), r1.Foo.Bars);
            Assert.AreSame(FieldMasks.GetFieldValue("foos", r1), r1.Foos);
            Assert.AreSame(FieldMasks.GetFieldValue("wrapper", r1), r1.Wrapper);

            // Value type should be tested using AreEqual.
            Assert.AreEqual(FieldMasks.GetFieldValue("foo.bar.num", r1), r1.Foo.Bar.Num);
            Assert.AreEqual(FieldMasks.GetFieldValue("foo.num", r1), r1.Foo.Num);
            Assert.AreEqual(FieldMasks.GetFieldValue("foo.text", r1), r1.Foo.Text);
            Assert.AreEqual(FieldMasks.GetFieldValue("opt_foos", r1), r1.OptFoos);

            Resource r2 = new Resource()
            {
                OptFoos = 32
            };

            Assert.Throws <ArgumentException>(delegate() {
                // r2.Foo is null.
                FieldMasks.GetFieldValue("foo.bar", r2);
            });
            Assert.Throws <ArgumentException>(delegate() {
                // r2.Jazz is not a valid field.
                FieldMasks.GetFieldValue("foo.jazz", r2);
            });
            Assert.Throws <ArgumentException>(delegate() {
                // r2.OptFoos.Blah cannot be recursed because OptFoos is a leaf level node.
                FieldMasks.GetFieldValue("foo.opt_foos.blah", r2);
            });
            Assert.Throws <ArgumentException>(delegate() {
                // YOu cannot recurse r2.Foos because it is a repeated field.
                FieldMasks.GetFieldValue("foo.opt_foos.blah", r2);
            });
        }