#DDD10 – My Ramblings

This post is a little late as DDD10 was on the 1st September, but I have been extremely busy #cough# attending Gaga concerts and working late. (Yes I’m a big Gaga fan, what of it! :0) )

For anyone that doesn’t know, “DDD” simply means DeveloperDeveloperDeveloper and are community events which are (at the moment) free to the community and sponsored by various partners. Now just because they are free this definitely does not dilute the content on offer. Before I ramble on about the Sessions on offer, I would like to say what a marvellous job the organisers and speakers of the events do, to make these events so successful. You really do feel the passion from these guys and gals. Humbling to say the least.

This is my 2nd year attending the event (again held at Microsoft). This year i wanted to choose Sessions which are applicable to what im trying to achieve now, instead of what interests me from the title. So as I’m learning ASP.NET and MVC at home at the moment, i decided to focus the majority of my efforts around web technologies (where possible), so i chose the following Sessions:



Keeping JS Sane

ASP.NET MVC gone wrong

WebSockets and SignalR – Building the Real Time Interactive web

Performance and Scalability, the Stack Exchange way

Windows 8 with XAML and C#

Developing a production immune system


My Experience….


As you can see a good mix of Sessions.  Overall, I had an really good day, enjoying myself immensely and learning some stuff along the way. Big thanks to all everyone involved. So how did i find the sessions……

  1. Keeping JS Sane – The first session of the day was run by an excitable Rob Ashton. The first thing I learnt was “Add Ponies”, which I presume is a reference to Rob’s fascination of My Little Pony“?Lets set the scene – It is 9.30AM on a Saturday morning, I have been up since 4am and travelled from Durrington-By-Sea to Reading with my laptop bag and overnight bag. I’m tired and ratty but I was looking forward to the day ahead, until I’m bombarded with references to a kiddies toy. I sighed…. alot…. It is a shame, because Rob’s work on line is astounding and in any normal circumstances I’m sure he is a great guy to be around and a good laugh. The problem was the early morning and a ratty Gareth, who didn’t appreciated the finer side to Rob’s hyperactive start.I did learn a few things (considering I’m a JS nOOb that should of been a must), which i will investigate. Specifically using JSLint and Zombie client-side testing framework.  I would like to point out though, that I met a (drunk) Rob at the after party and he is a very nice and witty chap and consumed at last count, 3 pizza’s at Pizza Express. Fair play to the chap!
  2. ASP.NET Gone Wrong – So after the first session, i was hoping for more, and i got it. This session was presented by Stuart Leeks and Simon Ince from Microsoft. The presentation was around the 11 rules of MVC where people slip up. It was a well thought out and well presented session, with some solid code samples, and Stuart and Simon really worked well together. I took a lot from this presentation, and i will be thinking over the coming weeks on how i can use them to improve my coding using MVC. The rules are:
    1. Controller Rule 1 – NO Business Logic in your Action Methods!
    2. Controller Rule 2 – A good Action Method should only be approximately 15 lines of code.
    3. Controller Rule 3 – Action Filters are your friend! Do not use a Base Controller to code generic functionality applicable to a Controller (Like Logging).
    4. Controller Rule 4 – Don’t use JavaScriptResult in your C#. Leave your Javascript on your Views.
    5. View Rule 5 – Always use strongly-typed Views. Don’t use the dynamic ViewBag or ViewData. Use ViewModels instead for this.
    6. View Rule 6 – Minimise logic within Views.
    7. View Rule 7 – I have written down “No Javascript in Views”. I will need to confirm this one i think. Unless Stuart meant putting your Javascript code within a separate Javascript source file and not directly in a View.
    8. View Rule 8 – Don’t use Base Vie. Create one per View.  This is for maintainability purposes.
    9. Model Rule 9 – Have a separate ViewModel for each View.
    10. Model Rule 10 – Don’t use base ViewModels. If needed use Child Actions to perform generic functionality.
    11. Model Rule 11 – Dont add any behavioural logic to the ViewModels.
  3. Websocket’s and SignalR – This was another solid session by Chris Alcock, and another I’m glad I attended. It was a tough choice as Gary Short’s Raspberry Pi was on at the same time, and my inner-Nerd really wanted to attend. Chris though did an excellent job describing Websocket’s and its implementation within SignalR. Nice session with the following points of interest:
    1. Websockets Protocol is currently on Version 13.
    2. Browser support is: Firefox 11+, Chrome 16+ and IE10.
    3. SignalR doesn’t just use Websockets, so can fall back to older protocols for browsers which doesn’t support Websockets.
    4. Tip: Never create a SignalR folder in the root of your Visual Studio Project as this will break stuff.
    5. Tip: Breakpoints can Timeout in SignalR Projects when debugging.
  4. Performance and Scalability, The Stack Exchange Way – Another one of my favourite sessions. Marc Garvell  presented some really interesting ideas using technologies he help build at Stack Exchange to locate performance issues that could be costly to them. It was a insightful presentation talking about Profiling using Miniprofiler  which can be used in MVC projects. Its a single assembly which can be included, and you pepper it around your code-base to use its functionality. It can also be used in a production environment which is a nice feature. Another example was their Micro-ORM, Dapper, as a light-weight alternative to EF  and LINQ-2-SQL.
  5. Windows 8 using XAML and C# – I chose this session because i attended Kris Athi DDD9 presentation on WIndows Phone 7 Development and thoroughly enjoyed it. I wasn’t disappointed this time either. A good session on Windows 8 and its feature set like Notifications, Charms and Contracts etc, but nothing i didnt already know. Kris though knows what he is talking about and i was thoroughly impressed again on his talk. This is a good thing, because if he doing future talks, i will probably choose his session based on his skills alone and not the subject matter, so well done Kris!
  6. Developing a Production Immune System – Out of all the sessions before DDD10 started, it was this one which i was looking forward to the most. I think i had a perception that this was going to be talking about creating systems to detect and fix issues automatically (as per the session brief), but it wasn’t. David Walker did warn us at the beginning of the presentation that he had picked a wide topic, and that he did. I didnt get anything from the presentation I’m afraid, which is testament to the fact with minus no notes to do with this talk! Sorry!


