ExecuteResult() public method

public ExecuteResult ( ActionContext, context ) : void
context ActionContext,
return void
Example #1
0
 public static string Capture(this ActionResult result, ControllerContext controllerContext)
 {
     using (var it = new ResponseCapture(controllerContext.RequestContext.HttpContext.Response)) {
         result.ExecuteResult(controllerContext);
         return(it.ToString());
     }
 }
Example #2
0
        /// <summary>
        /// If we get an unknown action while posting, it means that the user has just been redirected from a login page. The return URL
        /// will not accept the redirect since it is POST only. So we redirect to the Box Manager Home Page.
        /// </summary>
        /// <param name="actionName">actionName</param>
        /// <example>
        ///  ~/DcmsMobile2011/BoxManager/Home/HandleScan?UiType=ScanToPallet
        /// </example>
        protected override void HandleUnknownAction(string actionName)
        {
            ActionResult result = null;
            // Is this a valid action ?
            var methods = this.GetType().GetMethods().Where(p => p.Name == actionName).ToArray();

            if (methods.Length == 0)
            {
                // This action no longer exists. Does the user have a book mark which is now broken?
                AddStatusMessage("The page you requested was not found. You have been redirected to the main page.");
                result = RedirectToActionPermanent(MVC_PieceReplenish.PieceReplenish.Home.Index());
            }
            else
            {
                if (this.HttpContext.Request.HttpMethod == "GET")
                {
                    var attrPost = methods.SelectMany(p => p.GetCustomAttributes(typeof(HttpPostAttribute), true)).FirstOrDefault();
                    if (attrPost != null)
                    {
                        // GET request for an action which requires POST. Assume that the user has been redirected from the login screen
                        AddStatusMessage("Please start again.");
                        result = RedirectToAction(this.Actions.Building());
                    }
                }
            }
            if (result == null)
            {
                // We really don't know what to do. Let base class handle it
                base.HandleUnknownAction(actionName);
            }
            else
            {
                result.ExecuteResult(this.ControllerContext);
            }
        }
        protected string RenderActionResultToString(ActionResult result)
        {
            // Create memory writer.
            var sb        = new StringBuilder();
            var memWriter = new StringWriter(sb);

            // Create fake http context to render the view.
            var fakeResponse = new HttpResponse(memWriter);
            var fakeContext  = new HttpContext(System.Web.HttpContext.Current.Request,
                                               fakeResponse);
            var fakeControllerContext = new ControllerContext(
                new HttpContextWrapper(fakeContext),
                this.ControllerContext.RouteData,
                this.ControllerContext.Controller);
            var oldContext = System.Web.HttpContext.Current;

            System.Web.HttpContext.Current = fakeContext;

            // Render the view.
            result.ExecuteResult(fakeControllerContext);

            // Restore old context.
            System.Web.HttpContext.Current = oldContext;

            // Flush memory and return output.
            memWriter.Flush();
            return(sb.ToString());
        }
Example #4
0
        public static string ToHtml(this ActionResult result, BaseController controller)
        {
            // Create memory writer.
            var sb        = new StringBuilder();
            var memWriter = new StringWriter(sb);

            // Create fake http context to render the view.
            var fakeResponse = new HttpResponse(memWriter);

            var routeData = new RouteData();

            routeData.Values.Add("controller", controller.GetType().Name.Replace("Controller", ""));
            routeData.Values.Add("action", "PrintBlank");

            var fakeContext = new HttpContext(System.Web.HttpContext.Current.Request,
                                              fakeResponse);
            var fakeControllerContext = new ControllerContext(
                new HttpContextWrapper(fakeContext),
                routeData,
                controller);
            var oldContext = System.Web.HttpContext.Current;

            System.Web.HttpContext.Current = fakeContext;
            // Render the view.
            result.ExecuteResult(fakeControllerContext);

            // Restore old context.
            System.Web.HttpContext.Current = oldContext;

            // Flush memory and return output.
            memWriter.Flush();
            return(sb.ToString());
        }
Example #5
0
 public override void ExecuteResult(ControllerContext context)
 {
     context.Controller.TempData["Message"]        = _message;
     context.Controller.TempData["ClassAlert"]     = _classAlert;
     context.Controller.TempData["ClassGlyphicon"] = _classGlyphicon;
     _actionResult.ExecuteResult(context);
 }
