Example #1
0
        private async Task <RunWorkflowResult> BeginWorkflow(WorkflowExecutionContext workflowExecutionContext, IActivityBlueprint?activity, CancellationToken cancellationToken)
        {
            if (activity == null)
            {
                activity = _startingActivitiesProvider.GetStartActivities(workflowExecutionContext.WorkflowBlueprint).FirstOrDefault() ?? workflowExecutionContext.WorkflowBlueprint.Activities.First();
            }

            try
            {
                if (!await CanExecuteAsync(workflowExecutionContext, activity, false, cancellationToken))
                {
                    return(new RunWorkflowResult(workflowExecutionContext.WorkflowInstance, activity.Id, null, false));
                }

                var currentStatus = workflowExecutionContext.WorkflowInstance.WorkflowStatus;
                workflowExecutionContext.Begin();
                workflowExecutionContext.ScheduleActivity(activity.Id);
                await _mediator.Publish(new WorkflowStatusChanged(workflowExecutionContext.WorkflowInstance, workflowExecutionContext.WorkflowInstance.WorkflowStatus, currentStatus), cancellationToken);
                await RunCoreAsync(workflowExecutionContext, Execute, cancellationToken);

                return(new RunWorkflowResult(workflowExecutionContext.WorkflowInstance, activity?.Id, null, true));
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "Failed to run workflow {WorkflowInstanceId}", workflowExecutionContext.WorkflowInstance.Id);
                workflowExecutionContext.Fault(e, activity?.Id, null, false);

                if (activity != null)
                {
                    workflowExecutionContext.AddEntry(activity, "Faulted", null, SimpleException.FromException(e));
                }

                return(new RunWorkflowResult(workflowExecutionContext.WorkflowInstance, activity?.Id, e, false));
            }
        }
Example #2
0
        private async Task <RunWorkflowResult> ResumeWorkflowAsync(WorkflowExecutionContext workflowExecutionContext, IActivityBlueprint activity, CancellationToken cancellationToken)
        {
            try
            {
                if (!await CanExecuteAsync(workflowExecutionContext, activity, true, cancellationToken))
                {
                    return(new RunWorkflowResult(workflowExecutionContext.WorkflowInstance, activity.Id, null, false));
                }

                var blockingActivities = workflowExecutionContext.WorkflowInstance.BlockingActivities.Where(x => x.ActivityId == activity.Id).ToList();

                foreach (var blockingActivity in blockingActivities)
                {
                    await workflowExecutionContext.RemoveBlockingActivityAsync(blockingActivity);
                }

                var currentStatus = workflowExecutionContext.WorkflowInstance.WorkflowStatus;
                workflowExecutionContext.Resume();
                workflowExecutionContext.ScheduleActivity(activity.Id);
                await _mediator.Publish(new WorkflowStatusChanged(workflowExecutionContext.WorkflowInstance, workflowExecutionContext.WorkflowInstance.WorkflowStatus, currentStatus), cancellationToken);
                await RunCoreAsync(workflowExecutionContext, Resume, cancellationToken);

                return(new RunWorkflowResult(workflowExecutionContext.WorkflowInstance, activity.Id, null, true));
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "Failed to run workflow {WorkflowInstanceId}", workflowExecutionContext.WorkflowInstance.Id);
                workflowExecutionContext.Fault(e, activity.Id, null, false);
                workflowExecutionContext.AddEntry(activity, "Faulted", null, SimpleException.FromException(e));
                return(new RunWorkflowResult(workflowExecutionContext.WorkflowInstance, activity.Id, e, false));
            }
        }
Example #3
0
        public IronPythonResponse Run(IronPythonScript script)
        {
            object          actual       = null;
            SimpleException ex           = null;
            MemoryStream    outputStream = new MemoryStream();
            StringWriter    outputWriter = new StringWriter();

            MemoryStream errorStream = new MemoryStream();
            StringWriter errorWriter = new StringWriter();

            try
            {
                var engine = Python.CreateEngine();

                if (SynchronizationContext.Current == null)
                {
                    SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
                }

                AddAssemblyReferences(engine);
                engine.Runtime.IO.SetOutput(outputStream, outputWriter);
                engine.Runtime.IO.SetErrorOutput(errorStream, errorWriter);

                var scope = engine.CreateScope();
                scope.SetVariable("scenario", Scenario);

                if (ProjectHandler == null)
                {
                    ProjectHandler = ProjectManager.Instance?.ProjectHandler;
                }
                scope.SetVariable("project_handler", ProjectHandler);
                var sourceCode = engine.CreateScriptSourceFromString(script.Script);
                actual = sourceCode.Execute <object>(scope);
                if (scope.ContainsVariable("result"))
                {
                    actual = scope.GetVariable("result");
                }
            }
            catch (Exception e)
            {
                ex = new SimpleException(e);
            }

            return(new IronPythonResponse()
            {
                Response = AsKnownDataContract(actual),
                StandardError = errorWriter.ToString(),
                StandardOut = outputWriter.ToString(),
                Exception = ex
            });
        }
