예제 #1
0
        public void TestGetErrorsByOperationIndexNoLocation()
        {
            GoogleAdsFailure failure = new GoogleAdsFailure();

            failure.Errors.Add(new GoogleAdsError());
            Assert.AreEqual(failure.GetErrorsByOperationIndex(0).ToList().Count, 0);
        }
예제 #2
0
        public void TestGetErrorsByOperationIndexNoOperationIndex()
        {
            GoogleAdsFailure failure = new GoogleAdsFailure();

            failure.Errors.AddRange(new GoogleAdsError[] { OPERATIONS_NAME });
            Assert.AreEqual(failure.GetErrorsByOperationIndex(0).ToList().Count, 0);
        }
예제 #3
0
        /// <summary>
        /// Creates an <see cref="RpcException"/> for testing purposes.
        /// </summary>
        internal static RpcException CreateRpcException(string errorMessage,
                                                        string errorTrigger, Metadata responseMetadata)
        {
            GoogleAdsFailure failure = new GoogleAdsFailure();

            failure.Errors.Add(new GoogleAdsError()
            {
                ErrorCode = new ErrorCode()
                {
                    DistinctError = DistinctErrorEnum.Types.DistinctError.DuplicateElement
                },
                Location = new ErrorLocation()
                {
                    OperationIndex = 1,
                },
                Message = errorMessage,
                Trigger = new V0.Common.Value()
                {
                    StringValue = errorTrigger
                }
            });

            using (MemoryStream memoryStream = new MemoryStream())
            {
                failure.WriteTo(memoryStream);
                // TODO(Anash): Uncomment once Grpc allows periods in metadata key names.
                // responseMetadata.Add(GoogleAdsException.FAILURE_KEY,
                //     memoryStream.ToArray());
            }

            return(new RpcException(Status.DefaultSuccess, responseMetadata));
        }
예제 #4
0
        /// <summary>
        /// Creates an <see cref="RpcException"/> for testing purposes.
        /// </summary>
        internal static RpcException CreateRpcException(string errorMessage, string errorTrigger,
                                                        string requestId)
        {
            GoogleAdsFailure failure = new GoogleAdsFailure();

            failure.Errors.Add(new GoogleAdsError()
            {
                ErrorCode = new ErrorCode()
                {
                    DistinctError = DistinctErrorEnum.Types.DistinctError.DuplicateElement
                },
                Message = errorMessage,
                Trigger = new Value()
                {
                    StringValue = errorTrigger
                }
            });

            Metadata metadata = new Metadata();

            using (MemoryStream memoryStream = new MemoryStream())
            {
                failure.WriteTo(memoryStream);
                metadata.Add(GoogleAdsException.FAILURE_KEY,
                             memoryStream.ToArray());
                metadata.Add(GoogleAdsException.REQUEST_ID_KEY,
                             requestId);
            }

            return(new RpcException(Status.DefaultSuccess, metadata));
        }
        /// <summary>
        /// Adds operations to a job for a set of sample transactions.
        /// </summary>
        /// <param name="offlineUserDataJobServiceClient">The offline user data job service
        /// client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="offlineUserDataJobResourceName">The resource name of the job to which to
        /// add transactions.</param>
        /// <param name="conversionActionId">The ID of a store sales conversion action.</param>
        /// <param name="customKey">The custom key, or null if not uploading data with custom key
        /// and value.</param>
        /// <param name="itemId">A unique identifier of a product, or null if not uploading with
        /// item attributes.</param>
        /// <param name="merchantCenterAccountId">A Merchant Center Account ID, or null if not
        /// uploading with item attributes.</param>
        /// <param name="countryCode">A two-letter country code, or null if not uploading with
        /// item attributes.</param>
        /// <param name="languageCode">A two-letter language code, or null if not uploading with
        /// item attributes.</param>
        /// <param name="quantity">The number of items sold, or null if not uploading with
        /// item attributes.</param>
        private void AddTransactionsToOfflineUserDataJob(
            OfflineUserDataJobServiceClient offlineUserDataJobServiceClient, long customerId,
            string offlineUserDataJobResourceName, long conversionActionId, string customKey,
            string itemId, long?merchantCenterAccountId, string countryCode, string languageCode,
            long quantity)
        {
            // Constructions an operation for each transaction.
            List <OfflineUserDataJobOperation> userDataJobOperations =
                BuildOfflineUserDataJobOperations(customerId, conversionActionId, customKey, itemId,
                                                  merchantCenterAccountId, countryCode, languageCode, quantity);

            // [START enable_warnings_1]
            // Constructs a request with partial failure enabled to add the operations to the
            // offline user data job, and enable_warnings set to true to retrieve warnings.
            AddOfflineUserDataJobOperationsRequest request =
                new AddOfflineUserDataJobOperationsRequest()
            {
                EnablePartialFailure = true,
                ResourceName         = offlineUserDataJobResourceName,
                Operations           = { userDataJobOperations },
                EnableWarnings       = true,
            };

            AddOfflineUserDataJobOperationsResponse response = offlineUserDataJobServiceClient
                                                               .AddOfflineUserDataJobOperations(request);

            // [END enable_warnings_1]

            // Prints the status message if any partial failure error is returned.
            // NOTE: The details of each partial failure error are not printed here, you can refer
            // to the example HandlePartialFailure.cs to learn more.
            if (response.PartialFailureError != null)
            {
                Console.WriteLine($"Encountered {response.PartialFailureError.Details.Count} " +
                                  $"partial failure errors while adding {userDataJobOperations.Count} " +
                                  "operations to the offline user data job: " +
                                  $"'{response.PartialFailureError.Message}'. Only the successfully added " +
                                  "operations will be executed when the job runs.");
            }
            else
            {
                Console.WriteLine($"Successfully added {userDataJobOperations.Count} operations " +
                                  "to the offline user data job.");
            }

            // [START enable_warnings_2]
            // Prints the number of warnings if any warnings are returned. You can access
            // details of each warning using the same approach you'd use for partial failure
            // errors.
            if (request.EnableWarnings && response.Warnings != null)
            {
                // Extracts the warnings from the response.
                GoogleAdsFailure warnings = response.Warnings;
                Console.WriteLine($"{warnings.Errors.Count} warning(s) occurred");
            }
            // [END enable_warnings_2]
        }
