Wednesday, 12 January 2011

Asp.net MVC2 + HTML5 data-* attributes

So you want to add some custom data to a html element to aid your JavaScript development and adding data values to custom attributes is a big no no so what do you do? This is where the new HTML5 data-* comes to your rescue.

The next issue is you can’t use the usual ActionLink method overloads on the html helper as you can’t pass in ‘-‘ into anonymous types because it is a c# reserved character for subtracting!

So on the train home this evening I came up with the following:

public static MvcHtmlString ActionLinkHtml5Data(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes, object htmlDataAttributes)
{
    if (string.IsNullOrEmpty(linkText))
    {
        throw new ArgumentException(string.Empty, "linkText");
    }

    var html = new RouteValueDictionary(htmlAttributes);
    var data = new RouteValueDictionary(htmlDataAttributes);

    foreach (var attributes in data)
    {
        html.Add(string.Format("data-{0}", attributes.Key), attributes.Value);
    }

    return MvcHtmlString.Create(HtmlHelper.GenerateLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, null, actionName, controllerName, new RouteValueDictionary(routeValues), html));
}

And to use it, you already know how to as its the same way as all the other ActionLink overrides which are already available out of the box with an additional parameter which works the same as the htmlattributes parameter.

<%: Html.ActionLinkHtml5Data(“link display”, "Action", "Controller", new { id = Model.Id }, new { @class="link" }, new { extra = “some extra info” })  %>

It worked like a dream.

The issue with the “-“ being reserved has had a work around in MVC 3 by using “_” and then programmatically changing that to being “-“ in the output. I’ve not looked at the implementation but I can’t see how this is much different to what I’ve already achieved simply above.

Please let me know your thoughts.

Tuesday, 23 March 2010

ASP.net MVC – Exe download and file versioning

We use an application at work which is supplied as a single exe file which is downloaded from their website. The issue is the file has always been called application.exe irrespective of the version. With each new version it just gets overridden and keeps the same file name.

We added a request to the manufacturer a request that the file name include the version so we a) know which version we are getting and b) can keep a couple of historical versions locally just in case. However; due to the length of time they have gone for the single filename it is now linked from many different places and they don’t want to break the links.

It got me thinking, this would be ideal for a route in Asp.Net MVC but can you set the route to accept a string “application.exe” and it do as required. The short answer is yes! :-)

The thinking was setup the route for the single filename. This would execute an action on a controller which would go off to a repository, find the latest version file and then return the file as a DownloadResult to throw up the save file dialog. I had a hunt round the internet and found an oldish post by Phil Haack for this kind of thing. I updated it to map to a specific file, for instance on a file share.

public class DownloadResult : ActionResult
{
public string FileLocation { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }

public override void ExecuteResult(ControllerContext context)
{
if (!String.IsNullOrEmpty(FileLocation))
{
context.HttpContext.Response.AddHeader(
"content-disposition", "attachment; filename=" + FileName);
context.HttpContext.Response.ContentType
= ContentType;
}

context.HttpContext.Response.TransmitFile(FileLocation);
}
}



Once you’ve got that sorted all that’s left is to add in the route in your Global.asax …



routes.MapRoute("download", "application.exe",   
new {controller = "Home", action = "Download"});




And tad ta :-)



The other options would be routing / redirecting at the IIS/Apache level, but as a developer this seemed to be the easiest and simplest way to enable data access to help with new version releases.

Wednesday, 17 March 2010

SqlParameterCollection Extension Method AddWithValue

I don’t know why it’s not included in .net 3.5 / c#3 but the recommended way of adding a SQL Parameter to a SqlParameterCollection is to use the AddWithValue method; however, you can’t specify the SqlDbType with any of the overloads. It’s not hard …

    public static class DataAccessExtensions
{
/// <summary>
/// AddWithValue specifiying the <see cref="SqlDbType"/> of the parameter
/// </summary>
/// <param name="collection">The collection to add the parameter to</param>
/// <param name="parameterName">The name of the parameter</param>
/// <param name="value">The value of the parameter</param>
/// <param name="sqlDbType"><see cref="SqlDbType"/> which the SqlCommand is expecting for the created parameter</param>
public static void AddWithValue(this SqlParameterCollection collection, string parameterName, object value, SqlDbType sqlDbType)
{
var result
= new SqlParameter(parameterName, sqlDbType) { Value = value };
collection.Add(result);
}
}



Wednesday, 10 March 2010

Why do you tweet?

When Twitter came out I didn’t really see the point. As it gained in popularity I still didn’t really see the point; other than using up bandwidth. I’m not a big fan of social networking sites. I hate Facebook for a start. I think the layout is counter productive, it changes too often and generally the “apps” it has are pointless. The only reason why I’m signed up to it is some of my friends seem to have lost the ability to use email, in the traditional sense, and it’s the only way to communicate with them anymore.

Anyway, I digress …

After moving jobs back in Oct ‘09 and settling into my new role I started using Asp.Net MVC more as well as other technologies. After reading some of my regular blogs the writers started putting things like “Also follow me on twitter to get up to date posts, thoughts etc.”, so I thought why not; so I signed up.

The next question which hit me was which client to use? Well due to numerous recommendations from friends I decided to go with TweetDeck. It’s great and does what I want it to! It now just sits in my system tray and pops up every so often with little notes :-)

So the main reasons why I tweet?

- To follow some friends
- To follow .Net bloggers to links, trends etc.
- To follow Formula 1 people to keep up to date with the goings on in the sport.
- To follow some diet/health people to help with the WeightWatchers.
- Following on from the last 3 points I subscribe to a few hashtags (#f1 and #aspnet being a couple) for technology, disc golf, formula 1 and Weight Watchers.

And thats it!

I wouldn’t have found a number of blog posts and interesting details without Twitter over the past few months. The other part is the inside information about Formula 1 in the close season which before has not been possible to access, but with more and more drivers and staff using it, it’s been brilliant.

So if you’ve not thought about it before; Why do you tweet?

Monday, 8 March 2010

February Update - “And the winner is … “

… beer this month!

Short update this month;

- Not much lost
- Big beer in take as it was a mates Stag do

Upside; Spring is on it’s way. It’s sunny, although cold, so can go and play disc golf after work. The summer is on it’s way! :-)

Current weight loss (since Aug ‘09) : 16 1/8lbs

Current Status : Bad! (-97.8)
Beers: 490 + 37 = 527
Miles: 183 (gym: 129.5; road: 33) + 7.5 = 190.5
DG Rounds: 75 + 8 = 83
Gym visits: 94 + 5 = 99
Lengths : 56.7 (total: 567) 

Key
Good => Exercise > Beers
Level => Exercise == Beers
Bad => Exercise < Beers