Example #4
0
        private static async Task RespondWithHtml(HttpContext Context, SimpleException Exception, bool IncludeDetails)
        {
            var exception = Exception;

            if (!IncludeDetails)
            {
                // Remove inner exception that contains details.
                exception.InnerException = null;
            }
            using (var streamWriter = new StreamWriter(Context.Response.Body))
            {
                await streamWriter.WriteLineAsync("<html><body style=\"font-family: Consolas, Courier New, Courier New\"; font-size: 10px;><pre>");

                await streamWriter.WriteLineAsync(exception.GetSummary(true, true));

                await streamWriter.WriteLineAsync("</pre></body></html>");
            }
        }
Example #5
0
        private static async Task RespondWithJson(HttpContext Context, SimpleException Exception, bool IncludeDetails)
        {
            var exception = Exception;

            if (!IncludeDetails)
            {
                // Remove inner exception that contains details.
                exception.InnerException = null;
            }
            var serializableException = JObject.FromObject(exception);

            using (var streamWriter = new StreamWriter(Context.Response.Body))
            {
                using (var jsonWriter = new JsonTextWriter(streamWriter))
                {
                    await serializableException.WriteToAsync(jsonWriter);
                }
            }
        }
Example #6
0
        private async Task <RunWorkflowResult> RunWorkflowAsync(WorkflowExecutionContext workflowExecutionContext, IActivityBlueprint?activity, CancellationToken cancellationToken)
        {
            try
            {
                await RunCoreAsync(workflowExecutionContext, Execute, cancellationToken);

                return(new RunWorkflowResult(workflowExecutionContext.WorkflowInstance, activity?.Id, null, true));
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "Failed to run workflow {WorkflowInstanceId}", workflowExecutionContext.WorkflowInstance.Id);
                workflowExecutionContext.Fault(e, null, null, false);

                if (activity != null)
                {
                    workflowExecutionContext.AddEntry(activity, "Faulted", null, SimpleException.FromException(e));
                }

                return(new RunWorkflowResult(workflowExecutionContext.WorkflowInstance, activity?.Id, e, false));
            }
        }
 protected void AddModelError(SimpleException ex)
 {
     ModelState.AddModelError("", ex.Message);
 }
