public void AddTest()
 {
     RequestException target = new RequestException(); // TODO: Initialize to an appropriate value
     Exception ex = new Exception(); // TODO: Initialize to an appropriate value
     target.Add(ex);
     Assert.AreEqual(1, target.Exceptions.Count);
 }
示例#2
0
        public void Handle <TResponse>(Action <TResponse> handler)
            where TResponse : class
        {
            var connector = new RequestHandlerSubscriptionConnector <TResponse>();

            Action <TResponse> responseHandler = message =>
            {
                try
                {
                    handler(message);

                    _request.Complete(message);
                }
                catch (Exception ex)
                {
                    var exception = new RequestException("The response handler threw an exception", ex, message);
                    _request.Fail(exception);
                }
            };

            _handlers.Add(
                x => { return(connector.Connect(x, _requestId, HandlerSelector.ForHandler(responseHandler))); });
        }
示例#3
0
        /// <summary>
        /// Throw request exception asynchronous.
        /// </summary>
        /// <exception cref="RequestException">
        /// Thrown when a Request error condition occurs.
        /// </exception>
        /// <returns>
        /// A <see cref="Task"/> representing the operation.
        /// </returns>
        private static async Task throwRequestExceptionAsync(HttpResponseMessage response)
        {
            var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var error = parseError(response.StatusCode, content);

            RequestException requestException;

            switch (response.StatusCode)
            {
            case HttpStatusCode.BadRequest:
                requestException = new BadRequestException(error.Message, error.Code, error.Reason);
                break;

            case HttpStatusCode.Forbidden:
                requestException = new Exceptions.UnauthorizedAccessException(error.Message, error.Code, error.Reason);
                break;

            case HttpStatusCode.InternalServerError:
                requestException = new InternalServerErrorException(error.Message, error.Code, error.Reason);
                break;

            case HttpStatusCode.NotFound:
                requestException = new ResourceNotFoundException(error.Message, error.Code, error.Reason);
                break;

            case HttpStatusCode.Unauthorized:
                requestException = new AuthenticationFailureException(error.Message, error.Code, error.Reason);
                break;

            default:
                requestException = new RequestException(error.Message, error.Code, error.Reason);
                break;
            }
            throw requestException;
        }
示例#4
0
 /// Implement this virtual method in order to catch every request which did
 /// run into an HTTP error.
 public virtual void OnRequestDidCatch(RequestException exception)
 {
 }
        public void CanDeserializeTypeConversionFailed()
        {
            var ex = new RequestException(System.Net.HttpStatusCode.BadRequest, "[{errorType:'TypeConversionFailed', message:'msg', argument:'arg', value:'val', targetType:'int'}]");

            Assert.That(ex.ErrorObjects().First().GetType().Name, Is.EqualTo("TypeConversionFailed"));
        }
        public void CanDeserializeMissingArgument()
        {
            var ex = new RequestException(System.Net.HttpStatusCode.BadRequest, "[{errorType:'MissingArgument', message:'msg', argument:'arg' }]");

            Assert.That(ex.ErrorObjects().First().GetType().Name, Is.EqualTo("MissingArgument"));
        }
示例#7
0
 public TodoistException(TodoistError error, RequestException requestException)
     : base(requestException.Message, requestException)
 {
     Error = error;
 }
        /// <summary>
        /// Sends and receives data.
        /// </summary>
        /// <param name="request">Data to send.</param>
        /// <returns>Data received.</returns>
        private Response Send(Request request)
        {
            // Hourglass
            System.Windows.Forms.Cursor lCurrentCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

            Response lResult = null;
            if ((this.Connection != null) && (request != null))
            {
                lResult = new Response();

                // Check the info. of Request.
                CheckRequest(request);

                // Data To Send ...
                StringBuilder lSendData = XMLRequestSerializer.SerializeRoot(null as StringBuilder, request);

                // Send & Received Data ...
                StringBuilder lReceivedData = new StringBuilder(this.Connection.Send(lSendData.ToString()));

                // Throw a ResponseException if have error.
                lResult = XMLResponseSerializer.Deserialize(lReceivedData.ToString());

                // Save Ticket ...
                if (lResult.Ticket != null)
                {
                    request.Agent.Ticket = lResult.Ticket;
                }
            }
            else
            {
                // Hourglass
                System.Windows.Forms.Cursor.Current = lCurrentCursor;

                string lMessageError = CultureManager.TranslateString(LanguageConstantKeys.L_ERROR_REQUEST, LanguageConstantValues.L_ERROR_REQUEST);
                RequestException lrequestException = new RequestException(lMessageError);
                lrequestException.Number = 999;
                throw lrequestException;
            }

            // Hourglass
            System.Windows.Forms.Cursor.Current = lCurrentCursor;

            return lResult;
        }
