示例#1
0
        public void TestAsyncUnaryCallWithException()
        {
            GoogleAdsConfig config  = new GoogleAdsConfig();
            LoggingHandler  handler = new LoggingHandler(config);

            handler.WriteLogs = delegate(LogEntry logEntry)
            {
                Assert.AreEqual(config.ServerUrl, logEntry.Host);
                Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method);
                CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders);
                CompareMetadata(TEST_RESPONSE_METADATA, logEntry.ResponseHeaders);
                Assert.AreSame(TEST_REQUEST, logEntry.Request);

                // Response is null if there's an exception.
                Assert.IsNull(logEntry.Response);

                Assert.AreEqual(TEST_CUSTOMER_ID, logEntry.CustomerId);
                Assert.True(logEntry.IsFailure);
                GoogleAdsException googleAdsException = logEntry.Exception as GoogleAdsException;
                Assert.NotNull(googleAdsException);

                Assert.AreEqual(TEST_REQUEST_ID, googleAdsException.RequestId);

                Assert.NotNull(googleAdsException.Failure);
                Assert.AreEqual(1, googleAdsException.Failure.Errors.Count);
                Assert.NotNull(googleAdsException.Failure.Errors[0].ErrorCode);
                Assert.NotNull(googleAdsException.Failure.Errors[0].ErrorCode.DistinctError);
            };

            ClientInterceptorContext <HelloRequest, HelloResponse> context =
                GetClientInterceptorContext();
            AsyncUnaryCall <HelloResponse> call = ContinuationWithException(TEST_REQUEST, context);

            handler.HandleAsyncUnaryLogging(TEST_REQUEST, context, call.ResponseAsync, call);
        }
        /// <summary>
        /// Collects all ignorable policy topics that will be sent for exemption request later.
        /// </summary>
        /// <param name="ex">The API exception from a previous call to add ad group ads.</param>
        /// <returns>The ignorable policy topics</returns>
        private static string[] FetchIgnorablePolicyTopics(GoogleAdsException ex)
        {
            List <string> ignorablePolicyTopics = new List <string>();;

            Console.WriteLine("Google Ads failure details:");
            foreach (GoogleAdsError error in ex.Failure.Errors)
            {
                if (error.ErrorCode.ErrorCodeCase != ErrorCode.ErrorCodeOneofCase.PolicyFindingError)
                {
                    throw ex;
                }
                if (error.Details != null && error.Details.PolicyFindingDetails != null)
                {
                    PolicyFindingDetails details = error.Details.PolicyFindingDetails;
                    Console.WriteLine($"- Policy finding details:");

                    foreach (PolicyTopicEntry entry in details.PolicyTopicEntries)
                    {
                        ignorablePolicyTopics.Add(entry.Topic);
                        Console.WriteLine($"  - Policy topic name: '{entry.Topic}");
                        Console.WriteLine($"  - Policy topic entry type: '{entry.Type}");
                        // For the sake of brevity, we exclude printing "policy topic evidences"
                        // and "policy topic constraints" here. You can fetch those data by
                        // calling:
                        // - entry.Evidences
                        // - entry.Constraints
                    }
                }
            }
            return(ignorablePolicyTopics.ToArray());
        }
示例#3
0
        public void TestAsyncUnaryCallWithException()
        {
            ClientInterceptorContext <HelloRequest, HelloResponse> context =
                GetClientInterceptorContext();

            this.OnLogEventAvailable += delegate(object sender, LogEntry logEntry)
            {
                Assert.AreEqual(this.Config.ServerUrl, logEntry.Host);
                Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method);
                Assert.AreSame(TEST_REQUEST_METADATA, logEntry.RequestHeaders);
                Assert.AreSame(TEST_RESPONSE_METADATA, logEntry.ResponseHeaders);
                Assert.AreSame(TEST_REQUEST, logEntry.Request);

                // Response is null if there's an exception.
                Assert.IsNull(logEntry.Response);

                Assert.AreEqual(TEST_CUSTOMER_ID, logEntry.CustomerId);
                Assert.True(logEntry.IsFailure);
                GoogleAdsException googleAdsException = logEntry.Exception as GoogleAdsException;
                Assert.NotNull(googleAdsException);

                Assert.AreEqual(TEST_REQUEST_ID, googleAdsException.RequestId);

                Assert.NotNull(googleAdsException.Failure);
                Assert.AreEqual(1, googleAdsException.Failure.Errors.Count);
                Assert.NotNull(googleAdsException.Failure.Errors[0].ErrorCode);
                Assert.NotNull(googleAdsException.Failure.Errors[0].ErrorCode.DistinctError);
            };
            this.AsyncUnaryCall(TEST_REQUEST, context, ContinuationWithException);
            this.OnLogEventAvailable = null;
        }
