Archive

Posts Tagged ‘ASP.NET’

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

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

Telerik RadComboBox and ModalPopupExtender Issues

June 9, 2010 Leave a comment

If you have issues with this combination and the dropdown not being visible you need to increase the ZIndex of the Dropdown.

<telerik:RadComboBox ID="ddlApprovalGroup" runat="server"  ZIndex="10000000"/>

Hope this Helps.

Blair..

Custom ASP.NET Cache Provider – FileSystem

May 6, 2010 Leave a comment

So works been busy. Here is how to implement a filesystem based cached provider. I real life you would use something like memcached but I post the code later 🙂 All you need to do is create class that derives from OutputCacheProvide override the Get, Add, Set and Remove methods. Also you need to tell ASP.net to use it in the web.config file.

So here we go with the code

public class FileSystemCacheProvider : OutputCacheProvider
    {

        [Serializable]
        private class CacheObject
        {
            public object Item { get; set; }
            public DateTime Expires { get; set; }
        }

        private const string prefix = "fscache";

        public override object Get(string key)
        {
            string fullpath = GetFullPathNameForCacheKey(key);

            if (!File.Exists(fullpath))
            {
                return null;
            }

            CacheObject cObject;

            using (Stream fscacheStream = new FileStream(fullpath, FileMode.Open, FileAccess.Read))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                cObject = (CacheObject)(formatter.Deserialize(fscacheStream));
                
            }

            if (cObject != null)
            {
                if (cObject.Expires <= DateTime.Now.ToUniversalTime())
                    Remove(key);
                return cObject.Item;
            }

            return null;

        }

        private static string GetFullPathNameForCacheKey(string key)
        {
            return Path.Combine(prefix, AdjustKey(key));
        }

        public static string AdjustKey(string key)
        {
            if (key.Contains(@"\"))
                return key.Replace(@"\", "-");

            if (key.Contains(@"/"))
                return key.Replace(@"/", "-");

            return key;
        }

        public override object Add(string key, object entry, DateTime utcExpiry)
        {
            string fullpath = GetFullPathNameForCacheKey(key);
            using (Stream fscacheStream = new FileStream(fullpath, FileMode.Create))
            {
                fscacheStream.Position = 0; // Reset
                CacheObject cObject = new CacheObject {Expires = utcExpiry, Item = entry};

                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fscacheStream, cObject);
                return null;
            }
        }

        public override void Set(string key, object entry, DateTime utcExpiry)
        {
            string fullpath = GetFullPathNameForCacheKey(key);
            using (Stream fscacheStream = new FileStream(fullpath, FileMode.OpenOrCreate,FileAccess.Write))
            {

                CacheObject cObject = new CacheObject { Expires = utcExpiry, Item = entry };

                fscacheStream.Position = 0; // Reset
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fscacheStream, cObject);
            }
        }

        public override void Remove(string key)
        {
            string fullpath = GetFullPathNameForCacheKey(key);
            if (File.Exists(fullpath))
            {
                File.Delete(fullpath);
            }
        }
    }
<?xml version="1.0"?>
<caching>
      <outputCache defaultProvider="fscacheprovider"
                   enableOutputCache="true">
        <providers>
          <add name="fscacheprovider" type="ASPNET4.FileSystemCacheProvider, ASPNET4"/>
        </providers>
      </outputCache>
    </caching>

Any questions post a comment or suggestion or bugs.

Hope this helps someone.

Blair…

Categories: Development Tags: , , , ,