Example #6
0
        /// <summary>
        /// Executes the given <see cref="ActionResult"/>.
        /// </summary>
        /// <param name="actionResult">The action result to execute.</param>
        /// <returns>The result of executing the action result.</returns>
        public virtual string Execute(ActionResult actionResult)
        {
            if (actionResult == null)
            {
                throw new ArgumentNullException("actionResult");
            }

            // Build a new ControllerContext, using a StringWriter to capture the result of executing the ActionResult.
            using (var writer = new StringWriter(CultureInfo.InvariantCulture))
            {
                var response          = new HttpResponse(writer);
                var context           = new HttpContext(_controllerContext.HttpContext.ApplicationInstance.Request, response);
                var controllerContext = new ControllerContext(new HttpContextWrapper(context), _controllerContext.RouteData, _controllerContext.Controller);

                var oldContext = HttpContext.Current;
                HttpContext.Current = context;

                actionResult.ExecuteResult(controllerContext);

                HttpContext.Current = oldContext;

                writer.Flush();

                return(writer.ToString());
            }
        }
        public override void ExecuteResult(ControllerContext context)
        {
            CommandResult resultadobackendClient = null;

            if (context.Controller.ViewData.ModelState.IsValid)
            {
                var backendClient = ObjectFactory.GetInstance <IBackendClient>();
                try
                {
                    resultadobackendClient = backendClient.ExecuteCommand(command);
                }
                catch (FaultException <CommandFault> e)
                {
                    foreach (var error in e.Detail.CommandErrors)
                    {
                        context.Controller.ViewData.ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
                    }
                }
            }

            if (!context.Controller.ViewData.ModelState.IsValid)
            {
                errorView.ViewData = context.Controller.ViewData;
                errorView.TempData = context.Controller.TempData;
                errorView.ExecuteResult(context);
                return;
            }
            //context.Controller.TempData["Resultado"] = "OK";
            context.Controller.TempData["ResultadoCommand"] = resultadobackendClient;
            successAction.ExecuteResult(context);
        }
Example #8
0
        public override void ExecuteResult(ControllerContext context)
        {
            var alerts = context.Controller.TempData.GetAlerts();

            alerts.Add(new Alert(_alertClass, _message));
            _innerResult.ExecuteResult(context);
        }
Example #9
0
        public static void CRenderAction(this HtmlHelper helper, string Action, string Controller, params object[] Param)
        {
            var ControllerType = Assembly.GetAssembly(typeof(JIC.Crime.View.Controllers.ControllerBase)).GetTypes().Where(type => type.Namespace != null && type.Namespace.Equals("JIC.Crime.View.Controllers") && type.Name == Controller).FirstOrDefault();

            if (ControllerType == null)
            {
                throw new Exception("Controller Not Found");
            }

            object obj = UnityConfig.GetObject(ControllerType);

            if (obj == null)
            {
                throw new Exception("Couldn't Initialize Object");
            }

            var ActionMethod = ControllerType.GetMethod(Action);

            if (ActionMethod == null)
            {
                throw new Exception("Action Not Found in Controller");
            }
            ActionResult result = (ActionResult)ActionMethod.Invoke(obj, Param);

            result.ExecuteResult(helper.ViewContext);
        }
    public static string RenderViewToString(this ControllerContext @this, ActionResult actionResult)
    {
        // Create memory writer.
        var sb        = new System.Text.StringBuilder();
        var memWriter = new System.IO.StringWriter(sb);

        // Create fake http context to render the view.
        var fakeResponse = new HttpResponse(memWriter);
        var fakeContext  = new HttpContext(
            HttpContext.Current.Request,
            fakeResponse
            );
        var fakeControllerContext = new ControllerContext(
            new HttpContextWrapper(fakeContext),
            @this.RouteData,
            @this.Controller
            );
        var oldContext = HttpContext.Current;

        HttpContext.Current = fakeContext;

        // Render the view.
        actionResult.ExecuteResult(fakeControllerContext);

        // Restore old context.
        HttpContext.Current = oldContext;

        // Flush memory and return output.
        memWriter.Flush();
        return(sb.ToString());
    }