示例#4
0
        public virtual SearchStreamStream SearchStream(
            string customerId,
            string query,
            Action <SearchGoogleAdsStreamResponse> responseCallback,
            SummaryRowSetting summaryRowSetting = SummaryRowSetting.NoSummaryRow,
            CallSettings callSettings           = null)
        {
            try
            {
                Task <SearchStreamStream> t = SearchStreamAsync(customerId, query, responseCallback,
                                                                summaryRowSetting, callSettings);
                t.Wait();
                return(t.Result);
            }
            catch (AggregateException ae)
            {
                GoogleAdsException gae = GoogleAdsException.FromTaskException(ae);

                if (gae != null)
                {
                    throw gae;
                }
                throw;
            }
        }
示例#5
0
        /// <summary>
        /// Gets the Google Ads exception.
        /// </summary>
        /// <param name="e">The aggregate exception from the task.</param>
        /// <returns>The deserialized exception, or null if the exception cannot be deserialized.
        /// </returns>
        private static GoogleAdsException GetGoogleAdsException(AggregateException e)
        {
            RpcException rpcException = e?.InnerExceptions?.FirstOrDefault(
                delegate(Exception innerException)
            {
                return(innerException is RpcException);
            }
                ) as RpcException;

            return(rpcException == null ? null : GoogleAdsException.Create(rpcException));
        }
        /// <summary>
        /// Initiates one asynchronous report download.
        /// </summary>
        /// <param name="googleAdsService">The Google Ads service client.</param>
        /// <param name="customerId">The customer ID from which data is requested.</param>
        /// <param name="queryKey">The name of the query to be downloaded.</param>
        /// <param name="queryValue">The query for the download request.</param>
        /// <param name="responses">Collection of all successful report downloads.</param>
        /// <returns>The asynchronous operation.</returns>
        /// <exception cref="GoogleAdsException">Thrown if errors encountered in the execution of
        ///     the request.</exception>
        private Task <bool> DownloadReportAsync(
            GoogleAdsServiceClient googleAdsService, long customerId, string queryKey,
            string queryValue, ConcurrentBag <ReportDownload> responses)
        {
            try
            {
                // Issue an asynchronous download request.
                googleAdsService.SearchStream(
                    customerId.ToString(), queryValue,
                    delegate(SearchGoogleAdsStreamResponse resp)
                {
                    // Store the results.
                    responses.Add(new ReportDownload()
                    {
                        CustomerId = customerId,
                        QueryKey   = queryKey,
                        Response   = resp
                    });
                }
                    );
                return(Task.FromResult(true));
            }
            catch (AggregateException ae)
            {
                Console.WriteLine($"Download failed for {queryKey} and CID {customerId}!");

                GoogleAdsException gae = GoogleAdsException.FromTaskException(ae);

                var download = new ReportDownload()
                {
                    CustomerId = customerId,
                    QueryKey   = queryKey,
                    Exception  = gae
                };
                if (gae != null)
                {
                    Console.WriteLine($"Message: {gae.Message}");
                    Console.WriteLine($"Failure: {gae.Failure}");
                    Console.WriteLine($"Request ID: {gae.RequestId}");
                    download.Exception = gae;
                }
                else
                {
                    download.Exception = ae;
                }

                responses.Add(download);
                return(Task.FromResult(false));
            }
        }
        /// <summary>
        /// Collects all policy violation keys that can be exempted for sending a exemption
        /// request later.
        /// </summary>
        /// <param name="ex">The Google Ads exception.</param>
        /// <returns>The exemptible policy violation keys.</returns>
        private static PolicyViolationKey[] FetchExemptPolicyViolationKeys(GoogleAdsException ex)
        {
            bool isFullyExemptable = true;
            List <PolicyViolationKey> exemptPolicyViolationKeys = new List <PolicyViolationKey>();

            Console.WriteLine("Google Ads failure details:");
            foreach (GoogleAdsError error in ex.Failure.Errors)
            {
                if (error.ErrorCode.ErrorCodeCase !=
                    ErrorCode.ErrorCodeOneofCase.PolicyViolationError)
                {
                    Console.WriteLine("No exemption request is sent because there are other " +
                                      "non-policy related errors thrown.");
                    throw ex;
                }
                if (error.Details != null && error.Details.PolicyViolationDetails != null)
                {
                    PolicyViolationDetails details = error.Details.PolicyViolationDetails;
                    Console.WriteLine($"- Policy violation details:");

                    Console.WriteLine(" - Policy violation details:");
                    Console.WriteLine($"   - External policy name: '{details.ExternalPolicyName}'");
                    Console.WriteLine($"   - External policy description: " +
                                      $"'{details.ExternalPolicyDescription}'");
                    Console.WriteLine($"   - Is exemptable: '{details.IsExemptible}'");

                    if (details.IsExemptible && details.Key != null)
                    {
                        PolicyViolationKey key = details.Key;
                        Console.WriteLine($"   - Policy violation key:");
                        Console.WriteLine($"     - Name: {key.PolicyName}");
                        Console.WriteLine($"     - Violating Text: {key.ViolatingText}");
                        exemptPolicyViolationKeys.Add(key);
                    }
                    else
                    {
                        isFullyExemptable = false;
                    }
                }
            }

            if (!isFullyExemptable)
            {
                Console.WriteLine("No exemption request is sent because your keyword " +
                                  "contained some non-exemptible policy violations.");
                throw ex;
            }
            return(exemptPolicyViolationKeys.ToArray());
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="LogEntryTests"/> class.
        /// </summary>
        public LogEntryTests()
        {
            // Initialize request metadata.
            TEST_REQUEST_METADATA = new Metadata();
            TEST_REQUEST_METADATA.Add(MetadataKeyNames.DeveloperToken, TEST_DEVELOPER_TOKEN);
            TEST_REQUEST_METADATA.Add(TEST_KEY1, TEST_VALUE1);

            // Initialize response metadata.
            TEST_RESPONSE_METADATA = new Metadata();
            TEST_RESPONSE_METADATA.Add(MetadataKeyNames.RequestId, TEST_REQUEST_ID);
            TEST_RESPONSE_METADATA.Add(TEST_KEY2, TEST_VALUE2);

            // Create an exception for testing purposes.

            TEST_EXCEPTION = TestUtils.CreateException(TEST_ERROR_MESSAGE, TEST_ERROR_TRIGGER,
                                                       TEST_REQUEST_ID);
        }
示例#9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LogEntryTests"/> class.
        /// </summary>
        public LogEntryTests()
        {
            // Initialize request metadata.
            TEST_REQUEST_METADATA = new Metadata();
            TEST_REQUEST_METADATA.Add(GoogleAdsConfig.DEVELOPER_TOKEN_KEYNAME,
                                      TEST_DEVELOPER_TOKEN);
            TEST_REQUEST_METADATA.Add(TEST_KEY1, TEST_VALUE1);

            // Initialize response metadata.
            TEST_RESPONSE_METADATA = new Metadata();
            TEST_RESPONSE_METADATA.Add(GoogleAdsException.REQUEST_ID_KEY, TEST_REQUEST_ID);
            TEST_RESPONSE_METADATA.Add(TEST_KEY2, TEST_VALUE2);

            // Create an exception for testing purposes.

            TEST_EXCEPTION = TestUtils.CreateException(TEST_ERROR_MESSAGE, TEST_ERROR_TRIGGER,
                                                       TEST_RESPONSE_METADATA);
        }
        /// <summary>
        /// Runs a streaming search query and returns all rows that matches the query.
        /// </summary>
        /// <param name="request">The search request.</param>
        /// <param name="responseCallback">The response callback, which will be called
        /// for each <see cref="SearchGoogleAdsStreamResponse"/> in the response stream.</param>
        /// <param name="callSettings">The call settings to customize this API call.</param>
        /// <returns>The <see cref="SearchStreamStream"/> object for further processing.</returns>
        /// <remarks>This method reads the response stream and invokes the callback for each
        /// <see cref="SearchGoogleAdsStreamResponse"/> object in the response, you cannot
        /// iterate further on the <see cref="SearchStreamStream"/> object to obtain results. You
        /// can however perform additional tasks like retrieving the trailing metadata. If you do
        /// not care about this additional information, it is fine to ignore the return value
        /// of this method.</remarks>
        public virtual SearchStreamStream SearchStream(SearchGoogleAdsStreamRequest request,
                                                       Action <SearchGoogleAdsStreamResponse> responseCallback,
                                                       CallSettings callSettings = null)
        {
            try
            {
                Task <SearchStreamStream> t = SearchStreamAsync(request, responseCallback,
                                                                callSettings);
                // Since we call Task.Run() in SearchStreamAsync, it is safe to call
                // t.Result here without causing a deadlock. Also, no need to call t.Wait(),
                // because t.Result is blocking in nature.
                return(t.Result);
            }
            catch (AggregateException ae)
            {
                GoogleAdsException gae = GoogleAdsException.FromTaskException(ae);

                if (gae != null)
                {
                    throw gae;
                }
                throw;
            }
        }
示例#11
0
 /// <summary>
 /// Creates an <see cref="GoogleAdsException"/> for testing purposes.
 /// </summary>
 internal static GoogleAdsException CreateException(string errorMessage,
                                                    string errorTrigger, string requestId)
 {
     return(GoogleAdsException.Create(CreateRpcException(
                                          errorMessage, errorTrigger, requestId)));
 }
示例#12
0
 /// <summary>
 /// Creates an <see cref="GoogleAdsException"/> for testing purposes.
 /// </summary>
 internal static GoogleAdsException CreateException(string errorMessage,
                                                    string errorTrigger, Metadata responseMetadata)
 {
     return(GoogleAdsException.Create(CreateRpcException(errorMessage, errorTrigger,
                                                         responseMetadata)));
 }