Archive

Posts Tagged ‘MVC’

Redirect to a safe location Error Action Filter in ASP.NET MVC

February 15, 2011 Leave a comment

I have an example of an error action filter on how you can move the user to a previously know safe location in mvc with the following action filter. I and an error to tempdata which you could look for in the site master to show the error.

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;

namespace Learning.ActionFilters
{
    public class RedirectToRouteErrorAttribute : FilterAttribute, IExceptionFilter
    {
        public IEnumerable<string> RouteValues { get; private set; }
        public string ErrorMessage { get; private set; }

        public RedirectToRouteErrorAttribute(string errormessage, params string[] tokens)
        {
            ErrorMessage = errormessage;
            RouteValues = tokens;
        }

        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled)
                return;

            var items = from route in filterContext.RouteData.Values
                        join key in RouteValues on route.Key equals key
                        select route;

            var dict = new RouteValueDictionary(items);

            filterContext.Controller.TempData.Add("errormessage", ErrorMessage);
            filterContext.Result = new RedirectToRouteResult(dict);
            filterContext.HttpContext.Response.Clear();
            filterContext.ExceptionHandled = true;
        }
    }
}

// Here is an example of the usage
 [HttpPut]
 [ActionName("Edit")]
 [RedirectToRouteErrorAttribute("controller","action","id")]
 public virtual ActionResult EditUser(){}

You just specify which route values you want to keep so the RedirectToRouteResult work as required

Blair…

Advertisements

Adding Behaviors to ActionResults

January 28, 2011 Leave a comment

One problem you have with MVC is that you often need to tweak action response and add additional functionally to them. One solution is to sub class. The issues here you end up with a mess of classes and a deep inheritance tree. One solution decorator pattern.

public class ActionResultDecorator : ActionResult
    {

        protected ActionResult WrappedAction { get; private set; }

        public ActionResultDecorator(ActionResult wrappedActionResult)
        {
            WrappedAction = wrappedActionResult;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            WrappedAction.ExecuteResult(context);
        }
    }

     public class MimeTypeActionResultDecorator : ActionResultDecorator
    {

        public string MimeType { get; set; }

        public MimeTypeActionResultDecorator(ActionResult wrappedActionResult)
            : base(wrappedActionResult)
        {
        }

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = MimeType;
            base.ExecuteResult(context);
        }
    }


Simple solution like a Russian doll.

Blair

Moving On

December 20, 2010 Leave a comment

Well it has been an enjoyable 2.5 years at Ignia, and I have made a lot of great friends and had a fun time, but however life goes on and it is time for me to pursue a new direction and career. I am moving on to Kiandra IT and am really looking forward to a new Challenge.

I going to miss a whole heap of people but I know I will still keep in contact with the friends I have made.

I wish Ignia all the best as I eagerly wait to start my new role.

Blair

Creating MVC Controller Factories with Windsor

December 14, 2010 Leave a comment

You can setup dependency injection just by implementing the IControllerFactory interface or inheriting from DefaultControllerFactory. Default controller factory is preferred as it takes care of providing you more than just a controller name like Customer. Doing this manually is not great as you can see from the example below.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using System.Linq;

namespace MVCSamples.Infrastructure
{
    public class WindsorControllerFactory : IControllerFactory
    {

        private IEnumerable<Type> _controllerTypes;

        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            BuildDefaultControllerTypes();
            return IoC.Resolve(GetTypeNameForController(controllerName)) as IController;
        }

        public void BuildDefaultControllerTypes()
        {
            if (_controllerTypes == null || !_controllerTypes.Any())
                _controllerTypes = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.Name.EndsWith("Controller")).ToList();
        }

        public string GetTypeNameForController(string controllername)
        {
            return _controllerTypes.First(x => x.Name == String.Format("{0}Controller", controllername)).FullName;
        }

        public void ReleaseController(IController controller)
        {
            var disposablecontroller = controller as IDisposable;
            if (disposablecontroller != null) disposablecontroller.Dispose();
            IoC.Release(controller);
        }
    }
}

The second implementation below is not so naive. The DefaultControllerFactory takes care of finding the controller type for you. Just override the GetControllerInstance Method.

using System;
using System.Web.Mvc;

namespace MVCSamples.Infrastructure
{
    public class WindsorControllerFactory : DefaultControllerFactory
    {

        protected override IController GetControllerInstance(Type controllerType)
        {
            return IoC.Resolve(controllerType) as IController;
        }

        public override void ReleaseController(IController controller)
        {
            var disposablecontroller = controller as IDisposable;
            if (disposablecontroller != null) disposablecontroller.Dispose();
            IoC.Release(controller);
        }
    }
}

Blair

C# Abusing the Using statement for Fun and Profit

June 23, 2010 1 comment

I did some digging around on the net and found cool uses for C#’s using statement. Here is an example of how roughly the using statement works when creating a form in ASP.NET MVC. Be aware this is an example and not actually how it works as this is sampleware 🙂

public class FormHelper : IDisposable
{
	public FormHelper (string method, string action)
	{
		Console.WriteLine ("<form method=\"{0}\" action=\"{1}\">", method, action);
	}

	public virtual void Dispose ()
	{
		Console.WriteLine ("</form>");
	}	
}

using(FormHelper h = new FormHelper("GET","Test.aspx")){ }

Blair..

Learning… I mean Embracing Javascript

May 10, 2010 Leave a comment

Well this is a little interesting for me. Well when I first started programming with PHP back in the early 2000’s i really hated Javascript. and since Ajax had not come into play we use to do everything server side where possible. Then came Ajax which I got my first taste in 2007 with ASP.NET Ajax using update panels. Now everyone expects fairly rich UI’s and trying to do them in ASP.NET is really horrible especially when update panels run the whole page request from start to finish.

Also now my feelings towards Javascript are starting to change. I guess not opinions but ignorance is probably better. I have take the plunge and actually decided to learn Javascript. Now we have frameworks like JQuery we can complain about the DOM and the like we should embrace it as the functional programming language that it is.

I am using WebStorm from Jetbrains which has goot code completion so VS 2010 is not the only one out there that can claim this now.

Well the journey will be a long one but why I am doing this since I can hack my way through using UpdatePanels. Well I am a huge fan of ASP.NET MVC and am keen to update my skills so thus the plunge begins.

Blair..

WebForms the Agony

April 1, 2010 Leave a comment

Well this post even came to me as such a surprise. I have not done any web development for about 9 months, I have mainly done Windows Forms, CRM, WCF and other various things. I have been watching Rob Conery’s great MVC video set at TekPub also. After hacking and trying to do simple things with Telerik controls it really shows how flawed and cumbersome WebForms is. Even with our MVP architecture it still sucks.

Blair..