예제 #6
0
        public void TestGetErrorsByOperationIndexWithErrors()
        {
            GoogleAdsFailure failure = new GoogleAdsFailure();

            failure.Errors.Add(OPERATIONS_2_NAME);

            // There are no errors for index = 0.
            Assert.AreEqual(failure.GetErrorsByOperationIndex(0).ToList().Count, 0);

            // There is one error for index = 2.
            Assert.AreEqual(failure.GetErrorsByOperationIndex(2).ToList().Count, 1);
        }
예제 #7
0
        public void TestPartialFailureDeserialization()
        {
            GoogleAdsFailure failure = new GoogleAdsFailure();

            failure.Errors.Add(OPERATIONS_2_NAME);
            MutateAdGroupsResponse failedResponse = new MutateAdGroupsResponse()
            {
                PartialFailureError = GetStatus(failure)
            };

            Assert.True(failedResponse.PartialFailure.Equals(failure));
        }
예제 #8
0
        public void TestGetErrorsByOperationIndexWhenNoErrors()
        {
            GoogleAdsFailure failure = new GoogleAdsFailure();

            Assert.AreEqual(failure.GetErrorsByOperationIndex(0).ToList().Count, 0);
        }
예제 #9
0
 /// <summary>
 /// Wraps a <see cref="GoogleAdsFailure"/> in an Rpc.Status object.
 /// </summary>
 /// <param name="failure">The failure.</param>
 /// <returns>The wrapped Rpc.Status.</returns>
 private static Rpc.Status GetStatus(GoogleAdsFailure failure)
 {
     Rpc.Status status = new Rpc.Status();
     status.Details.Add(Any.Pack(failure));
     return(status);
 }