Example #8
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            var responseType = filterContext.HttpContext.Request.GetPreferedResponseType();

            if (filterContext.HttpContext.Request.IsJqAjaxRequest()
                && filterContext.Exception == null
                && ((filterContext.Result is RedirectToRouteResult) || filterContext.Result is RedirectResult))
            {
                //If we have redirect result, and it is an ajax request:
                // - IF it is json or xml:
                // we'll return 200 OK with the URL in the header, the user can decide if he wants to redirect
                // - if it is an html request, we'll redirect to the new action but send info about the ajax-request with it

                var redir = filterContext.Result as RedirectToRouteResult;
                if (responseType == ResponseType.Json || responseType == ResponseType.Xml) //we'll return a redirect object
                {
                    string url;
                    if (redir != null)
                    {
                        url = UrlHelper.GenerateUrl(
                            redir.RouteName,
                            null /* actionName */,
                            null /* controllerName */,
                            redir.RouteValues,
                            RouteTable.Routes,
                            filterContext.RequestContext,
                            false /* includeImplicitMvcValues */);
                    }
                    else
                    {
                        url = ((RedirectResult) filterContext.Result).Url;
                    }
                    filterContext.RequestContext.HttpContext.Response.AddHeader("Location", url);
                }
                else if (redir != null && !redir.RouteValues.ContainsKey("__mvcajax")) //without these extra params we can't detect an ajax request in FireFox :(
                {
                    redir.RouteValues["__mvcajax"] = "true";
                    redir.RouteValues["resultformat"] = filterContext.RouteData.Values["resultformat"] ??
                                                        filterContext.RouteData.DataTokens["resultformat"];
                    redir.RouteValues["format"] = filterContext.RouteData.Values["format"];
                    return;
                }

            }

            if (filterContext.IsChildAction || filterContext.HttpContext.Request.IsJqAjaxRequest())
            {
                var result = filterContext.Result as ViewResult;
                if (result != null && responseType == ResponseType.Html)
                {
                    var viewResult = filterContext.Result as ViewResult;
                    //prefer partial
                    if (viewResult != null)
                    {
                        filterContext.Result = new PartialViewResult()
                                                   {
                                                       TempData = viewResult.TempData,
                                                       ViewData = viewResult.ViewData,
                                                       ViewName = viewResult.ViewName,
                                                   };
                    }
                }
                else if (responseType == ResponseType.Json || responseType == ResponseType.Xml)
                {
                    ViewDataDictionary data = filterContext.Result is ViewResultBase ? ((ViewResultBase)filterContext.Result).ViewData : filterContext.Controller.ViewData;

                    object model = data;
                    if (filterContext.Exception != null)
                        model = filterContext.Exception;
                    else if (data != null && data.Model != null)
                        model = data.Model;

                    if (model is Exception)
                    {
                        filterContext.Result = null;

                        Exception exc = ((Exception)model).InnerException ?? ((Exception)model);
                        if (exc is HttpException)
                        {
                            filterContext.HttpContext.Response.StatusCode = ((HttpException)exc).GetHttpCode();
                        }
                        else
                        {
                            filterContext.HttpContext.Response.StatusCode = 500;
                        }
                        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                        filterContext.HttpContext.Response.StatusDescription = exc.Message;
                        filterContext.ExceptionHandled = true;
                        model = new SimpleException(exc);
                    }

                    if (responseType == ResponseType.Json)
                    {
                        if (!(filterContext.Result is JsonResult))
                        {
                            var jsonresult =    IoC.Resolver.IsRegistered<JsonResult>() ?
                                                IoC.Resolver.Resolve<JsonResult>() : new JsonResult();
                            jsonresult .Data = model ?? new object();
                            filterContext.Result = jsonresult;
                        }
                    }
                    else if (!(filterContext.Result is XmlResult))
                    {
                        filterContext.Result = new XmlResult(model);
                    }
                }
            }
        }