The Winner is….



So after 6 sessions, my top presentation goes too… well its a tie between ASP.NET MVC Gone Wrong and Performance and Scalability, The Stack Exchange Way. Both were really good solid presentations which I thoroughly enjoyed.

Overall though the day itself was marvellous and i think well received by all present. I will end by saying again a massive thank you to the organisers, sponsors and of course the speakers. DDD10 is what it is not because its free, but because of the community and the guys who take the time to organize it. Thank you 🙂

P.S. Pizza Express was brilliant as well and I met some lovely chaps as well.

Stephen Roberts

Aaron Rhodes

Max Edwards

Simon P Stevens

Dan Kendall

[MVC 3] MvcImage Alpha Released!

As you all know ive been working on an Open Source project which shows you how to handle images using ASP.NET MVC 3. This release now encompasses the last code update as such for this Project to include the functionality to show a collection of Users registered (Using the vanilla Membership).
This collection will show:





The code is now available on Codeplex:


The code is also now available on Github:


I’m now going to write some blog posts to explain the functionality and how i accomplished this to describe the code.

Enhanced by Zemanta

[MVC 3] Images – Downloading Images

UPDATE: I have now combined all my MVC Image Handling  blog posts into a Open Source Project. Feel free to check this out once you have read the post.


Original Blog Post:

The previous posts i have shown you how to upload images, and use JQuery to preview the image. We have also used Entity Framework 4.0 and SQL to save a image as a varbinary data type.

Now I’m going to show you how to download the image, and display it on your view, using a HTML Helper.

Before we start lets think about what we need:

  • HTML Helper Extension to help display the image
  • Controller classes to grab the image
  • Object validation methods

Lets start with the code for the HTML Helper Extension. You should be familiar with how these work now. Again, mine is to accept a model using Lambda expressions:

public static MvcHtmlString DisplayImageFor<TModel, TProperty>    (this HtmlHelper<TModel> helper,
    Expression<Func<TModel, TProperty>> expression, string alt = null,     string action = null string controller= null, string actionParameterName = null,string height = null, string width = null)

    if (String.IsNullOrEmpty(alt)){
        string _name = ExpressionHelper.GetExpressionText(expression);
        alt = helper.ViewContext.ViewData.TemplateInfo.        GetFullHtmlFieldName(_name);

    if (String.IsNullOrEmpty(height)){
        height = "126px";

    if (String.IsNullOrEmpty(width)){
        width = "126px";

        actionParameterName = "id";

    ///---Set the default src settings if null 
 ///--- src element is made up of action, controller and acionParameterName 
 if (String.IsNullOrEmpty(action)){
        action = "GetImage";


    if (String.IsNullOrEmpty(controller)){
        controller = "ImagePreview";

    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression,     helper.ViewData);
    Object value = metadata.Model;
    Type valueType = metadata.Model.GetType();
string src = null;

        src = String.Format(CultureInfo.InvariantCulture,

    var imgBuilder = new TagBuilder("img");

    imgBuilder.MergeAttribute("alt", alt);
    imgBuilder.MergeAttribute("src", src);
    imgBuilder.MergeAttribute("height", height);
    imgBuilder.MergeAttribute("width", width);

    return MvcHtmlString.Create(imgBuilder.ToString(TagRenderMode.SelfClosing));


So in a nutshell:

  1. If the parameters are null we set up the default values for the HTML Elements.
  2. build the metadata from the ViewData dictionary. We can then load the metadata.Model data to an Object, i.e. the value of the model.
  3. We build the src element to include the link of the controller we will build later to get the image.
  4. We use again to build the HTML Elements.
  5. The alt element will end up being the models name if there isn’t a parameter passed, for e.g.
     1: <img width="126" height="126" alt="property.UniqueKey" src="/ImagePreview/GetImage/b8b03b6d-e30c-46d6-9cba-002f3a4699ee"/>


You will notice we have used a static method, ObjectValidation.IsStringType. This has been built to allow me to query the object type. I need this so i can make sure the parameter I’m passing to the controller is a String. Here is how i have implemented this:

public static bool IsStringType(Type type)
    if (type == null)
        return false;

    switch (Type.GetTypeCode(type))
        case TypeCode.String:
            return true;

        case TypeCode.Object:
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                return IsStringType(Nullable.GetUnderlyingType(type));

            return false;


    return false;

Quite  a simple class, which passes the type of the object (Previously we used .GetType() to achieve this), then we test to see if the equals String. If it does, we return true.

The other check is if the object is generic and Nullable, we pass the underlying type back through to the IsStringType method.

We have now built our HTML Helper and our Object Validation method, now onto our GetImage action method we set in the src element.

        #region GetImage
        public ActionResult GetImage(Guid id)
            //Guid ID = new Guid(id); Medium profileimage = new Medium();

            try {
                int count = db.Media.Count(c => c.Unique_Key == id);

                if(count > 0)
                    profileimage =  db.Media.SingleOrDefault(i => i.Unique_Key == id);
                    //--Convert the Image data into Memory. 
 byte[] imagedata = profileimage.Source;
                    return File(imagedata, profileimage.Content_Type, profileimage.File_Name);


                count = 0;
                count = db.Media.Count(c => c.Table_Link == id);

                if (count > 0)
                    profileimage = db.Media.SingleOrDefault(i => i.Table_Link == id);
                    //--Convert the Image data into Memory. 
 byte[] imagedata = profileimage.Source;
                    return File(imagedata, profileimage.Content_Type, profileimage.File_Name);

                return File(new byte[0], null);
            finally {
                if (db != null)




This controller method contains alot of my own bespoke business logic in obtaining the image. Which is why i do 2 checks.

Enhanced by Zemanta

[MVC 3] Upload Image –SQL Server & Entity Framework

UPDATE: I have now combined all my MVC Image Handling  blog posts into a Open Source Project. Feel free to check this out once you have read the post.


Original Blog Post:

The last post i described how to create a HTML Helper for Image Previewing. This time around we will be uploading an image to a Database, which is handled little differently than normal CRUD operations.

The following block of code shows my Create action method within my UserProfile controller:

 1:         public ActionResult Create(UserProfile userprofile,
 2:          HttpPostedFileBase imageLoad2)
 3:         {
 4:             var profileimage = new Medium();
 6:             if (imageLoad2 != null)
 7:             {
 8:                 using (Image img =
 9:                 {
 11:                     //--Initialise the size of the array
 12:                     byte[] file = new byte[imageLoad2.InputStream.Length];
 14:                     //--Create a new BinaryReader and set the InputStream
 //-- for the Images InputStream to the
 16:                     //--beginning, as we create the img using a stream.
 17:                     BinaryReader reader =
                              new BinaryReader(imageLoad2.InputStream);
 18:                     imageLoad2.InputStream.Seek(0, SeekOrigin.Begin);
 20:                     //--Load the image binary.
 21:                     file = reader.ReadBytes((int)imageLoad2.
 23:                     //--Create a new image to be added to the database
 25:                     profileimage.Created_Date = DateTime.Now;
 26:                     profileimage.Source = file;
 27:                     profileimage.File_Size = imageLoad2.ContentLength;
 28:                     profileimage.File_Name = imageLoad2.FileName;
 29:                     profileimage.Content_Type = imageLoad2.ContentType;
 30:                     profileimage.Height = img.Height;
 31:                     profileimage.Width = img.Width;
 32: #if DEBUG
 33:                     profileimage.Record_Status = "T";   //--Testing.
 34: #else
 35:                         profileimage.Record_Status = " ";/--Live.
 36: #endif
 40:                 }
 41:             }
 43:             if (ModelState.IsValid)
 44:             {
 46:                 db.Media.AddObject(profileimage);
 47:                 db.SaveChanges();
 49:                 return RedirectToAction("Index", "Home");
 51:             }
 53:             var viewModel = new UserProfileViewModel
 54:             {
 55:                 UserProfile = userprofile,
 56:                 UserTypes = userTypes
 57:             };
 59:             return View(userprofile);
 60:         }

This method creates has two parameters, the model UserProfile, and the imageLoad2 is the file posted. Have a look at the previous post about building the HTML.

NB: the parameter name imageLoad2 needs to be the name of the input file from the view so that is is bound (using the MVC Model Binding). If you used a different name the parameter would be null.

The method creates a Entity Framework model Medium, which is my class to describe the SQL Table which holds the Images. The images are saved within SQL as (MAX). Quite easy really, create a   to convert the image stream to binary,  then using the EF to the entity set, then save it to the table.

There we have it. Join me next time for downloading the image, using another custom HTML Helper.


Enhanced by Zemanta

[MVC 3] Image Preview –HTML Helpers

UPDATE: I have now combined all my MVC Image Handling  blog posts into a Open Source Project. Feel free to check this out once you have read the post.


Original Blog Post:

In my i showed you how to preview an image using a combination of JQuery/AJAX and controller code behind.

This blog post i will show you how to take that a step further and take the HTML code and generate a nice HTML Helper. HTML Helpers are a nice way of re-using your code for future projects.

Lets take a look at the HTML code we wish to generate on the fly:

<input class="upload" type="file" name="imageLoad2" id="File1"/> <img alt="Preview" id="imgThumbnail2" height="126px" width="126px" /> 

This is the code that our JQuery, plays around with to preview an image. Not a lot of code, but wouldn’t be nice to encapsulate this within an Helper?

Firstly what are helpers? Well all they are is code that returns HTML either as a string or Mvchtmlstring. They are useful where you have a lot of conditional logic, plus they also allow you to pass through your model as LINQ Lambda Expression.  Most of the common ones are scaffolded when you create a CRUD controller, that creates your Controller and View using the default T4 Templates.


Ones like:

  1. Html.EditorFor()
  2. Html.LabelFor()
  3. Html.DropDownListFor()

There are lots of them, check them out using your Razor view.


So, to create my custom  helpers, I’ve created a folder in my Project called Helpers and a static class ImageHelpers . Because we are creating a HTML Helper that works like the ones included in the framework, we need to create them using . So you will notice the first parameter is thisHtmlHelper<TModel> helper which will define this extension method as an extension of HtmlHelper. The rest of the parameters allow us to customise the method if needed.

We also have created the method to allow us to pass the generic model and property types. This is useful so we can pass any of our models through, and later on we will add a new T4 template which includes varbinary in the templating. That is a different post though.

 public static class ImageHelpers {
     public static MvcHtmlString UploadImageFor<TModel, TProperty>
       (this HtmlHelper<TModel> helper,
       Expression<Func<TModel, TProperty>> expression, string id = null,
       string name = null, string cssclass = null, string alt = null,
       string imgId = null, string height = null, string width = null)
         const string type = "file";

         if (cssclass == null)
             cssclass = "upload";

         if (id == null)
             id = "File1";

         if (name == null)
             name = "imageLoad2";

         if (alt == null)
             alt = "Preview";

         if (imgId == null)
             imgId = "imgThumbnail2";

         if (height == null)
             height = "126px";

         if (width == null)
             width = "126px";

         var fileBuilder = new TagBuilder("input");
         var imgBuilder = new TagBuilder("img");
         var mergedBuilder = new TagBuilder("p");

         ///Firstly we build the input tag. //--Add the CSS class. fileBuilder.AddCssClass(cssclass);        
        //--Add the name. fileBuilder.MergeAttribute("name", name);        
        //--Add the id. fileBuilder.MergeAttribute("id",id);        
        //--Add the type. fileBuilder.MergeAttribute("type",type);

        ///Secondly we build the img tag. //--Add the alt. imgBuilder.MergeAttribute("alt", alt);        
        //--Add the id. imgBuilder.MergeAttribute("id", imgId);        
        //--Add the height and width. imgBuilder.MergeAttribute("height", height);        
        imgBuilder.MergeAttribute("width", width);

         ///Merge the two together into a p tag. 
        mergedBuilder.InnerHtml += fileBuilder;        
        mergedBuilder.InnerHtml += imgBuilder;        
        return MvcHtmlString.Create(mergedBuilder.ToString());



So, we use three variables to to build an input, image and paragraph tags. This is a nifty little class that allows us to build HTML Elements, and some methods and properties to allow us to quickly to get our desired result, and we return a once we have built it.

We set the default elements to be the names we use in our JQuery, so that the default logic is applied if we have our jquery-previewimage.js used.

We then add our Html helper to our view (After deleting the original code):

          <div class="editor-label"> @Html.LabelFor(model => model.ProfileImage)         
         </div> <div class="editor-field"> @Html.UploadImageFor(model => model.ProfileImage)         

This will generate the original code as seen here when run:


So there we have it, our own HTML Helper which we can re-use for future projects.