예제 #10
0
        /// <summary>
        /// Creates and executes an asynchronous job to add users to the Customer Match user list.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which calls are made.
        /// </param>
        /// <param name="userListResourceName">the resource name of the Customer Match user list
        /// to add users to</param>
        private static void AddUsersToCustomerMatchUserList(GoogleAdsClient client,
                                                            long customerId, string userListResourceName)
        {
            // Get the OfflineUserDataJobService.
            OfflineUserDataJobServiceClient service = client.GetService(
                Services.V4.OfflineUserDataJobService);

            // Creates a new offline user data job.
            OfflineUserDataJob offlineUserDataJob = new OfflineUserDataJob()
            {
                Type = OfflineUserDataJobType.CustomerMatchUserList,
                CustomerMatchUserListMetadata = new CustomerMatchUserListMetadata()
                {
                    UserList = userListResourceName
                }
            };

            // Issues a request to create the offline user data job.
            CreateOfflineUserDataJobResponse response1 = service.CreateOfflineUserDataJob(
                customerId.ToString(), offlineUserDataJob);
            string offlineUserDataJobResourceName = response1.ResourceName;

            Console.WriteLine($"Created an offline user data job with resource name: " +
                              $"'{offlineUserDataJobResourceName}'.");

            AddOfflineUserDataJobOperationsRequest request =
                new AddOfflineUserDataJobOperationsRequest()
            {
                ResourceName         = offlineUserDataJobResourceName,
                Operations           = { BuildOfflineUserDataJobOperations() },
                EnablePartialFailure = true,
            };
            // Issues a request to add the operations to the offline user data job.
            AddOfflineUserDataJobOperationsResponse response2 =
                service.AddOfflineUserDataJobOperations(request);

            // Prints the status message if any partial failure error is returned.
            // Note: The details of each partial failure error are not printed here,
            // you can refer to the example HandlePartialFailure.cs to learn more.
            if (response2.PartialFailureError == null)
            {
                // Extracts the partial failure from the response status.
                GoogleAdsFailure partialFailure = response2.PartialFailure;
                Console.WriteLine($"{partialFailure.Errors.Count} partial failure error(s) " +
                                  $"occurred");
            }
            Console.WriteLine("The operations are added to the offline user data job.");

            // Issues an asynchronous request to run the offline user data job for executing
            // all added operations.
            Operation <Empty, Empty> operationResponse =
                service.RunOfflineUserDataJob(offlineUserDataJobResourceName);

            Console.WriteLine("Asynchronous request to execute the added operations started.");;
            Console.WriteLine("Waiting until operation completes.");

            // PollUntilCompleted() implements a default back-off policy for retrying. You can
            // tweak the polling behaviour using a PollSettings as illustrated below.
            operationResponse.PollUntilCompleted(new PollSettings(
                                                     Expiration.FromTimeout(TimeSpan.FromSeconds(MAX_TOTAL_POLL_INTERVAL_SECONDS)),
                                                     TimeSpan.FromSeconds(POLL_FREQUENCY_SECONDS)));

            if (operationResponse.IsCompleted)
            {
                Console.WriteLine($"Offline user data job with resource name " +
                                  $"'{offlineUserDataJobResourceName}' has finished.");
            }
            else
            {
                Console.WriteLine($"Offline user data job with resource name" +
                                  $" '{offlineUserDataJobResourceName}' is pending after " +
                                  $"{MAX_TOTAL_POLL_INTERVAL_SECONDS} seconds.");
            }
        }