Example #9
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            var responseType = filterContext.HttpContext.Request.GetPreferedResponseType();

            if (filterContext.HttpContext.Request.IsJqAjaxRequest() &&
                filterContext.Exception == null &&
                ((filterContext.Result is RedirectToRouteResult) || filterContext.Result is RedirectResult))
            {
                //If we have redirect result, and it is an ajax request:
                // - IF it is json or xml:
                // we'll return 200 OK with the URL in the header, the user can decide if he wants to redirect
                // - if it is an html request, we'll redirect to the new action but send info about the ajax-request with it

                var redir = filterContext.Result as RedirectToRouteResult;
                if (responseType == ResponseType.Json || responseType == ResponseType.Xml) //we'll return a redirect object
                {
                    string url;
                    if (redir != null)
                    {
                        url = UrlHelper.GenerateUrl(
                            redir.RouteName,
                            null /* actionName */,
                            null /* controllerName */,
                            redir.RouteValues,
                            RouteTable.Routes,
                            filterContext.RequestContext,
                            false /* includeImplicitMvcValues */);
                    }
                    else
                    {
                        url = ((RedirectResult)filterContext.Result).Url;
                    }
                    filterContext.RequestContext.HttpContext.Response.AddHeader("Location", url);
                }
                else if (redir != null && !redir.RouteValues.ContainsKey("__mvcajax")) //without these extra params we can't detect an ajax request in FireFox :(
                {
                    redir.RouteValues["__mvcajax"]    = "true";
                    redir.RouteValues["resultformat"] = filterContext.RouteData.Values["resultformat"] ??
                                                        filterContext.RouteData.DataTokens["resultformat"];
                    redir.RouteValues["format"] = filterContext.RouteData.Values["format"];
                    return;
                }
            }

            if (filterContext.IsChildAction || filterContext.HttpContext.Request.IsJqAjaxRequest())
            {
                var result = filterContext.Result as ViewResult;
                if (result != null && responseType == ResponseType.Html)
                {
                    var viewResult = filterContext.Result as ViewResult;
                    //prefer partial
                    if (viewResult != null)
                    {
                        filterContext.Result = new PartialViewResult()
                        {
                            TempData = viewResult.TempData,
                            ViewData = viewResult.ViewData,
                            ViewName = viewResult.ViewName,
                        };
                    }
                }
                else if (responseType == ResponseType.Json || responseType == ResponseType.Xml)
                {
                    ViewDataDictionary data = filterContext.Result is ViewResultBase ? ((ViewResultBase)filterContext.Result).ViewData : filterContext.Controller.ViewData;

                    object model = data;
                    if (filterContext.Exception != null)
                    {
                        model = filterContext.Exception;
                    }
                    else if (data != null && data.Model != null)
                    {
                        model = data.Model;
                    }

                    if (model is Exception)
                    {
                        filterContext.Result = null;

                        Exception exc = ((Exception)model).InnerException ?? ((Exception)model);
                        if (exc is HttpException)
                        {
                            filterContext.HttpContext.Response.StatusCode = ((HttpException)exc).GetHttpCode();
                        }
                        else
                        {
                            filterContext.HttpContext.Response.StatusCode = 500;
                        }
                        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                        filterContext.HttpContext.Response.StatusDescription      = exc.Message;
                        filterContext.ExceptionHandled = true;
                        model = new SimpleException(exc);
                    }

                    if (responseType == ResponseType.Json)
                    {
                        if (!(filterContext.Result is JsonResult))
                        {
                            var jsonresult = IoC.Resolver.IsRegistered <JsonResult>() ?
                                             IoC.Resolver.Resolve <JsonResult>() : new JsonResult();
                            jsonresult.Data      = model ?? new object();
                            filterContext.Result = jsonresult;
                        }
                    }
                    else if (!(filterContext.Result is XmlResult))
                    {
                        filterContext.Result = new XmlResult(model);
                    }
                }
            }
        }
Example #10
0
        private static async Task HandleException(HttpContext Context, ExceptionHandlingOptions Options, ILogger Logger)
        {
            if (Options.ResponseHandler != null)
            {
                if (Options.ExceptionResponseFormat.HasValue || Options.IncludeDetails)
                {
                    throw new ArgumentException($"If setting an {nameof(Options.ResponseHandler)}, do not set an {nameof(Options.ExceptionResponseFormat)} or set {nameof(Options.IncludeDetails)} to true.");
                }
            }
            // Get correlation ID.
            var correlationId = Context.GetCorrelationId();
            // Get exception.
            var             exceptionHandlerFeature = Context.Features.Get <IExceptionHandlerFeature>();
            SimpleException innerException;

            if (exceptionHandlerFeature.Error is ApiException apiException)
            {
                // Exception occurred when a Refit proxy called a service method.
                // Deserialize exception from JSON response.
                try
                {
                    var refitException = await apiException.GetContentAsAsync <SimpleException>() ?? new SimpleException(apiException, correlationId, Options.AppName, Options.ProcessName);

                    innerException = new SimpleException(refitException, correlationId, Options.AppName, Options.ProcessName,
                                                         "An exception occurred when a Refit proxy called a service method.");
                }
                catch
                {
                    // Ignore exception when deserializing JSON response.
                    innerException = new SimpleException(apiException, correlationId, Options.AppName, Options.ProcessName);
                    innerException = new SimpleException(innerException, correlationId, Options.AppName, Options.ProcessName,
                                                         $"Failed to deserialize exception from service method response.  Ensure the service's {nameof(ExceptionHandlingMiddleware)} is configured to use {nameof(ExceptionResponseFormat)}.{nameof(ExceptionResponseFormat.Json)}.");
                }
            }
            else
            {
                innerException = new SimpleException(exceptionHandlerFeature.Error, correlationId, Options.AppName, Options.ProcessName);
            }
            // Log exception.
            var exception = new SimpleException(innerException, correlationId, Options.AppName, Options.ProcessName,
                                                $"{Context.Request.Method} with {Context.Request.ContentType ?? "unknown"} content type to {Context.Request.Path} resulted in HTTP status code {Context.Response.StatusCode}.");

            Logger.Log(correlationId, exception);
            Logger.LogMetric(correlationId, Context.Request.Path, "Critical Error", 1);
            // Respond to caller.
            if (Options.ResponseHandler != null)
            {
                // Respond with customer handler.
                Options.ResponseHandler(Context, exception);
                return;
            }
            // Respond with HTML or JSON.
            // ReSharper disable once SwitchStatementMissingSomeCases
            switch (Options.ExceptionResponseFormat)
            {
            case ExceptionResponseFormat.Html:
                await RespondWithHtml(Context, exception, Options.IncludeDetails);

                break;

            case ExceptionResponseFormat.Json:
                await RespondWithJson(Context, exception, Options.IncludeDetails);

                break;

            default:
                throw new Exception($"{nameof(ExceptionResponseFormat)} {Options.ExceptionResponseFormat} not supported.");
            }
        }
