Jamie Dixon

Web Developer, Software Engineer and Mixed Language Artist
RSS icon Email icon Home icon
  • Selenium IDE for Firefox 6

    Posted on August 18th, 2011 Jamie 3 comments

    Whilst not yet in public release, a new version of the Selenium IDE is now available for those using Firefox 6.

    http://xserve.openqa.org:8085/browse/IDE-EDITOR-MULTI-166/artifact

  • Replacing Request.IsAjaxRequest() with ActionFilter

    Posted on December 8th, 2010 Jamie No comments

    Ever wondered if you can replace all those

    ?View Code CSHARP
    if(Request.IsAjaxRequest())
    {
    // return some partial view
    }

    with an action filter?

    Although it’s not much code to write the above in many controller methods, I was intrigued to figure out how this behaviour could be replaced through the use of a custom ActionFilter. Here’s what I came up with (It might not be any better than using the above and this was created purely out of a desire to figure out how possible it could be):

    Action Filter:

    ?View Code CSHARP
     public class ReturnPartialForAjaxRequestActionFilter : ActionFilterAttribute
        {
            public string ViewName { get; set; }
     
            public override void OnActionExecuted(ActionExecutedContext filterContext)
            {
                if (ViewName != null)
                {
                    var request = filterContext.RequestContext.HttpContext.Request;
                    if (request.IsAjaxRequest())
                    {
                        var result = (ViewResult)filterContext.Result;
     
                        filterContext.Result = new PartialViewResult
                        {
                            ViewName = ViewName,
                            ViewData = result.ViewData
                        };
                    }
                }
                base.OnActionExecuted(filterContext);
            }
        }

    Usage:

    ?View Code CSHARP
    [ReturnPartialForAjaxRequestActionFilter(ViewName = "PartialViewName")]
    public ActionResult MyActionResult()
    {
    }

    This is possibly a bit overkill given that it most likely involves more typing than simply writing out the original if statement however as a thought exercise it was quite fun to implement.

    MVC
  • ASOS Marketplace – It’s alive!

    Posted on November 23rd, 2010 Jamie No comments

    After months of hardwork from everyone on the team, today is the day that ASOS Marketplace goes live (https://marketplace.asos.com) !

    There’s a lot I want to say about this project and the people who’ve been involved but that’s going to have to wait until after today. As with any major project like this, launch day is a big deal.

    ASOS Marketplace is by far the largest and most fun project I’ve worked on to date and seeing it go live today is a really special moment.

    I’m writing this post just moments before we hit the go live button knowing that as soon as we go live it’s going to be all hands on deck.

    If you’re reading this post then everything has gone well and I’m likely dancing around the office with the rest of the team.

    ASOS Marketplace

  • Get random item from IList< T >

    Posted on November 3rd, 2010 Jamie No comments

    In what could turn out to be a series of posts about helpful extension methods I thought I’d include this quick little method for getting a random item from an IList collection.

    ?View Code CSHARP
    public static T GetRandomItem<T>(this IList<T> collection)
            {
                return collection[(new Random().Next(0, collection.Count))];
            }

    This can then be used as follows:

    ?View Code CSHARP
    var collectionList = new List<string> {"String 1", "String 2", "String 3"};
    string item = collectionList.GetRandomItem();
  • ContainsAny & EquelsAny

    Posted on November 2nd, 2010 Jamie No comments

    This post is a bit of a reference for myself and also a handy tip for those wondering how to perform Contains and Equels on a collection of strings.

    For the purposes I needed I simply wanted to check if a string Equels Any or Contains Any of an array of strings. I put these together as a couple of extension methods:

    ?View Code CSHARP
    public static bool ContainsAny(this string input, string[] items)
            {
                return items.Any(input.Contains);
            }
    ?View Code CSHARP
            public static bool EqualsAny(this string input, string[] items)
            {
                return items.Any(input.Equels);
            }

    That’s all that’s required.

    This means we can now do things like:

    ?View Code CSHARP
    bool isWomenOrUnisex = category.EquelsAny(new []{"women","unisex"});

    Simples!

  • Passing Parameters to an ActionFilter in ASP.NET MVC

    Posted on August 5th, 2010 Jamie 1 comment

    Creating action filters is quite a simple process. You can simply inherit from ActionFilterAttribute and bingo, you’ve got yourself a custom ActionFilter.

    There’s a lot of articles out in the wilderness of the web that explain how to go about creating custom ActionFilters and most of them are pretty good articles.

    The one thing I’ve not been able to find online is some instruction of how to create action filters that accept some kind of parameters. We already see this concept being used by such things as the OutputCacheAttribute action method where we can pass in a Duration, and various other parameters:

    ?View Code CSHARP
    [OutputCache(Duration = 5)]

    So how do we allow our own custom action filters to accept parameters in this same way?

    The answer seems really simple once you know however a search on Google doesn’t seem to return much in the way of any answers to this question (as with many of my posts, they’re usually things that I haven’t been able to find online already).

    The simple answer is that: Action filter parameters are properties of the action filter.

    Here’s a short example custom action filter that exposes a property which I then use when attaching the attribute to a class.

    ?View Code CSHARP
    public class CustomActionAttrbitue : ActionFilterAttribute
    {
         public int Id {get; set;}
         public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Do some work here.
        }
    }

    and in attaching this attribute to a class:

    ?View Code CSHARP
    [CustomAction(Id = 5)]
    public class MyController  : Controller
    {
     
    }

    Like I said above, once you know that the parameter is a property of the action filter, it seems obvious. Hope this helps someone else looking for this information.

  • Rendering a partial view n number of times with ASP.NET MVC

    Posted on July 30th, 2010 Jamie No comments

    UPDATE

    After spending a little more time working with MVC2 and having read this comment by Brad Wilson, I now know about the existence of Html.Partial which renders a partia view directly to a string.

    This simplifies my code in a number of ways. Firstly the code itself is just simpler. There’s no longer any need to render the partial out to a string because our new Partial method does this for us.

    The RenderPartials method now looks like:

    ?View Code CSHARP
    public static void RenderPartials(this HtmlHelper helper, string partialViewName, IEnumerable models, string htmlFormat)
            {
                foreach (var view in models.Select(model =&gt; helper.Partial(partialViewName,model)))
                {
                    helper.ViewContext.HttpContext.Response.Output.Write(htmlFormat, view.ToHtmlString());
                }
            }

    Much cleaner !!

    This also fixed up the problem of using a names partial view rather than the full path. Again, all of this is handled by our new Partial method which leaves us get on with the important stuff.

    Thanks again to the MVC team for including something extremely useful in MVC2.

    Origional Post

    I’ve recently been thinking about the way that RenderPartial works in ASP.NET MVC and one of the things I’ve been wanting is a way to render a partial view n number of times based on some kind of collection.

    I had a look around and didn’t find anything so I’ve written out a solution which I’d like to share. It’s by no means a perfect solution right now. I’d like to add support for named partials rather than specifying the path to the partial view and this will be part of the next iteration.

    Why?
    The main reason for this solution is to solve the problem of having looping code in the views. This can quite often get a bit messy especially when mixing html and C#.

    The implementation

    Firstly, here’s the method signature:

    ?View Code CSHARP
    public static void RenderPartials(this HtmlHelper helper,
                                                     string partialViewName,
                                                     IEnumerable models,
                                                     string htmlFormat)
    • The partialViewName parameter is going to be the location of our partial view. I’m going to be improving this to accept just the name of the view in this next iteration.
    • The models parameter contains a collection and for each item in that collection, we’ll render out our partial view.
    • The htmlFormat paramter is an optional parameter. This basically allows you to specify code that you’d like to be part of the iteration of each model item with {0} being the partial view itself (I’ll give an example below)

    The method:

    So here’s the method as it stands at the moment.

    ?View Code CSHARP
    public static void RenderPartials(this HtmlHelper helper, string partialViewName, IEnumerable models, string htmlFormat)
            {
                htmlFormat = (htmlFormat.IsNullOrEmpty()) ? "{0}" : htmlFormat;
     
                foreach (var model in models)
                {
                    var viewDataDictionary = new ViewDataDictionary(model);
                    var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
     
                    var x = new ViewPage {ViewData = viewDataDictionary, Url = urlHelper, ViewContext = helper.ViewContext};
     
                    Control control = x.LoadControl(partialViewName);
                    x.Controls.Add(control);
     
                    var sb = new StringBuilder();
     
                    using (var sw = new StringWriter(sb))
                    {
                        using (var tw = new HtmlTextWriter(sw))
                        {
                            x.RenderControl(tw);
                            helper.ViewContext.HttpContext.Response.Output.Write(htmlFormat,sb); // Output content to the response stream
                        }
                    }
                }
            }

    with a simple overload method to make the htmlFormat parameter optional:

    ?View Code CSHARP
    public static void RenderPartials(this HtmlHelper helper, string partialViewName, IEnumerable models)
            {
                helper.RenderPartials(partialViewName,models,null);
            }

    How do we use it?

    Here’s a basic example of how we can use this new RenderPartials method within one of our views:

    ?View Code CSHARP
    &lt;%: Html.RenderPartials("~/Areas/OrderManagement/Views/Shared/Order.ascx",
                                       Model.Orders,
                                       "<span class="\&quot;specialOrder\&quot;">{0}</span>"); %&gt;

    This will now render our partial view Order.ascx once for each order in Model.Orders. Our third parameter for htmlFormat specifies some html that we’re wrapping our partial view in with {0} being the partial view itself. This allows for our front end team to add custom html to specific renderings of our partial view.

    Conclusion
    So the main idea of this method is to neaten up our views a little bit whilst at the same time, giving our front end guys enough control and flexibility to make the solution viable.

    If you have any comments or sugestions you can either drop me a line at jamie@jamie-dixon.co.uk or leave a comment below.

    You can follow me on Twitter at http://twitter.com/jamiedixon :-)

  • Visual Studio – Lost nesting of codebehind

    Posted on April 30th, 2010 Jamie No comments

    We’ve all had times when we’ve created an ASP.NET webpage and then a new page is required with almost identical functionality.

    I had that task today and so making things simple I copied the current files, pasted them and made the necessary changes to hook the designer and code-behind files to the aspx page.

    This works perfectly. The code builds, the page runs, everything happens as I expected it to.

    Then I noticed a little quirk in Visual Studio 2008. One of the great features of Visual Studio is the way in which it visually nests code-behind files in the Solution Explorer under your aspx file.

    After making a copy of my origional page I noticed that my code-behind was left astray. I checked all the references to make sure everything was hooked up correctly but still, my code-behind wasn’t nesting nicely under my aspx page as usual.

    Now I’m sure many people have come across this problem before however this was a first for me.

    It turns out that the references are stores in the csproj file. There is a reference to the code-behind file and a list of dependancies. By default, when doing a copy/paste of files outside of Visual Studio, this reference is not updated and the code-behind file doesn’t attach itself to the aspx file in the Solution Explorer.

    The solution is to simply add a reference to the dependant aspx fie in the csproj file like so:

    <Compile Include="myShinyNewFile.aspx.cs">
    <DependentUpon>myShinyNewFile.aspx</DependentUpon>
    <SubType>ASPXCodeBehind</SubType>
    </Compile>

    Once you’ve added the second line into the csproj file, restarting visual studio brings back the much loved nesting.

  • Upgrading EPiServer to version 6

    Posted on April 23rd, 2010 Jamie 3 comments

    With the new EPiServer 6 now available to the masses, upgrading current EPiServer sites is something we’ve all been looking forward to.

    I was tasked this week with upgrading a pretty large website we’ve current got in EPiServer 5.2.375.236.

    There’s a nice little upgrade utility that comes with the EPiServer Deployment Center and this was my first port of call. I knew there’d be more to it than simply using the upgrade wizard however this handy utility did the majority of the work.

    I then headed over to the EPiServer CMS folder on my local machine to grab the required DLLs from the “6.0.530.0″ folder, dropped these into my websites DLL folder and updated all my references in Visual Studio. Bingo! Right? Well almost.

    After running the project for the first time I came across the following error message:

    Cannot resolve dependencies for the following module(s)
    EPiServer.Cms.Shell.UI.InitializableModule
    EPiServer.Cms.Shell.UI.InitializableModule
    EPiServer.Web.InitializationModule
    EPiServer.Web.InitializationModule

    The error is quite clear and I knew that some dependancies were missing, I just didn’t know which ones.

    After some digging around and much testing, it turns out that not all of the required DLLs are present in the “6.0.530.0″ folder (C:\Program Files\EPiServer\CMS\6.0.530.0 – on my machine).

    Doing a quick *.dll search in the CMS folder I found a zip file containing a full EPiServer project with a complete bin folder (C:\Program Files\EPiServer\CMS\6.0.530.0\VSTemplates\EPiServerProject.zip – on my machine).

    This bin folder contains 35 dlls where as the “6.0.530.0/bin” folder only contains 26 dlls.

    Copying all of these new dlls to my DLLs folder, updating my references in Visual Studio once more and running the project now works as expected :-)

    EPiServer 6 is looking really slick and the admin panel has improved hugely.

    I’m hoping that this post will be of help to all EPiServer developers finding they have the same problem. Having searched Google for a good couple of hours yielding no helpful results on this one, I hope this post will be of much help.

  • Global Resource strings by property

    Posted on April 15th, 2010 Jamie No comments

    Every now and then I come across a bunch of string literals littered through out some code and begin the task of moving them out into their own resource file (.resx).

    Gaining access to these strings from C# is pretty easy however I’m yet to find anywhere explaining it the way I find simplest.

    Assuming your resx file is stored in the App_GlobalResources folder, you can basically assign your resource file to a variable in your C# using the following syntax:

    ?View Code CSHARP
    using Res = Resources.MyResourceFile

    This then gives you the ability to referene the contents of the resource file as properties in your code.

    ?View Code CSHARP
    string x = Res.OneOfMyStringNames;