예제 #11
0
        /// <summary>
        /// Creates and executes an asynchronous job to add users to the Customer Match user list.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which calls are made.
        /// </param>
        /// <param name="userListResourceName">the resource name of the Customer Match user list
        /// to add users to</param>
        /// <remarks>Resource of the offline user data job.</remarks>
        // [START add_customer_match_user_list]
        private static string AddUsersToCustomerMatchUserList(GoogleAdsClient client,
                                                              long customerId, string userListResourceName)
        {
            // Get the OfflineUserDataJobService.
            OfflineUserDataJobServiceClient service = client.GetService(
                Services.V10.OfflineUserDataJobService);

            // Creates a new offline user data job.
            OfflineUserDataJob offlineUserDataJob = new OfflineUserDataJob()
            {
                Type = OfflineUserDataJobType.CustomerMatchUserList,
                CustomerMatchUserListMetadata = new CustomerMatchUserListMetadata()
                {
                    UserList = userListResourceName
                }
            };

            // Issues a request to create the offline user data job.
            CreateOfflineUserDataJobResponse response1 = service.CreateOfflineUserDataJob(
                customerId.ToString(), offlineUserDataJob);
            string offlineUserDataJobResourceName = response1.ResourceName;

            Console.WriteLine($"Created an offline user data job with resource name: " +
                              $"'{offlineUserDataJobResourceName}'.");

            AddOfflineUserDataJobOperationsRequest request =
                new AddOfflineUserDataJobOperationsRequest()
            {
                ResourceName         = offlineUserDataJobResourceName,
                Operations           = { BuildOfflineUserDataJobOperations() },
                EnablePartialFailure = true,
            };
            // Issues a request to add the operations to the offline user data job.
            AddOfflineUserDataJobOperationsResponse response2 =
                service.AddOfflineUserDataJobOperations(request);

            // Prints the status message if any partial failure error is returned.
            // Note: The details of each partial failure error are not printed here,
            // you can refer to the example HandlePartialFailure.cs to learn more.
            if (response2.PartialFailureError != null)
            {
                // Extracts the partial failure from the response status.
                GoogleAdsFailure partialFailure = response2.PartialFailure;
                Console.WriteLine($"{partialFailure.Errors.Count} partial failure error(s) " +
                                  $"occurred");
            }
            Console.WriteLine("The operations are added to the offline user data job.");

            // Issues an asynchronous request to run the offline user data job for executing
            // all added operations.
            Operation <Empty, OfflineUserDataJobMetadata> operationResponse =
                service.RunOfflineUserDataJob(offlineUserDataJobResourceName);

            Console.WriteLine("Asynchronous request to execute the added operations started.");

            // Since offline user data jobs may take 24 hours or more to complete, it may not be
            // practical to do operationResponse.PollUntilCompleted() to wait for the results.
            // Instead, we save the offlineUserDataJobResourceName and use GoogleAdsService.Search
            // to check for the job status periodically.
            // In case you wish to follow the PollUntilCompleted or PollOnce approach, make sure
            // you keep both operationResponse and service variables alive until the polling
            // completes.

            return(offlineUserDataJobResourceName);
        }
        /// <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 conversion
        /// enhancement is uploaded.</param>
        /// <param name="conversionActionId">ID of the conversion action for which adjustments are
        /// uploaded.</param>
        /// <param name="orderId">The unique order ID (transaction ID) of the conversion.</param>
        /// <param name="conversionDateTime">The date time at which the conversion with the
        /// specified order ID occurred.</param>
        /// <param name="userAgent">The HTTP user agent of the conversion.</param>
        /// <param name="restatementValue">The restatement value.</param>
        /// <param name="restatementCurrencyCode">The currency of the restatement value.</param>
        // [START upload_conversion_enhancement]
        public void Run(GoogleAdsClient client, long customerId, long conversionActionId,
                        string orderId, string conversionDateTime, string userAgent, double?restatementValue,
                        string restatementCurrencyCode)
        {
            // Get the ConversionAdjustmentUploadService.
            ConversionAdjustmentUploadServiceClient conversionAdjustmentUploadService =
                client.GetService(Services.V10.ConversionAdjustmentUploadService);

            // [START create_adjustment]
            // Creates the enhancement adjustment.
            ConversionAdjustment enhancement = new ConversionAdjustment()
            {
                ConversionAction = ResourceNames.ConversionAction(customerId, conversionActionId),
                AdjustmentType   = ConversionAdjustmentType.Enhancement,

                // Enhancements MUST use order ID instead of GCLID date/time pair.
                OrderId = orderId
            };

            // Sets the conversion date and time if provided. Providing this value is optional but
            // recommended.
            if (string.IsNullOrEmpty(conversionDateTime))
            {
                enhancement.GclidDateTimePair = new GclidDateTimePair()
                {
                    ConversionDateTime = conversionDateTime
                };
            }

            // Adds user identifiers, hashing where required.

            // Creates a user identifier using sample values for the user address.
            UserIdentifier addressIdentifier = new UserIdentifier()
            {
                AddressInfo = new OfflineUserAddressInfo()
                {
                    HashedFirstName     = NormalizeAndHash("Joanna"),
                    HashedLastName      = NormalizeAndHash("Smith"),
                    HashedStreetAddress = NormalizeAndHash("1600 Amphitheatre Pkwy"),
                    City        = "Mountain View",
                    State       = "CA",
                    PostalCode  = "94043",
                    CountryCode = "US"
                },
                // Optional: Specifies the user identifier source.
                UserIdentifierSource = UserIdentifierSource.FirstParty
            };

            // Creates a user identifier using the hashed email address.
            UserIdentifier emailIdentifier = new UserIdentifier()
            {
                UserIdentifierSource = UserIdentifierSource.FirstParty,
                // Uses the normalize and hash method specifically for email addresses.
                HashedEmail = NormalizeAndHashEmailAddress("*****@*****.**")
            };

            // Adds the user identifiers to the enhancement adjustment.
            enhancement.UserIdentifiers.AddRange(new[] { addressIdentifier, emailIdentifier });

            // Sets optional fields where a value was provided.
            if (!string.IsNullOrEmpty(userAgent))
            {
                // Sets the user agent. This should match the user agent of the request that
                // sent the original conversion so the conversion and its enhancement are either
                // both attributed as same-device or both attributed as cross-device.
                enhancement.UserAgent = userAgent;
            }

            if (restatementValue != null)
            {
                enhancement.RestatementValue = new RestatementValue()
                {
                    // Sets the new value of the conversion.
                    AdjustedValue = restatementValue.Value
                };
                // Sets the currency of the new value, if provided. Otherwise, the default currency
                // from the conversion action is used, and if that is not set then the account
                // currency is used.
                if (restatementCurrencyCode != null)
                {
                    enhancement.RestatementValue.CurrencyCode = restatementCurrencyCode;
                }
            }
            // [END create_adjustment]
            try
            {
                // Uploads the enhancement adjustment. Partial failure should always be set to true.
                UploadConversionAdjustmentsResponse response =
                    conversionAdjustmentUploadService.UploadConversionAdjustments(
                        new UploadConversionAdjustmentsRequest()
                {
                    CustomerId            = customerId.ToString(),
                    ConversionAdjustments = { enhancement },
                    // Enables partial failure (must be true).
                    PartialFailure = true,
                });

                // Prints the status message if any partial failure error is returned.
                // Note: The details of each partial failure error are not printed here,
                // you can refer to the example HandlePartialFailure.cs to learn more.
                if (response.PartialFailureError != null)
                {
                    // Extracts the partial failure from the response status.
                    GoogleAdsFailure partialFailure = response.PartialFailure;
                    Console.WriteLine($"{partialFailure.Errors.Count} partial failure error(s) " +
                                      $"occurred");
                }
                else
                {
                    // Prints the result.
                    ConversionAdjustmentResult result = response.Results[0];
                    Console.WriteLine($"Uploaded conversion adjustment of " +
                                      $"'{result.ConversionAction}' for order ID '{result.OrderId}'.");
                }
            }
            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 conversions are uploaded.
        /// </param>
        /// <param name="conversionActionId">ID of the conversion action for which conversions are
        /// uploaded.</param>
        /// <param name="emailAddress">The email address.</param>
        /// <param name="conversionDateTime">The date time at which the conversion occurred.</param>
        /// <param name="conversionValue">The conversion value.</param>
        /// <param name="orderId">The unique order ID (transaction ID) of the conversion.</param>
        // [START upload_conversion_with_identifiers]
        public void Run(GoogleAdsClient client, long customerId, long conversionActionId,
                        string emailAddress, string conversionDateTime, double conversionValue,
                        string orderId)
        {
            // Get the ConversionUploadService.
            ConversionUploadServiceClient conversionUploadService =
                client.GetService(Services.V10.ConversionUploadService);

            // [START create_conversion]
            // Gets the conversion action resource name.
            string conversionActionResourceName =
                ResourceNames.ConversionAction(customerId, conversionActionId);

            // Creates a builder for constructing the click conversion.
            ClickConversion clickConversion = new ClickConversion()
            {
                ConversionAction   = conversionActionResourceName,
                ConversionDateTime = conversionDateTime,
                ConversionValue    = conversionValue,
                CurrencyCode       = "USD"
            };

            // Sets the order ID if provided.
            if (!string.IsNullOrEmpty(orderId))
            {
                clickConversion.OrderId = orderId;
            }

            // Optional: Specifies the user identifier source.
            clickConversion.UserIdentifiers.Add(new UserIdentifier()
            {
                // Creates a user identifier using the hashed email address, using the normalize
                // and hash method specifically for email addresses.
                // If using a phone number, use the NormalizeAndHash(String) method instead.
                HashedEmail = NormalizeAndHashEmailAddress(emailAddress),
                // Optional: Specifies the user identifier source.
                UserIdentifierSource = UserIdentifierSource.FirstParty
            });
            // [END create_conversion]

            try
            {
                // Uploads the click conversion. Partial failure should always be set to true.
                UploadClickConversionsResponse response =
                    conversionUploadService.UploadClickConversions(
                        new UploadClickConversionsRequest()
                {
                    CustomerId  = customerId.ToString(),
                    Conversions = { clickConversion },
                    // Enables partial failure (must be true).
                    PartialFailure = true
                });

                if (response.PartialFailureError != null)
                {
                    // Extracts the partial failure from the response status.
                    GoogleAdsFailure partialFailure = response.PartialFailure;
                    Console.WriteLine($"{partialFailure.Errors.Count} partial failure error(s) " +
                                      $"occurred");
                }
                else
                {
                    ClickConversionResult result = response.Results[0];
                    // Prints the result.
                    Console.WriteLine($"Uploaded conversion that occurred at" +
                                      $" {result.ConversionDateTime} to {result.ConversionAction}.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }