<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Michael De Wildt &#187; ASP.NET MVC</title>
	<atom:link href="http://www.mikeyd.com.au/category/asp-net-mvc/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mikeyd.com.au</link>
	<description>An uber nerd rambling about open source, PHP, Python and whatever I find interesting</description>
	<lastBuildDate>Wed, 04 Jan 2012 22:36:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>ASP.NET MVC &#8211; A Declarative Model Validation Technique</title>
		<link>http://www.mikeyd.com.au/2009/09/18/asp-net-mvc-a-declarative-model-validation-solution/</link>
		<comments>http://www.mikeyd.com.au/2009/09/18/asp-net-mvc-a-declarative-model-validation-solution/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 23:57:13 +0000</pubDate>
		<dc:creator>Mikey</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Attributes]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[Regex]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://www.mikeyd.com.au/?p=55</guid>
		<description><![CDATA[I have been doing a lot of work lately with ASP.NET MVC and found that many of the MVC examples are set up where the server that the web application runs has direct access to a database and use LINQ to SQL style validation. See Nerd Dinner example to see how the Microsoft guys validate. [...]]]></description>
			<content:encoded><![CDATA[<p>I have been doing a lot of work lately with ASP.NET MVC and found that many of the MVC examples are set up where the server that the web application runs has direct access to a database and use LINQ to SQL style validation. See <a href="http://nerddinner.codeplex.com/">Nerd Dinner</a> example to see how the Microsoft guys validate.</p>
<p>My application cannot use the Nerd Dinner example because my front end IIS server does not have direct access to a database (Or in my case CICS mainframe!). So I needed a simple declarative way of validating my data before I sent it off to a web service to be inserted into the mainframe.</p>
<p>So, using attributes, reflection and a little help from a colleague of mine, I came up with this solution. The main algorithm in the solution is an extension method that attaches itself to the FormCollection class used by MVC. The method iterates through each method attribute attached to the properties of a given class. Inside each attribute is a validation technique that is applied to the data stored in the FormCollection, if the validation fails a model error is added to the model state.</p>
<pre class="code"><span style="color: blue">public static void </span>Validate(<span style="color: blue">this </span><span style="color: #2b91af">FormCollection </span>fc, <span style="color: #2b91af">Type </span>t, <span style="color: #2b91af">ModelStateDictionary </span>msd)
{
    <span style="color: blue">foreach </span>(<span style="color: #2b91af">PropertyInfo </span>pi <span style="color: blue">in </span>t.GetProperties())
    {
        <span style="color: blue">foreach </span>(<span style="color: #2b91af">ValidatorAttribute </span>attr <span style="color: blue">in </span>pi.GetCustomAttributes(<span style="color: blue">typeof </span>(<span style="color: #2b91af">ValidatorAttribute</span>), <span style="color: blue">true</span>))
        {
            msd.SetModelValue(attr.Name, fc.GetValue(attr.Name));
            <span style="color: green">//ignore attributes that are not in the value list
            </span><span style="color: blue">bool </span>attrInValueList = (<span style="color: blue">from </span>key <span style="color: blue">in </span>fc.Keys.Cast&lt;<span style="color: blue">string</span>&gt;()
                                    <span style="color: blue">where </span>key.Equals(attr.Name)
                                    <span style="color: blue">select </span>key).Count() &gt; 0;
            <span style="color: blue">if </span>(attrInValueList &amp;&amp; !attr.Validate(fc))
                msd.AddModelError(attr.Name, attr.ErrorMessage);
        }
    }
}</pre>
<p>As mentoned, the validation algorithm uses attributes attached to the properties of a model. The validation attributes are simple static classes that are initialised with the name of the property, an error message to display and any extra parameters that are necessary. Below is an example of regular expression and date validation attributes.</p>
<pre class="code"><span style="color: blue">public abstract class </span><span style="color: #2b91af">ValidatorAttribute </span>: <span style="color: #2b91af">Attribute
</span>{
    <span style="color: blue">protected </span>ValidatorAttribute(<span style="color: blue">string </span>name, <span style="color: blue">string </span>errorMessage)
    {
        Name = name;
        ErrorMessage = errorMessage;
    }
    <span style="color: blue">public string </span>Name { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>ErrorMessage { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public abstract bool </span>Validate(<span style="color: #2b91af">FormCollection </span>fc);
}
<span style="color: blue">public class </span><span style="color: #2b91af">RegexValidatorAttribute </span>: <span style="color: #2b91af">ValidatorAttribute
</span>{
    <span style="color: blue">public </span>RegexValidatorAttribute(<span style="color: blue">string </span>name, <span style="color: blue">string </span>regex, <span style="color: blue">string </span>errorMessage)
        : <span style="color: blue">base</span>(name, errorMessage)
    {
        Regex = regex;
    }
    <span style="color: blue">public string </span>Regex { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public override bool </span>Validate(<span style="color: #2b91af">FormCollection </span>fc)
    {
        <span style="color: blue">if </span>(fc[Name] == <span style="color: blue">null</span>)
            <span style="color: blue">return false</span>;

        <span style="color: blue">return new </span><span style="color: #2b91af">Regex</span>(Regex).Match(fc[Name].Trim()).Success;
    }
}
<span style="color: blue">public class </span><span style="color: #2b91af">DateValidatorAttribute </span>: <span style="color: #2b91af">ValidatorAttribute
</span>{
    <span style="color: blue">public </span>DateValidatorAttribute(<span style="color: blue">string </span>name, <span style="color: blue">string </span>errorMessage)
        : <span style="color: blue">base</span>(name, errorMessage) { }
    <span style="color: blue">public override bool </span>Validate(<span style="color: #2b91af">FormCollection </span>fc)
    {
        <span style="color: #2b91af">DateTime </span>d;
        <span style="color: blue">return </span><span style="color: #2b91af">DateTime</span>.TryParse(fc[Name], <span style="color: blue">out </span>d);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Now all I did was apply these validation attributes to the properties of my model that I wanted to validate. A big note here is that the name passed as a parameter to the validation attribute must match the name of the property to be validated.</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">Client
</span>{
    [<span style="color: #2b91af">RegexValidator</span>(<span style="color: #a31515">"FirstName"</span>, <span style="color: #a31515">@"^([a-zA-Z0-9\s\-]{0,12})$"</span>, <span style="color: #a31515">"Please enter a valid first name."</span>)]
    <span style="color: blue">public string </span>FirstName { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }

    [<span style="color: #2b91af">RegexValidator</span>(<span style="color: #a31515">"FamilyName"</span>, <span style="color: #a31515">@"^([a-zA-Z0-9\s\-]{0,18})$"</span>, <span style="color: #a31515">"Please enter a valid family name."</span>)]
    <span style="color: blue">public string </span>FamilyName { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }

    [<span style="color: #2b91af">DateValidator</span>(<span style="color: #a31515">"DateOfBirth"</span>, <span style="color: #a31515">"Please enter a valid date of birth."</span>)]
    <span style="color: blue">public string </span>DateOfBirth { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Finally, to validate your form collection all you need to do is the following. Again the keys in the form collection must match the properties of the model that is being validated.</p>
<pre class="code">collection.Validate(<span style="color: blue">typeof</span>(<span style="color: #2b91af">Client</span>), ViewData.ModelState);
<span style="color: blue">if </span>(ViewData.ModelState.IsValid)
    UpdateModel(client, collection.ToValueProvider());</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>That&#8217;s it! Now I can clearly see in one location, the model, what the validation requirements of each property are and easily adjust them if need be. The same validation algorithm and validation attributes can be used for any model!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikeyd.com.au/2009/09/18/asp-net-mvc-a-declarative-model-validation-solution/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Custom Helper &#8211; A HttpRequest extension method</title>
		<link>http://www.mikeyd.com.au/2009/08/31/asp-net-mvc-httprequest-helper/</link>
		<comments>http://www.mikeyd.com.au/2009/08/31/asp-net-mvc-httprequest-helper/#comments</comments>
		<pubDate>Mon, 31 Aug 2009 06:54:04 +0000</pubDate>
		<dc:creator>Mikey</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.mikeyd.com.au/?p=46</guid>
		<description><![CDATA[Recently I ran into an issue using JQuery’s AJAX library and ASP.NET MVC. Refer to my last post about using JQuery’s AJAX with ASP.NET MVC. After deploying a solution to my web server I had a major issue where my JQuery $.post method was not working and was not giving me any errors. I immediately [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I ran into an issue using JQuery’s AJAX library and ASP.NET MVC. Refer to my <a href="http://www.mikeyd.com.au/?p=39">last post</a> about using JQuery’s AJAX with ASP.NET MVC.</p>
<p>After deploying a solution to my web server I had a major issue where my JQuery $.post method was not working and was not giving me any errors. I immediately thought that there was an error in my server settings or something other then my code because I had no issues in my development environment.</p>
<p>It turned out to be an issue with routing! In my development environment the application was installed under the root directory (‘\’) where as on my server it was installed under a subfolder of the root directory (For example: ‘\test\’) thus the value I coded inside my $.post method was incorrect when deployed to my server.</p>
<p>In order to make it easy for me to deploy to any environment without changing my JQuery method each time I created this simple extension method for the HttpRequest class.</p>
<pre class="brush:csharp">public static class HttpRequestHelper
{
    public static string AppendServerPath(this HttpRequest request, string path)
    {
        return request.ApplicationPath.EndsWith("/")
                   ? request.ApplicationPath + path
                   : request.ApplicationPath + "/" + path;
    }
}</pre>
<p>So now inside my JQuery method all I have to do is call this method and append the exact path I wish to invoke.\</p>
<pre class="brush:javascript">$.post("&lt;%=Request.AppendServerPath("Test/Controller/DoSomething") %&gt;", null, doSomeThing());</pre>
<p>This also worked well inside my Site.Master where I ran into similar issues linking images, style sheets, JavaScript files, etc.</p>
<p>Wherever there is a link in my code I now call this extension method and know it will deploy almost everywhere.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikeyd.com.au/2009/08/31/asp-net-mvc-httprequest-helper/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