Example #11
0
        public virtual object Invoke(Type controllerType, MethodInfo action, IHttpContext context)
        {
            ControllerContext controllerContext = new ControllerContext(context);

            var controller    = (Controller)ServiceResolver.Current.Resolve(controllerType);
            var newController = controller as IController;

            try
            {
                controllerContext.Controller     = controller;
                controllerContext.ControllerName = controllerType.Name;
                controllerContext.ControllerUri  = "/" + controllerType.Name;
                controllerContext.ActionName     = action.Name;

                controller.SetContext(controllerContext);


                if (newController != null)
                {
                    var actionContext = new ActionExecutingContext(controllerContext);
                    newController.OnActionExecuting(actionContext);
                    if (actionContext.Result != null)
                    {
                        return(actionContext.Result);
                    }
                }
                object[]     args   = { controllerContext };
                ActionResult result = (ActionResult)action.Invoke(controller, args);
                result.ExecuteResult(controllerContext);

                if (newController != null)
                {
                    var actionContext = new ActionExecutedContext(controllerContext, false, null);
                    newController.OnActionExecuted(actionContext);
                    if (actionContext.Result != null)
                    {
                        return(actionContext.Result);
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                if (newController != null)
                {
                    var exceptionContext = new ExceptionContext(ex);
                    newController.OnException(exceptionContext);
                    if (exceptionContext.Result != null)
                    {
                        return(exceptionContext.Result);
                    }
                }

                ActionResult result = (ActionResult)controller.TriggerOnException(ex);

                return(result);
            }
        }
Example #12
0
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentEncoding = Encoding.UTF8;

            context.HttpContext.Response.StatusCode = statusCode;

            actualResult.ExecuteResult(context);
        }
 public override void ExecuteResult(ControllerContext context)
 {
     _result.ExecuteResult(context);
     if (_error != null && _error.StatusCode != null)
     {
         context.HttpContext.Response.StatusCode = _error.StatusCode.Value;
     }
 }
        public override void ExecuteResult(ControllerContext context)
        {
            // Add the notification
            context.Controller.Notifications().Add(_status, _message);

            // Continue with execution
            _result.ExecuteResult(context);
        }
Example #15
0
        /// <summary>
        /// Renders an MVC view defined by a controller and named action.
        /// </summary>
        ///
        /// <remarks>
        /// The basis for this was taken from user http://stackoverflow.com/users/66372/eglasius 's
        /// answer answer for this question:
        /// http://stackoverflow.com/questions/3702526/is-there-a-way-to-process-an-mvc-view-aspx-file-
        /// from-a-non-web-application.
        /// </remarks>
        ///
        /// <exception cref="ArgumentException">
        /// Thrown when the named action could not be found on the controller.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown when there is already an application HTTP context.
        /// </exception>
        ///
        /// <typeparam name="T">
        /// Generic type of the controller.
        /// </typeparam>
        /// <param name="action">
        /// The action name.
        /// </param>
        /// <param name="destroyContext">
        /// true to destroy context.
        /// </param>
        ///
        /// <returns>
        /// The string of HTML
        /// </returns>

        public string RenderView <T>(string action, bool destroyContext = true)  where T : Controller, new()
        {
            // get method info

            var mi = GetCaseInsensitiveMethod(typeof(T), action);

            if (mi == null)
            {
                throw new ArgumentException(String.Format("Unable to find action \"{0}\" on controller \"{1}\"",
                                                          action,
                                                          typeof(T).FullName));
            }

            string controllerName = ("." + typeof(T).FullName)
                                    .BeforeLast("Controller").AfterLast(".");

            string path = controllerName + "/" + action;
            //string url = "http://mvc.test.abc/" + path;

            var controller = new T();

            //var writer = new StringWriter();

            //var httpContext = new HttpContext(new HttpRequest("", url, ""), new HttpResponse(writer));


            if (HttpContext.Current != null)
            {
                throw new InvalidOperationException("HttpContext was already set");
            }

            HttpResponse response;
            StringWriter writer;

            Context = GetHttpContext(out writer, out response);

            HttpContext.Current = Context;
            var routeData = new RouteData();

            routeData.Values.Add("controller", controllerName);
            routeData.Values.Add("action", mi.Name);

            var controllerContext = new ControllerContext(new HttpContextWrapper(Context), routeData, controller);

            controller.ControllerContext = controllerContext;

            ActionResult res = (ActionResult)mi.Invoke(controller, new object[] { });

            res.ExecuteResult(controllerContext);

            if (destroyContext)
            {
                ClearContext();
            }

            return(writer.ToString());
        }
Example #16
0
 /// <summary>
 /// Captures the text from an ActionResult.
 /// </summary>
 /// <param name="result"></param>
 /// <param name="controllerContext"></param>
 /// <returns></returns>
 public static string Capture(this ActionResult result, ControllerContext controllerContext)
 {
     // Credit:Dmytrii Nagirniak
     // http://approache.com/blog/render-any-aspnet-mvc-actionresult-to/
     using (var it = new ResponseCapture(controllerContext.RequestContext.HttpContext.Response))
     {
         result.ExecuteResult(controllerContext);
         return(it.ToString());
     }
 }
        /// <summary>
        /// Captures the contents of an ActionResult as a string
        /// </summary>
        /// <param name="result">The ActionResult</param>
        /// <param name="controllerContext">The current ControllerContext</param>
        /// <returns>Returns the contents of the ActionResult as a string</returns>
        public static string Capture(this ActionResult result, ControllerContext controllerContext)
        {
            // Use the current response
            using (var content = new ResponseCapture(controllerContext.RequestContext.HttpContext.Response))
            {
                // Execute the ActionResult against the current ControllerContext and return the contents
                result.ExecuteResult(controllerContext);

                return(content.ToString());
            }
        }
Example #18
0
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        var          usePartial = ShouldUsePartial();
        ActionResult res        = GetInnerViewResult(usePartial);

        res.ExecuteResult(context);
    }