Example #11
0
        public static void Enable(IApplicationBuilder ApplicationBuilder, ExceptionHandlingOptions Options)
        {
            if (Options.ResponseHandler != null)
            {
                if (Options.ExceptionResponseFormat.HasValue || Options.IncludeDetails)
                {
                    throw new ArgumentException($"If setting an {nameof(Options.ResponseHandler)}, do not set an {nameof(Options.ExceptionResponseFormat)} or set {nameof(Options.IncludeDetails)} to true.");
                }
            }
            ApplicationBuilder.UseExceptionHandler(AlternatePipeline =>
            {
                // Run terminates the middleware pipeline.
                AlternatePipeline.Run(async HttpContext =>
                {
                    // Get correlation ID.
                    Guid correlationId = HttpContext.GetCorrelationId();
                    // Get exception.
                    IExceptionHandlerFeature exceptionHandlerFeature = HttpContext.Features.Get <IExceptionHandlerFeature>();
                    SimpleException innerException;
                    if (exceptionHandlerFeature.Error is ApiException apiException)
                    {
                        // Exception occurred when a Refit proxy called a service method.
                        // Deserialize exception from JSON response.
                        try
                        {
                            SimpleException refitException = apiException.GetContentAs <SimpleException>() ?? new SimpleException(apiException, correlationId, Options.AppName, Options.ProcessName);
                            innerException = new SimpleException(refitException, correlationId, Options.AppName, Options.ProcessName,
                                                                 "An exception occurred when a Refit proxy called a service method.");
                        }
                        catch
                        {
                            // Ignore exception when deserializing JSON response.
                            innerException = new SimpleException(apiException, correlationId, Options.AppName, Options.ProcessName);
                            innerException = new SimpleException(innerException, correlationId, Options.AppName, Options.ProcessName,
                                                                 $"Failed to deserialize exception from service method response.  Ensure the service's {nameof(ExceptionHandlingMiddleware)} is configured to use {nameof(ExceptionResponseFormat)}.{nameof(ExceptionResponseFormat.Json)}.");
                        }
                    }
                    else
                    {
                        innerException = new SimpleException(exceptionHandlerFeature.Error, correlationId, Options.AppName, Options.ProcessName);
                    }
                    // Log exception.
                    SimpleException exception = new SimpleException(innerException, correlationId, Options.AppName, Options.ProcessName,
                                                                    $"{HttpContext.Request.Method} with {HttpContext.Request.ContentType ?? "unknown"} content type to {HttpContext.Request.Path} resulted in HTTP status code {HttpContext.Response.StatusCode}.");
                    ILogger logger = ApplicationBuilder.ApplicationServices.GetRequiredService <ILogger>();
                    logger.Log(correlationId, exception);
                    logger.LogMetric(correlationId, HttpContext.Request.Path, "Critical Error", 1);
                    // Respond to caller.
                    if (Options.ResponseHandler != null)
                    {
                        // Respond with customer handler.
                        Options.ResponseHandler(HttpContext, exception);
                        return;
                    }
                    // Respond with HTML or JSON.
                    // ReSharper disable once SwitchStatementMissingSomeCases
                    switch (Options.ExceptionResponseFormat)
                    {
                    case ExceptionResponseFormat.Html:
                        await RespondWithHtml(HttpContext, exception, Options.IncludeDetails);
                        break;

                    case ExceptionResponseFormat.Json:
                        await RespondWithJson(HttpContext, exception, Options.IncludeDetails);
                        break;

                    default:
                        throw new Exception($"{nameof(ExceptionResponseFormat)} {Options.ExceptionResponseFormat} not supported.");
                    }
                });
            });
        }