示例#9
0
        private async Task ExecuteOperation(ExecutionContext context)
        {
            var operation = context.Operation;

            if (operation.values != null)
            {
                context.AddValuesIn(ProcessValues(operation.values, context.Values));
            }

            var patternOkay = context.PatternMatcher.IsMatch(context.Path);

            var conditionOkay = true;

            if (!string.IsNullOrEmpty(operation.condition))
            {
                var conditionResult = _jmesPathQuery.Search(operation.condition, context.Values);
                conditionOkay = ConditionBoolean(conditionResult);
            }

            for (var shouldExecute = patternOkay && conditionOkay; shouldExecute; shouldExecute = await EvaluateRepeat(context))
            {
                var message = ConvertToString(ProcessValues(operation.message, context.Values));
                var write   = ConvertToString(ProcessValues(operation.write, context.Values));

                if (!string.IsNullOrEmpty(message))
                {
                    _console.WriteLine();
                    _console.WriteLine($"{new string(' ', context.Indent * 2)}- {message.Color(ConsoleColor.Cyan)}");
                }

                var debugPath = Path.Combine(OutputDirectory.Required(), "logs", $"{++_operationCount:000}-{new string('-', context.Indent * 2)}{new string((message ?? write ?? operation.request ?? operation.template ?? string.Empty).Select(ch => char.IsLetterOrDigit(ch) ? ch : '-').ToArray())}.yaml");
                Directory.CreateDirectory(Path.GetDirectoryName(debugPath));
                using (var writer = _secretTracker.FilterTextWriter(File.CreateText(debugPath)))
                {
                    var logentry = new Dictionary <object, object>
                    {
                        {
                            "operation",
                            new Dictionary <object, object>
                            {
                                { "message", message },
                                { "target", operation.target },
                                { "condition", operation.condition },
                                { "repeat", operation.repeat },
                                { "request", operation.request },
                                { "template", operation.template },
                                { "write", write },
                            }
                        },
                        { "valuesIn", context.ValuesIn },
                        { "valuesOut", context.ValuesOut },
                        { "request", null },
                        { "response", null },
                        { "cumulativeValues", context.Values },
                    };

                    try
                    {
                        // object result = null;
                        object outputContext = context.Values;

                        try
                        {
                            // First special type of operation - executing a request
                            if (!string.IsNullOrWhiteSpace(operation.request))
                            {
                                var request = context.TemplateEngine.Render <WorkflowModel.Request>(
                                    operation.request,
                                    context.Values);

                                logentry["request"] = request;

                                HttpAuthentication auth = null;
                                if (request.auth != null)
                                {
                                    // TODO: remove these defaults
                                    auth = new HttpAuthentication
                                    {
                                        tenant      = request?.auth?.tenant ?? "common",
                                        resourceId  = request?.auth?.resource ?? "499b84ac-1321-427f-aa17-267ca6975798",
                                        clientId    = request?.auth?.client ?? "e8f3cc86-b3b2-4ebb-867c-9c314925b384",
                                        interactive = IsInteractive
                                    };
                                }

                                var client = _clientFactory.Create(auth);

                                var method = new HttpMethod(request.method ?? "GET");
                                if (IsDryRun && method.Method != "GET")
                                {
                                    _console.WriteLine($"Skipping {method.Method.ToString().Color(ConsoleColor.DarkYellow)} {request.url}");
                                }
                                else
                                {
                                    var jsonRequest = new JsonRequest
                                    {
                                        method  = method,
                                        url     = request.url,
                                        headers = request.headers,
                                        body    = request.body,
                                        secret  = request.secret,
                                    };

                                    var jsonResponse = await client.SendAsync(jsonRequest);

                                    var response = new WorkflowModel.Response
                                    {
                                        status  = (int)jsonResponse.status,
                                        headers = jsonResponse.headers,
                                        body    = jsonResponse.body,
                                    };

                                    logentry["response"] = response;

                                    outputContext = MergeUtils.Merge(new Dictionary <object, object> {
                                        { "result", response }
                                    }, outputContext);

                                    if (response.status >= 400)
                                    {
                                        var error = new RequestException($"Request failed with status code {jsonResponse.status}")
                                        {
                                            Request  = request,
                                            Response = response,
                                        };
                                        throw error;
                                    }
                                }
                            }

                            // Second special type of operation - rendering a template
                            if (!string.IsNullOrWhiteSpace(operation.template))
                            {
                                if (!string.IsNullOrEmpty(write))
                                {
                                    var targetPath = Path.Combine(OutputDirectory.Required(), write);

                                    Directory.CreateDirectory(Path.GetDirectoryName(targetPath));

                                    using (var targetWriter = File.CreateText(targetPath))
                                    {
                                        if (!string.IsNullOrWhiteSpace(operation.template))
                                        {
                                            context.TemplateEngine.Render(operation.template, context.Values, targetWriter);
                                        }
                                    }
                                }

                                if (operation.output != null)
                                {
                                    var templateResult = context.TemplateEngine.Render <object>(operation.template, context.Values);

                                    outputContext = MergeUtils.Merge(new Dictionary <object, object> {
                                        { "result", templateResult }
                                    }, outputContext);
                                }
                            }

                            // Third special type of operation - nested operations
                            if (operation.operations != null)
                            {
                                var nestedResult = await ExecuteOperations(context, operation.operations);

                                if (operation.output == null)
                                {
                                    // if output is unstated, and there are nested operations with output - those flows back as effective output
                                    context.AddValuesOut(nestedResult);
                                }
                                else
                                {
                                    // if output is stated, nested operations with output are visible to output queries
                                    outputContext = MergeUtils.Merge(nestedResult, context.Values) ?? context.Values;
                                }
                            }

                            // If output is specifically stated - use it to query
                            if (operation.output != null)
                            {
                                context.AddValuesOut(ProcessValues(operation.output, outputContext));
                            }

                            if (operation.@throw != null)
                            {
                                var throwMessage = ConvertToString(ProcessValues([email protected], context.Values));
                                throwMessage = string.IsNullOrEmpty(throwMessage) ? message : throwMessage;

                                var throwDetails = ProcessValues([email protected], context.Values);

                                _console.WriteLine(throwMessage.Color(ConsoleColor.DarkRed));
                                if (throwDetails != null)
                                {
                                    _console.WriteLine(_serializers.YamlSerializer.Serialize(throwDetails).Color(ConsoleColor.DarkRed));
                                }

                                throw new OperationException(string.IsNullOrEmpty(throwMessage) ? message : throwMessage)
                                      {
                                          Details = throwDetails
                                      };
                            }
                        }
                        catch (Exception ex) when(CatchCondition(ex, operation.@catch, outputContext))
                        {
                            if ([email protected] != null)
                            {
                                var mergedContext = MergeError(ex, outputContext);
                                var catchDetails  = ProcessValues([email protected], mergedContext);
                                context.AddValuesOut(catchDetails);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        logentry["error"] = new Dictionary <object, object>
                        {
                            { "type", ex.GetType().FullName },
                            { "message", ex.Message },
                            { "stack", ex.StackTrace },
                        };

                        throw;
                    }
                    finally
                    {
                        logentry["valuesIn"]         = context?.ValuesIn;
                        logentry["valuesOut"]        = context?.ValuesOut;
                        logentry["cumulativeValues"] = context?.Values;
                        _serializers.YamlSerializer.Serialize(writer, logentry);
                    }
                }
            }
        }
示例#10
0
 public void RequestExceptionConstructorTest()
 {
     RequestException target = new RequestException();
     Assert.AreEqual(0, target.Exceptions.Count);
 }
示例#11
0
 void ProcessResponse(RequestException requestException, ResponseHelper responseHelper)
 {
     request._EventDelegate(request._Type, requestException == null ? ServiceEvent.COMPLETE : ServiceEvent.ERROR, 1, Deserialize <DATA_TYPE>(responseHelper.Text), request._UserData);
 }
        public void CheckPlatinumBrowserRequestExceptionType()
        {
            RequestException ex = new RequestException("PageNotInitied", new RestResponse());

            Assert.IsInstanceOf <Exception>(ex);
        }
示例#13
0
 public void OnException(RequestException arg)
 {
 }
示例#14
0
 /// <summary>
 ///     Invokes the <see cref="RequestException" /> event
 /// </summary>
 /// <param name="e">The exception that occurred during the request</param>
 protected virtual void OnRequestException(Exception e)
 {
     RequestException?.Invoke(this, new EndpointExceptionEventArgs(e));
 }