How to Change ASP.NET MVC ValidationMessageFor from <span> to <label>

Wednesday, 28 July 2010 11:49 by SyntaxC4

When it comes to providing a more usable interface for your user, I find that labels are the key. Being able to style a label as an error message and position it where you need it for your user is great, the added functionality being, if the user clicks on the label it lands their cursor nicely in the corresponding field [provided you have filled in the ‘for’ attribute].

When it comes to ASP.NET MVC, Microsoft made the choice to go with a <span> tag instead of the <label>.  I’m not sure why they made this decision, and please feel free to comment below if I'm breaking an html rule here, but a label for error validation just seems to be a no brainer to me.

If you feel the same here is a snippet of Code I created to be change a ValidationMessageFor Extension Method into a Method that provides the label error messaging.

     using System;
     using System.Linq.Expressions;
     using System.Text.RegularExpressions;
     using System.Web.Mvc;
     using System.Web.Mvc.Html;
 
     public static class ValidationExtensions
     {
         public static MvcHtmlString ValidationMessageLabelFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, string errorClass = "error")
         {
             string elementName = ExpressionHelper.GetExpressionText(expression);
             MvcHtmlString normal = html.ValidationMessageFor(expression);
             if (normal != null)
             {
                 string newValidator = Regex.Replace(normal.ToHtmlString(), @"<span([^>]*)>([^<]*)</span>", string.Format("<label for=\\"{0}\\" $1>$2</label>", elementName), RegexOptions.IgnoreCase);
 
                 if (!string.IsNullOrWhiteSpace(errorClass))
                     newValidator = newValidator.Replace("field-validation-error", errorClass);
 
 
                 return MvcHtmlString.Create(newValidator);
             }
             return null;
         }
     }
 

I know that Regular Expression can cause some performance issues, and I don’t call myself a RegEx Master, so if you find a more efficient way to do this please Contact Me, and I will be sure to post the code change.

Remember: “friends don’t let friends __doPostBack();”

Happy Coding!

Help Me, Help You… Windows Azure at Tech Days.

Friday, 9 July 2010 17:48 by SyntaxC4

techdays_magnify Today at 5pm I received an important email that I had been waiting for, this email confirmed me as being a Session Leader at Tech Days 2010 in Canada.  This means I will be creating the slides and demos that will appear in the “Using Microsoft Visual Studio 2010 to Build Applications that run on Windows Azure”.  I have been speaking on Windows Azure across Canada, and up until now I’ve been showing off what I wanted to show you, now it’s your turn.

 

It’s a hard knock life, for us

office-space Being a Developer is challenging at times, we have to figure out the problems of the world. Although we all live in the same world, we all face different challenges; currently my challenge is to encompass a little bit of each of your lives into one hour of your time. This leaves me with one question what are the battles you’re going to be taking into the cloud? For this I need your help, Please leave a comment, or Contact me and let me know one thing that you think you can benefit from knowing about Windows Azure.

The Next Generation of Defensive Coding

Tuesday, 6 July 2010 19:46 by SyntaxC4

If you’re a Software Developer, hopefully you understand the concept of Defensive Coding. If you’re not familiar with the term here is a quick example to explain the concept.

public string SomeMethod(string prefix, string rootWord, string suffix)
{
	// Ensure Parameters contain values.
	if(string.IsNullOrEmpty(prefix))
		throw new ArgumentNullException("Prefix cannot be null");

	if(string.IsNullOrEmpty(rootWord))
		throw new ArugmentNullException("RootWord cannot be null");

	if(string.IsNullOrEmpty(suffix))
		throw new ArugmentNullException("Suffix cannot be null");

	return string.Format("{0}{1}{2}", prefix, rootWord, suffix);
}

Defensive coding gives the benefit of ensuring that your method is being used properly by who ever is implementing your code, if the proper requirements aren’t met the code throws an exception and warns the Developer what particular parameters expects in order for the function to complete properly.

This concept has been used for years and has suited its purpose well. However there are certain things that this method doesn’t provide. Wouldn’t it be nice if these conditions could be validated by the IDE, before compiling your project? Enter Code Contracts.

codecontracts_sm Code Contracts were added to .NET 4, but are available to be used in previous versions of the .NET Framework by installing them from the Microsoft DevLabs Project Site. To use Code contracts you will have to Add a Reference to the System.Diagnostics.Contracts namespace.

 

Static Checking which is the feature of Code Contracts that works without explicitly compiling your code [Visual Studio Background Compilation is necessary], is unfortunately only available in Visual Studio 2010. [Aside: I use the term unfortunately here lightly, you really should Upgrade to Visual Studio 2010, Microsoft has done an amazing job, and you won’t be sorry]

To Mimic the code that I’ve shown above, however this time leveraging the Code Contracts.

public string SomeMethod(string prefix, string rootWord, string suffix)
{
	// Ensure Parameters contain values.
	Contract.Assert(!string.IsNullOrEmpty(prefix));
	Contract.Assert(!string.IsNullOrEmpty(rootWord));
	Contract.Assert(!string.IsNullOrEmpty(suffix));

	return string.Format("{0}{1}{2}", prefix, rootWord, suffix);
}