Example #19
0
        public override void ExecuteResult(ControllerContext context)
        {
            var alerts = context.Controller.TempData.ContainsKey("Message") ? (List <Alert>)context.Controller.TempData["Message"] : new List <Alert>();
            var alert  = new Alert {
                Message = _message, AlertStyle = _alertStyle
            };

            alerts.Add(alert);
            context.Controller.TempData["Message"] = alerts;
            _actionResult.ExecuteResult(context);
        }
Example #20
0
        /// <summary>
        /// Captures the specified result. This method recall an Action method
        /// </summary>
        /// <param name="result">The result in a string Format</param>
        /// <param name="controllerContext">The controller context.</param>
        /// <returns></returns>
        public static string Capture(this ActionResult result, ControllerContext controllerContext)
        {
            var response    = controllerContext.RequestContext.HttpContext.Response;
            var localWriter = new System.IO.StringWriter();

            response.Output = localWriter;
            result.ExecuteResult(controllerContext);

            localWriter.Flush();

            return(localWriter.ToString());
        }
Example #21
0
        /// <summary>
        /// Handle 404 exception and redirect it to the 404 error page, and fallback to NotFoundError view
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnException(ExceptionContext filterContext)
        {
            //handle 404 exception
            if (filterContext.Exception is HttpException)
            {
                HttpException httpException = filterContext.Exception as HttpException;
                if (httpException.GetHttpCode() == 404)
                {
                    filterContext.HttpContext.Response.StatusCode = 404;
                    //add 404 page handling specified by url map

                    string error404PageId = _PageFactory.UrlMap
                                            .ToNullHelper()
                                            .Propagate(
                        urlMap => urlMap.Error404PageId)
                                            .Return(string.Empty);

                    if (!string.IsNullOrEmpty(error404PageId))
                    {
                        CMSPageRequest page404 = _PageFactory.GetPage(Request, error404PageId) as CMSPageRequest;
                        if (page404 != null && page404.Exists)
                        {
                            filterContext.ExceptionHandled = true;

                            ActionResult result404 = viewOrXsltFallback(page404);
                            result404.ExecuteResult(ControllerContext);
                            return;
                        }
                    }

                    //go to provided Error view, structured url map 404 page is not used, only if the view exists
                    //otherwise, use base procedure
                    ViewResult viewResult = View("NotFoundError", new Error404()
                    {
                        Title    = Ingeniux.Runtime.Properties.Resources.Error404Title,
                        BodyCopy = Ingeniux.Runtime.Properties.Resources.Error404BodyCopy,
                        Factory  = _PageFactory
                    });

                    ViewEngineResult viewEngineResult = viewResult.ViewEngineCollection.FindView(ControllerContext, viewResult.ViewName, viewResult.MasterName);
                    if (viewEngineResult != null && viewEngineResult.View != null && viewEngineResult.ViewEngine != null)
                    {
                        filterContext.ExceptionHandled = true;

                        viewResult.ExecuteResult(ControllerContext);
                        return;
                    }
                }
            }

            base.OnException(filterContext);
        }
Example #22
0
        /// <summary>
        /// Used for HandleUnknownAction to require login
        /// </summary>
        /// <param name="userMessage">HTML Encoded user message</param>
        protected void ExecuteBounceToLoginNoAccess(string userMessage, TempDataDictionary tempData)
        {
            if (this.ControllerContext == null)
            {
                this.ControllerContext = new ControllerContext(new HttpContextWrapper(System.Web.HttpContext.Current), this.RouteData, this);
                this.TempData          = tempData;
            }
            SetSessionVars(this.Request.RequestContext);

            ActionResult action = BounceToLoginNoAccessResult(userMessage);

            action.ExecuteResult(this.ControllerContext);
        }
Example #23
0
    public static string Capture(this ActionResult result, ControllerContext controllerContext)
    {
        if (controllerContext == null)
        {
            return("");
        }

        using (var capture = new ResponseCapture(controllerContext.RequestContext.HttpContext.Response))
        {
            result.ExecuteResult(controllerContext);
            return(capture.ToString());
        }
    }
Example #24
0
    public override void ExecuteResult(ControllerContext context)
    {
        var isAjaxRequest = context.HttpContext.Request["isAjax"];

        if (isAjaxRequest != null && isAjaxRequest.ToLower() == "true")
        {
            _ajaxActionResult.ExecuteResult(context);
        }
        else
        {
            _viewResult.ExecuteResult(context);
        }
    }
Example #25
0
        protected override void HandleUnknownAction(string actionName)
        {
            //TryGetCompany(actionName, out var firma, out var result);
            if (TryGetCompany(actionName, out var firma, out var result))
            {
                (Firma firma, string viewName, string title)model = (firma, "Index", $"{firma.Jmeno}");
                ActionResult res = View("_subjektLayout", model);
                res.ExecuteResult(this.ControllerContext);
                return;
            }

            result.ExecuteResult(this.ControllerContext);
        }
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();

            Server.ClearError();

            Logger.LogError(exception);

            HomeController controller = Common.CreateController <HomeController>();
            //Users don't have to know any details about this exception - show it only to an admin
            ActionResult result = controller.Error(Global.IsAdminMode ? exception : new Exception(Localization.ApplicationLocalization.UnexpectedError));

            result.ExecuteResult(controller.ControllerContext);
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
Example #27
0
        /// <summary>
        /// Assert on the given <paramref name="streamedFileResult"/> content with a custom <paramref name="assertion"/>.
        /// </summary>
        /// <param name="streamedFileResult">SUT (System under Test).</param>
        /// <param name="assertion">Custom assertion.</param>
        public static void OnContent(ActionResult streamedFileResult, Action <string> assertion)
        {
            using (var actualBody = new MemoryStream())
            {
                var actualContext = new ActionContext {
                    HttpContext = new DefaultHttpContext {
                        Response = { Body = actualBody }
                    }
                };
                streamedFileResult?.ExecuteResult(actualContext);
                string actualContent = Encoding.UTF8.GetString(actualBody.ToArray());

                assertion(actualContent);
            }
        }
Example #28
0
        public override void ExecuteResult(ControllerContext controllerContext)
        {
            var tagHelperProvider = GetTagHelperProvider(_defaultDependencyResolver, controllerContext);

            var response = controllerContext.HttpContext.Response;

            if (response.Filter != null)
            {
                response.Filter = new HtmlProcessor(response.Output, tagHelperProvider);
            }
            else
            {
                response.Output = new TagHelperWriter(response.Output, tagHelperProvider);
            }
            _actionResult.ExecuteResult(controllerContext);
        }
Example #29
0
        public override void ExecuteResult(ControllerContext context)
        {
            //ActionResult emptyRes = new EmptyResult();
            //emptyRes.ExecuteResult(context);
            TextWriter   baseOutput = context.HttpContext.Response.Output;
            MyTextWriter W          = new MyTextWriter(baseOutput);

            context.HttpContext.Response.Output = W;
            _main.ExecuteResult(context);
            context.HttpContext.Response.Output = baseOutput;
            //CustomContext MyContext = new CustomContext(context);
            //_main.ExecuteResult(MyContext);

            //context.HttpContext.Response.Write("<div style='width:100%;text-align:center;'>" +
            //    "<br><h1>DIOS applications</h1><p>&copy; " + DateTime.Now.Year.ToString() + "</p>");

            _result = W.Result;
        }
Example #30
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (context.HttpContext.Request.IsAuthenticated)
            {
                context.HttpContext.Response.StatusCode = 200;
                InitializeResult(context);
                Result.ExecuteResult(context);
            }
            else
            {
                base.ExecuteResult(context);
            }
        }