As you can see the implementation is much neater and easier to read than the blocks of if statements.  This is not the only functionality of Code Contracts either, you can let the contract pass the value through by using the Assume Method which assumes that the value is valid. Other Advantages include Code Based Documentation [Outlining what is expected by the method (in Code, because no one likes making XML Comments)], Business Rule Validation, Can be evaluated on TFS Gated Check-in.

Once I start using Code Contracts in more depth, I’ll be sure to start giving you more real life implementation scenarios. As always be sure to check back!

Until then, Happy Coding!

You asked, Microsoft Delivered. Free Time on Windows Azure.

Tuesday, 6 July 2010 17:13 by SyntaxC4

If you were one of the developers at one of my talks that was tempted to try Windows Azure, but didn’t want to pay to give the platform a shot, here is your chance.  Previously, the only way to get some time on Azure was to have an MSDN Subscription but Microsoft noticed that a lot of their audience that wanted to try out the Azure a Platform didn’t have a subscription.

Microsoft has announced the Windows Azure Introductory Special which offers 25 free hours per month on a Small instance, a Web Edition SQL Azure Database, 2 Service Bus connections to AppFabric, and 500MB of Transfers coming to, and going from the Cloud.  This is a fairly decent starting point for someone trying to launch an existing application to Windows Azure.

How do I get started?

If you just came across my blog there are a few posts that you may want to check out to get up to speed on Windows Azure:

You can also get some tools and an a free IDE to help you deploy your project to the cloud.

Where do I sign up?

Head on over to the Windows Azure Offers page, and click the Buy Now button under the Introductory Special.

What do I do next?

Head out to TechDays 2010 for some Training on Windows Azure.

[Update]

The Microsoft DPE Team in Canada is Dedicated to answering your questions about Windows Azure. If you have a question you would like to ask directly to a Microsoft Representative email the Canadian team at

[/Update]

Return of the Energized – MSY-ATL-YYZ

Tuesday, 15 June 2010 19:04 by SyntaxC4

Last week I was in New Orleans, Louisiana with Sean Kearney, Mitch Garvis, John Bristowe, Damir Bersinic, Ruth Morton, Rick Claus and about 10,000 other Developers and IT Pros from across the World. We were all attending TechEd North America a four day Conference put on by Microsoft to train Developers, IT Pros and Managers about new Technologies and Best Practices while using Microsoft Software and Development Tools. I was Particularly interested in attending as many Windows Azure, Windows Phone 7, and Developer Fundamentals sessions as possible.

251 After watching so many keynote addresses of Microsoft Conferences online, it was quite amazing to finally be one of the live audience members on location. I didn’t get the best seat in the house, but it definitely will be an experience I will not soon forget. Outlined in the keynote were many enhancements to Windows Azure, Bing Maps, Office Communication Server, System Center as well as Power Pivot [a new feature in Excel 2010] and Pivot Viewer.

258

The pre-Keynote performance was by a local band which got the crowd Energized, which isn’t an easy task when your audience is full of Developers and IT Pros at 8:30am on a Monday morning.

The keynote, although not a very launch heavy address, was mind blowing.  Watching a keynote via a Browser and a Silverlight video player doesn’t do justice to everything that is going on.  Literally 10,000+ Developers and IT Pros mesmerized by the demos of the tools in which we use in our day to day lives.

 

 

I look forward to attending a future Microsoft Conference, as TechEd 2010 was my first large scale conference.

 

Some advice on attending conferences

Windows Azure Data ContainerFirst off, don’t schedule a block of three conferences over a span of three weeks, not only is it exhausting, but you really don’t get the chance to appreciate each conference, the somewhat blend together. Travelling between Montreal, Regina, and New Orleans was a crazy adventure, and I left little room for fault tolerance, luckily nothing went wrong.

Secondly, Make sure you leave a few hours for the Expo. The Expo is a great resource for swag and other possibly great connections. I didn’t spend nearly enough time collecting free T-shirts (I only got 7 or so), or getting demo software, but I did walk out of the Expo with some great stuff. I also managed to see a Windows Azure Data Center up close and personal, as well as getting to meet many people on the Windows Azure team [Watch for an upcoming blog post on an interview I did with David Robinson of the SQL Azure Team].

Last but not least, follow up! You’re spending a few days at a conference which is an information overload on it’s own. Be sure to note which sessions you liked, and where the resources will be posted so you are able to review the content again. Luckily Microsoft was kind enough to post the sessions publicly on the Microsoft TechEd Website.

One Last Thing

Cory Fowler in a Windows Azure Data Container

I’m in the Cloud, Everybody take a look at me!

About SyntaxC4:

  • Cory Fowler
  • Guelph, Ontario
  • English
  • SyntaxC4

SyntaxC4 Tweets:

Posts by Date:

<<  July 2010  >>
MoTuWeThFrSaSu
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

Archive:

Advertisements:

Tag Cloud:

Favourite Publishers:

Apress Daily Deal
Apress Daily Deal

Blog Roll: