<?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>devermind.com</title>
	<atom:link href="http://devermind.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://devermind.com</link>
	<description>Adrian Grigore's software development weblog. Motto: I will not waste my time looking for a clever motto.</description>
	<lastBuildDate>Sat, 30 Jan 2010 12:00:25 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Visual Studio 2008 randomly hangs when opening .aspx .ascx or .master files</title>
		<link>http://devermind.com/aspnet/visual-studio-2008-randomly-hangs-when-opening-aspx-ascx-or-master-files/</link>
		<comments>http://devermind.com/aspnet/visual-studio-2008-randomly-hangs-when-opening-aspx-ascx-or-master-files/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 13:12:27 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[visual-studio asp.net]]></category>

		<guid isPermaLink="false">http://devermind.com/aspnet/visual-studio-2008-randomly-hangs-when-opening-aspx-ascx-or-master-files/</guid>
		<description><![CDATA[Visual Studio 2008 has been running quite smoothly on my computer until this week. But then it started randomly hanging when opening an .aspx .ascx .master file. The problem even occurred when opening the file in isolation, instead of opening the file as part of a solution. Deactivating all add-ins did not help. 
Fortunately It [...]]]></description>
			<content:encoded><![CDATA[<p>Visual Studio 2008 has been running quite smoothly on my computer until this week. But then it started randomly hanging when opening an .aspx .ascx .master file. The problem even occurred when opening the file in isolation, instead of opening the file as part of a solution. Deactivating all add-ins did not help. </p>
<p>Fortunately It seems I just found the solution: After uninstalling the &#8220;Microsoft Visual Studio Web authoring Component&#8221;, the problem seems have to have disappeared. I&#8217;m not even sure what this component does, but it seems to be a relict from Visual Studio 2005 and so far I have not noticed any missing features since I uninstalled it.</p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/aspnet/visual-studio-2008-randomly-hangs-when-opening-aspx-ascx-or-master-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Tip #4: Client-side form validation made easy &#8211; Part 2</title>
		<link>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2/</link>
		<comments>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 13:00:49 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[client-side form validation]]></category>
		<category><![CDATA[client-side validation]]></category>
		<category><![CDATA[dataannotationsmodelbinder]]></category>
		<category><![CDATA[form validation]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery.validate]]></category>
		<category><![CDATA[remote validation]]></category>
		<category><![CDATA[xVal]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=219</guid>
		<description><![CDATA[In my previous article about ASP.NET MVC Client-Side validation, I showed how to set up your project so that you don&#8217;t have to write any custom JavaScript code for any new validation rules. This approach also covered remote client-side  validation  &#8211; these are rules which require server-side resource in order if a particular [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://devermind.com/aspnet-mvc/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/">previous article</a> about ASP.NET MVC Client-Side validation, I showed how to set up your project so that you don&#8217;t have to write any custom JavaScript code for any new validation rules. This approach also covered remote client-side  validation  &#8211; these are rules which require server-side resource in order if a particular input field is valid or not.</p>
<p>Since I wrote the first part of the article, Steve Sanderson adopted my idea of automatic client-side validation and baked a similar feature right into the latest version of <a href="http://xval.codeplex.com/">xVal</a>. </p>
<p>One important thing is still missing though: What do you do when validation depends on server-side resources but also involves several different form fields? For example, let&#8217;s assume you were implementing a form for your website users to update their contact information. </p>
<p><span id="more-219"></span></p>
<p><strong>Figure 1 &#8211; Example update form</strong><br />
<a href="http://devermind.com/wp-content/uploads/2010/01/Figure1.png"><img src="http://devermind.com/wp-content/uploads/2010/01/Figure1.png" alt="Figure1 - Example update form" title="Figure1 - Example update form" width="804" height="240" class="alignnone size-full wp-image-220" /></a></p>
<p>The form is very similar to the signup form from the last part of this article. However this time  instead of adding new data to the database, the user needs to update his e-mail address. Validation still has to check that the e-mail address entered does not already exist yet. However, this time  it should ignore the current user&#8217;s e-mail address. </p>
<p>For example, if the current user&#8217;s e-mail address is adrian@lobstersoft.com, then we still want to accept this as valid input. But if he enters &#8220;john@doe.com&#8221; and that e-mail address is already taken, we want client-side validation to fail. </p>
<p><a href="http://devermind.com/wp-content/uploads/2010/01/Figure2.png"><img src="http://devermind.com/wp-content/uploads/2010/01/Figure2.png" alt="Figure 2 -  Client-side validation in action" title="Figure 2 -  Client-side validation in action" width="788" height="234" class="alignnone size-full wp-image-221" /></a></p>
<p>And all of this should of course work automatically on both the server and client side simply by providing a server-side validation rule and attaching it the Viewmodel:</p>
<p>Listing 1 &#8211; ViewModel with client/server side enabled entity validation attribute</p>
<pre class="brush: csharp;">
    [EmailUnique]
    public class UserModel
    {
        public int ID{ get; set;}

        [Required(ErrorMessage = &quot;E-mail address is missing.&quot;)]
        [RegularExpression(EmailRegEx, ErrorMessage = &quot;Invalid e-mail address.&quot;)]
        [EmailUnique]
        public string Email { get; set; }

        public class EmailUniqueAttribute : RemoteEntityValidator
        {
            public EmailUniqueAttribute()
                : base(new string[] { &quot;Email&quot;, &quot;ID&quot; }, typeof(User))
            {
                ErrorMessage = &quot;Someone else has already signed up with this e-mail address.&quot;;
            }

            protected override bool EntityValid(object value)
            {
                User entity = (User)value;
	      //make sure there is no user with a different ID but same e-mail address
                return !new FakeUsersRepository().LoadAll().Any(u =&gt; u.ID != entity.ID &amp;&amp; u.Email == entity.Email);
            }
        }

	// Other UserModel properties and validation attributes...
}
</pre>
<h2>Behind the scenes</h2>
<p>Validation of the e-mail input on this form depends on two variables: The user&#8217;s e-mail address and his user ID. </p>
<p>Therefore we need to:</p>
<p>1. Store the user id as a hidden form input field<br />
2. Provide a client-side Javascript function that creates a remote validation rule that submits all relevant form input fields for the particular validation rule to the server.<br />
3. Provide a server-side action method that triggers the validation attribute&#8217;s IsValid method and returns the result to the client-side remote validator. </p>
<p>The approach is quite similar to remote property validation, except that multiple form input fields have to be provided to the server, but there are also a few other other minor differences. For  example the client-side remote validation rules must also be re-validate when one of the other form input elements that validation depends on is changed.  </p>
<p>But the good news is that all of this can be still solved in a generic way so that you can get away just by coding your server-side data annotation validation attributes &#8211; Very similar to the technique shown in the first part of this article. </p>
<h2>Using the RemoteEntityValidator</h2>
<p>For using the code provided with this article in your own project, proceed as follows: </p>
<p>1. Add Xval, jquery.validate, DataAnnotationModelBinder and the code provided in this article&#8217;s demo project to your project as shown in the first part of this article.<br />
2. Next, whenever you need to write a validation attribute that depends on multiple properties of your view model, derive your validation attribute from RemoteEntityValidator as shown in Listing 1. </p>
<p>These are the differences you have to mind in comparison to the RemotePropertyValidator from the first part of the article:</p>
<p>• The RemoteEntityValidator&#8217;s constructor takes one more variable than the RemotePropertyValidator: A string array of all property names in the ViewModel which are relevant for running the validation rule. I guess this could also be done in a more type-safe way by using Linq expressions, but I chose strings for the sake of a simpler syntax, especially when handling many different form fields. </p>
<p>• Note that even though the RemoteEntityValidator depends on several model properties, you must not apply it to all relevant properties in your model. Just apply it to the ViewModel entity and the property that corresponds to the html input element where you want the client-side validation error to appear. However, you do have to apply it both to the ViewModel property AND to the ViewModel class. The property-level attribute is needed for the triggering client side validation when the input element is changed, and the entity-level attribute is needed for server side validation to work. </p>
<p>• Your html form needs to have an ID attribute. It could be done without, but in my project this led to some problems with client-side validation when the form was reloaded via ajax. That&#8217;s why I changed the client-side code for retrieving form input values to something more stable since posting the first part of this article.  </p>
<p><a href='http://devermind.com/wp-content/uploads/2010/01/RemoteValidation.zip'><strong>Download the demo project</strong></a></p>
<h2>Conclusion</h2>
<p>You have learned how to implement client- and server-side validation in a completely generic, model-oriented way. This part of the article completed the technique shown before with validation attributes that depend on several model properties. </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2fwp-admin%2fpost.php%3faction%3dedit%26post%3d219%26message%3d1"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2fwp-admin%2fpost.php%3faction%3dedit%26post%3d219%26message%3d1" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/ASPNET-MVC-Tip-4-Client-side-form-validation-made-easy-Part-2-devermindcom"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdevermind.com%2Faspnet-mvc%2Fasp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2%2F" style="border:0px"/></a></p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Tip #3: Client-side form validation made easy &#8211; Part 1</title>
		<link>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/</link>
		<comments>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/#comments</comments>
		<pubDate>Sun, 21 Jun 2009 11:00:58 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[client-side form validation]]></category>
		<category><![CDATA[client-side validation]]></category>
		<category><![CDATA[dataannotationsmodelbinder]]></category>
		<category><![CDATA[form validation]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery.validate]]></category>
		<category><![CDATA[remote validation]]></category>
		<category><![CDATA[xVal]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=152</guid>
		<description><![CDATA[Client-side form validation has become a de-facto standard for modern web applications. However, replicating server-side validation rules on the client side can be a tedious and error-prone process. 
In addition, there are some validation rules which cannot be checked completely on the client side, for example because the validation depends on information stored in the [...]]]></description>
			<content:encoded><![CDATA[<p>Client-side form validation has become a de-facto standard for modern web applications. However, replicating server-side validation rules on the client side can be a tedious and error-prone process. </p>
<p>In addition, there are some validation rules which cannot be checked completely on the client side, for example because the validation depends on information stored in the server database. For those rules you need to implement remote client-side form validation. </p>
<p>The xVal framework is great for automatic generation of client-side validation code for some of your server-side validation rules, but it does not support remote client-side validation.</p>
<p>This article shows a fully generic way to implement remote client-side form validation so that</p>
<p>• Validation rules remain solely in your ASP.NET MVC model<br />
• You write each validation rule just once, and only in easily testable C# code.  There is no JavaScript or other client-side counterpart .<br />
• There is no need to branch or otherwise modify xVal or jquery.validate<br />
• All you have to do for each new remote form validation rule is to derive from the base class shown in this article.</p>
<p>I&#8217;ll describe how to implement this in detail. I&#8217;ve also uploaded a demo project showing how this works in action. </p>
<p><span id="more-152"></span></p>
<h2>A brief example</h2>
<p>Let&#8217;s assume you are implementing a website signup form. For the sake of simplicity, lets limit the form to asking for an e-mail address and a password. </p>
<p><strong>Figure 1 &#8211; Example signup form</strong></p>
<p><a href="http://devermind.com/wp-content/uploads/2009/06/emptyform.png"><img src="http://devermind.com/wp-content/uploads/2009/06/emptyform.png" alt="emptyform" title="emptyform" width="585" height="186" class="alignnone size-full wp-image-154" /></a></p>
<p>You want to implement the signup form with both client and server side validation. For the e-mail field, let&#8217;s enforce the following validation rules:</p>
<p>1. Email address is not missing<br />
2. Email address looks valid<br />
3. There is no other user with the same e-mail address in your database. </p>
<p>Rules  1 and 2 can easily be checked on the client side. However, rule 3 can only be done with remote validation: Your client-side validation script needs to connect to your web server and ask if the e-mail address is already taken. </p>
<p>In our example, the only user already in the databse shall be adrian@lobstersoft.com. As soon as someone enters this e-mail address in the form and hits tab, return, or the Create button, an error message should appear before the form has even been posted:</p>
<p><strong>Figure 2 &#8211; Error messages should appear before the form has even been posted</strong></p>
<p><a href="http://devermind.com/wp-content/uploads/2009/06/errorform.png"><img src="http://devermind.com/wp-content/uploads/2009/06/errorform.png" alt="errorform" title="errorform" width="613" height="197" class="alignnone size-full wp-image-155" /></a></p>
<p>Listing 1 shows the entire validation logic necessary for both client and server side validation:</p>
<p><strong>Listing 1 &#8211; Signup form client- and server-side  validation rules</strong></p>
<pre class="brush: csharp;">
using System.ComponentModel.DataAnnotations;

namespace RemoteValidation.Models
{
    public class User
    {
        [Required(ErrorMessage = &quot;E-mail address is missing.&quot;)]
        [RegularExpression(EmailRegEx, ErrorMessage = &quot;Invalid e-mail address.&quot;)]
        [IsNew(ErrorMessage = &quot;Someone has already signed up with this e-mail address.&quot;)]
        public string Email { get; set; }

        [Required(ErrorMessage = &quot;Password is missing.&quot;)]
        public string Password { get; set; }

        public class IsNewAttribute : RemotePropertyValidator
        {
            protected override bool PropertyValid(object value)
            {
                return (string)value != &quot;adrian@lobstersoft.com&quot;;
            }
        }

        private const string EmailRegEx = @&quot;^(([^&lt;&gt;()[\]\\.,;:\s@\&quot;&quot;]+&quot;
                                  + @&quot;(\.[^&lt;&gt;()[\]\\.,;:\s@\&quot;&quot;]+)*)|(\&quot;&quot;.+\&quot;&quot;))@&quot;
                                  + @&quot;((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}&quot;
                                  + @&quot;\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+&quot;
                                  + @&quot;[a-zA-Z]{2,}))$&quot;;
    }
}
</pre>
<p>The SignUp action methods should also be easy to implement since the controller does not need to know anything about our validation rules. </p>
<p><strong>Listing 2 &#8211; Signup form action methods</strong></p>
<pre class="brush: csharp;">
         //
        // GET: /Users/SignUp
        public ActionResult SignUp()
        {
            return View(new User());
        }

        //
        // POST: /Users/SignUp
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SignUp(User model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            //Add User to database and start spamming daemon here

            return RedirectToAction(&quot;SignUpComplete&quot;);
        }
</pre>
<p>Lastly, here&#8217;s how the view above is implemented. </p>
<p><strong>Listing 3 &#8211; Signup form view implementation</strong></p>
<pre class="brush: xhtml;">
&lt;%@ Page Title=&quot;&quot; Language=&quot;C#&quot; MasterPageFile=&quot;~/Views/Shared/Site.Master&quot; Inherits=&quot;System.Web.Mvc.ViewPage&lt;RemoteValidation.Models.User&gt;&quot; %&gt;

&lt;asp:Content ID=&quot;Content1&quot; ContentPlaceHolderID=&quot;TitleContent&quot; runat=&quot;server&quot;&gt;
    SignUp
&lt;/asp:Content&gt;
&lt;asp:Content ID=&quot;Content2&quot; ContentPlaceHolderID=&quot;MainContent&quot; runat=&quot;server&quot;&gt;
    &lt;h2&gt;
        SignUp&lt;/h2&gt;
    &lt;%= Html.ValidationSummary(&quot;SignUp was unsuccessful. Please correct the errors and try again.&quot;) %&gt;
    &lt;% using (Html.BeginForm())
       {%&gt;
    &lt;fieldset&gt;
        &lt;legend&gt;Fields&lt;/legend&gt;
        &lt;p&gt;
            &lt;label for=&quot;Email&quot;&gt;
                Enter your e-mail address:&lt;/label&gt;
            &lt;%= Html.TextBox(&quot;Email&quot;)%&gt;
            &lt;%= Html.ValidationMessage(&quot;Email&quot;, &quot;*&quot;)%&gt;
        &lt;/p&gt;
        &lt;p&gt;
            &lt;label for=&quot;Password&quot;&gt;
                Enter a password:&lt;/label&gt;
            &lt;%= Html.Password(&quot;Password&quot;)%&gt;
            &lt;%= Html.ValidationMessage(&quot;Password&quot;, &quot;*&quot;)%&gt;
        &lt;/p&gt;
        &lt;p&gt;
            Hint: To see that remote validation works, try signing up as &quot;adrian@lobstersoft.com&quot;.
        &lt;/p&gt;
        &lt;p&gt;
            &lt;input type=&quot;submit&quot; value=&quot;Create&quot; /&gt;
        &lt;/p&gt;
    &lt;/fieldset&gt;
    &lt;% } %&gt;

    &lt;%= Html.ClientSideValidation&lt;RemoteValidation.Models.User&gt;()%&gt;
&lt;/asp:Content&gt;
</pre>
<p>Note that the View does not contain any JavaScript or other means to specify client-side validation rules. Everything is done transparently and automatically behind the scenes. </p>
<h2>Prerequisites</h2>
<p>In order for this to work, you need to set up a few things first:</p>
<ol>
<li>
Data Annotation validation attributes for server-side validation. IMO this is the best way to handle server-side validation anyway, even if you are not using client-side validation at all. </p>
<p>Brad Wilson has written a great <a href="http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html">blog article</a> on how to use DataAnnotations in ASP.NET MVC.</p>
<p>Note that there is a bug in DataAnnotationModelBinder which might lead to NullReferenceExceptions when using custom ViewModels. This does not become apparent in our demo project, but if you should encounter this problem, you can find a fix in <a href="http://stackoverflow.com/questions/820468/how-does-dataannotationsmodelbinder-work-with-custom-viewmodels">this StackOverflow posting</a>.
</li>
<li>
Download and reference <a href=" http://bassistance.de/jquery-plugins/jquery-plugin-validation/ ">jquery.validate </a>in your Master Page.
</li>
<li>
Download and reference <a href="http://xval.codeplex.com/">xVal</a>  version 0.8 or later in your project. xVal is a great framework for easy implementation of client-side validation in ASP.NET MVC. It transforms standard server-side validation rules into client-side validation rules recognized by jquery.validate. </p>
<p>Steve Sanderson describes how to set it up and use in <a href="http://blog.codeville.net/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/">this blog article</a>.
</li>
</ol>
<p>Once you get this far, you can implement rules 1 and 2 from our example. You could also implement rule 3, although you&#8217;d have to derive it from System.ComponentModel.DataAnnotations.ValidationAttribute, so there would&#8217;t be any client-side validation for that. </p>
<h2>Implementing generic client-side Remote Validation</h2>
<p>While rules 1 and 2 are automagically enforced by xVal on both the client and server side, rule 3 is only checked when the user posts the form. That&#8217;s because xVal does not know what to do with our custom rule. It just looks for standard validation rules like Required, StringLength or RegularExpression and ignores everything else. </p>
<p>Enforcing rule 3 on the client side as well without incurring any additional effort is where the technique I would like to present comes into play.</p>
<p>The first step is not to derive your custom validation rule from ValidationAttribute, but from the RemotePropertyValidator class I implemented. This is already depicted in Listing 1 above. </p>
<p>RemotePropertyValidator is in turn derived from ValidationAttribute, but it also implements xVal&#8217;s ICustomRule interface. This allows it to specify a JavaScript function that should be executed in order to check if the given property is valid on the client side. </p>
<p>RemotePropertyValidator tells xVal to execute the JavaScript function &#8220;RemotePropertyValidation&#8221;. The parameters for this function should be the type of your derived custom validator and the Error message you specified:</p>
<p><strong>Listing 4 &#8211; RemotePropertyValidation class</strong></p>
<pre class="brush: csharp;">
   public abstract class RemotePropertyValidator : ValidationAttribute, ICustomRule
    {
        public CustomRule ToCustomRule()
        {
            return new CustomRule(
                &quot;RemotePropertyValidation&quot;, // JavaScript function name
                new
                    {
                        validator = ToString(),
                        errorMessage = base.ErrorMessage,
                    }, // Params for JavaScript function

                base.ErrorMessage
                );
        }
    }
</pre>
<p>You might be wondering why I am checking for empty  strings / null in Listing 4. That&#8217;s because of differences between how xVal / jquery.validate work on the client side and how the DataAnnotationsModelRunner is implemented on the server side: While it is possible to implicitly implement a Required validator by deriving from ValidationAttribute on the server side, it is not possible to do this with ICustomRule descendents on the client. So I am checking for empty strings / null to avoid inconsistent behaviour. </p>
<p>The ClientSideRegEx property can be set to a regular expression that will be executed on the client before the remote validation is done. You can use it to avoid unnecessary calls to your RemoteValidation controller.</p>
<p>Now, when the user starts typing something in the e-mail field, the browser will execute the JavaScript function &#8220;RemotePropertyValidation&#8221;. Note that this function will receive your derived server-side validator&#8217;s object type and your validator&#8217;s error message  as parameters. </p>
<p>Next, we need to implement a generic RemotePropertyValidation function. In this function we can create a &#8220;remote&#8221; validation rule as supported by jquery.validate and attach it to the Email e-mail input field&#8217;s rules collection:</p>
<p><strong>Listing 5 &#8211; Generic client-side remote validation function</strong></p>
<pre class="brush: javascript;">
function RemotePropertyValidation(value, element, params) {
    var wrappedElement = $(element);
    if (wrappedElement.rules()[&quot;remote&quot;] === undefined) {
        //add optional regEx validator to minimize ajax requests
        if (params.regEx !== null &amp;&amp; wrappedElement.rules()[&quot;xVal_regex&quot;] === undefined) {
            wrappedElement.rules(&quot;add&quot;, {
                xVal_regex: [params.regEx],
                messages: {
                    xVal_regex: params.errorMessage
                }
            });
        }
        var remoteRule =
        //add a new remote validation rule
        wrappedElement.rules(&quot;add&quot;, {
            remote: {
                url: &quot;/RemoteValidation/Property&quot;,
                data: {
                    value: new CreateInputValueAccessor(wrappedElement.attr(&quot;name&quot;)),
                    validator: params.validator
                }
            },
            messages: {
                remote: params.errorMessage
            }
        });

        //validate element again to trigger the new rule(s)
        $(&quot;form&quot;).validate().element(wrappedElement);
    }
    return true;
}

function CreateInputValueAccessor(inputName) {
    return function() {
        return $(&quot;[name=&quot; + inputName + &quot;]&quot;).val();
    };
}
</pre>
<p>The RemotePropertyValidation () function should be referenced in your Master page. Now the first time a user enters something in the Email field , jquery.validate will first validate it using the Required and the Regex rule. If both rules are satisfied, it will check if the e-mail address is already taken with the validation rule that RemotePropertyValidation() inserted on the fly. This will fetch the following URL and parse the JSON reply as validation result.:</p>
<p>http://<Domain>/RemoteValidation/Property?value=<UserInput>&#038;validator=RemoteValidtion.Models.User.IsNew</p>
<p>Now we just need to implement a RemoteValidation that construct an appropriate validator object (note that this is provided in &#8220;validator&#8221; request parameter), let it validate the user input and return the validation result  as JSON: </p>
<p><strong>Listing 6 &#8211; RemoteValidation controller</strong></p>
<pre class="brush: csharp;">
using System;
using System.Reflection;
using System.Web.Mvc;
using RemoteValidation.Models;

namespace RemoteValidation.Controllers
{
    public class RemoteValidationController : Controller
    {
        //
        // GET: /RemoteValidation/Property
        public JsonResult Property()
        {
            Type validatorType = Type.GetType(Request[&quot;validator&quot;], true);
            var validator = (RemotePropertyValidator) Activator.CreateInstance(validatorType);
            return Json(validator.IsValid(Request[&quot;value&quot;]));
        }
    }
}
</pre>
<p>And that&#8217;s it! Now that you have the JavaScript  RemotePropertyValidation function and the remote validation controller in place, all you need to do for new custom validation rules is to derive them from RemotePropertyValidator. This ensures that your validation rules are are automatically enforced on both the server and the client. </p>
<p>For example, all you&#8217;d need to implement for server AND remote client-side validation of password strength is this: </p>
<p><strong>Listing 7 &#8211; Complete implementation of an additional client- and server-side Validator</strong></p>
<pre class="brush: csharp;">
 public class IsSafePasswordAttribute : RemotePropertyValidator
        {

            public IsSafePasswordAttribute()
            {
                //perform some simple password strength check with a regular expression
                //on the client side first
                ClientSideRegEx = &quot;.{8,20}&quot;;
            }

            protected override bool PropertyValid(object value)
            {
                //Insert more elaborate server-side / remote client side password checking
                // logic and return result here...
            }
        }
</pre>
<h2>Caveats</h2>
<p>There are a few things you should keep in mind when using this technique: </p>
<ul>
<li>
You can&#8217;t implicitly implement a Required validator using this technique, so if a property is not optional, you must always decorate it with a Required validator apart from of your own RemotePropertyValidator descendant. It wouldn&#8217;t really make sense to implement a Required validator this way anyway. Please see the Implementation section above if you are interested in the reason for this. </li>
<li>
You can only apply one remote validation rule per form field. This is a limitation of jquery.validate, and it makes sense not to have more than one remote validation rule anyway since you want to minimize the amount of server postbacks as much as possible. If you need to remotely check two different rules on the same property, you can always write a new rule which incorporates both checks, so the only problem is finding an error message that fits both validation rules.
</li>
<li>
This approach only works for Validation Attributes applied to properties, not to entire business entities. I&#8217;ll discuss a similar approach for validating entire business entities in the second part of this article.
</li>
</ul>
<p><a href='http://devermind.com/wp-content/uploads/2009/06/RemoteValidation.zip'>Download the finished demo project </a></p>
<h2>Summary</h2>
<p>Now you know how to implement remote client-side validation without writing any custom JavaScript code.  I discussed how to implement all validation rules, even those that can only be checked on the server, on both the client AND server side in C# code only. I showed how you can do this without any additional effort when implementing new rules. </p>
<p>The only real limitation is that the business rule can check only a single property, not an entire business entity. Stay tuned for the second part of this article, where I&#8217;ll discuss how to circumvent this limitation in a similarly easy way. </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2faspnet-mvc%2fasp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2faspnet-mvc%2fasp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p>
<a rev="vote-for" href="http://dotnetshoutout.com/ASPNET-MVC-Tip-3-How-to-cover-ALL-your-client-side-form-validation-needs-without-writing-any-JavaScript-devermindcom"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdevermind.com%2Faspnet-mvc%2Fasp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1" style="border:0px"/></a></p>
<p><strong>Edit:</strong> The second part of this article has already been posted <a href="http://devermind.com/aspnet-mvc/asp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/aspnet-mvc/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Tip #2: Turn on compile-time View Checking</title>
		<link>http://devermind.com/aspnet/aspnet-mvc-tip-turn-on-compile-time-view-checking/</link>
		<comments>http://devermind.com/aspnet/aspnet-mvc-tip-turn-on-compile-time-view-checking/#comments</comments>
		<pubDate>Sun, 03 May 2009 14:01:32 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[MSBuild]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=139</guid>
		<description><![CDATA[I like the compiler to catch as many errors as possible before I start debugging or release my application. This also applies to code nuggets in ASP.NET MVC views, especially since these are not unit-testable. This article shows how to enable compile-time View checking for ASP.NET MVC projects. ]]></description>
			<content:encoded><![CDATA[<p>I like the compiler to catch as many errors as possible before I start debugging or release my application. This also applies to code nuggets in ASP.NET MVC views, especially since these are not easily unit-testable. But views are not validated at compilation, at least not when using the standard settings for ASP.NET MVC projects.</p>
<p>Tools like Resharper can notify you of syntax errors within your views, but you can still build the project and not get a single error.  Instead, your application will crash when trying to evaluate the buggy view.</p>
<p>Fortunately you can easily make Visual Studio compile your views along with the rest of your code.<span id="more-139"></span> The only downside is that your project will build a bit slower, but if this bothers you during development you can also enable this feature on a per configuration basis.  For example you may want to compile your views in Release mode, but not in your Debug configuration , so you have the extra safety of compile-time view checking before releasing a new version, but you still get lightning-fast compilation times while developing.</p>
<p>Please proceed as follows to turn on compile time view compilation:</p>
<ol>
<li>Open your .csproject or .vbproject file in a text editor of your choice. It’s just a simple xml file, which is why any editor will do fine.</li>
<li>Locate the &lt;PropertyGroup&gt; element that belongs to the configuration you would like to alter.</li>
<li>Within this PropertyGroup, add an additional  element with “true” as its text value.</li>
</ol>
<p>For example, this will turn on view compilation in my project&#8217;s Release configuration:</p>
<pre class="brush: xml;">

&lt;PropertyGroup Condition=&quot; '$(Configuration)|$(Platform)' == 'Release|AnyCPU' &quot;&gt;

&lt;MvcBuildViews&gt;true&lt;/MvcBuildViews&gt;

...
</pre>
<p>That&#8217;s it! The next time one of your views has compile-time errors, these will be reported when building your application.</p>
<p>One last thing: You need to repeat this procedure for all configurations you might create in the future if you want your views to be checked in those configurations as well. Even if you tell Visual Studio to copy settings from an existing configuration where this tag is already set to true, the  MvcBuildViews tag is not copied by Visual Studio.</p>
<p><strong>Edit:</strong> As some readers pointed out, your project&#8217;s compilation time will increase after turning on view compilation. For this reason, I have recently switched it off for the debug configuration of my current project. However, compile-time view compilation is still tremendously useful before releasing a new version. Or perhaps even before submitting a new revision to your source control server. It can catch a lot of different errors this way, especially if you are using the new ASP.NET MVC <a href="http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx">strongly typed Html helpers</a>. </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2flinq%2faspnet-mvc-tip-turn-on-compile-time-view-checking"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2flinq%2faspnet-mvc-tip-turn-on-compile-time-view-checking" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<div class="shoutIt"><a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http://devermind.com/linq/aspnet-mvc-tip-turn-on-compile-time-view-checking"><br />
<img style="border:0px" src="http://dotnetshoutout.com/image.axd?url=http://devermind.com/linq/aspnet-mvc-tip-turn-on-compile-time-view-checking" alt="Shout it" /><br />
</a></div>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/aspnet/aspnet-mvc-tip-turn-on-compile-time-view-checking/feed/</wfw:commentRss>
		<slash:comments>43</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Tip #1: Using Custom ViewModels with POST action methods</title>
		<link>http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods/</link>
		<comments>http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods/#comments</comments>
		<pubDate>Sat, 18 Apr 2009 11:44:27 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[custom]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[viewmodel]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=102</guid>
		<description><![CDATA[One of the top good practices for ASP.NET MVC is not to use the ViewData Dictionary, but to put your data in a strongly typed ViewModel instead. Many people seem to be using Linq to SQL entities as a ViewModel, because it&#8217;s a very comfortable approach. But what do you do if your view should [...]]]></description>
			<content:encoded><![CDATA[<p>One of the top good practices for ASP.NET MVC is not to use the ViewData Dictionary, but to put your data in a strongly typed ViewModel instead. Many people seem to be using Linq to SQL entities as a ViewModel, because it&#8217;s a very comfortable approach. But what do you do if your view should contain data that is not included in any of your linq entities? <a href="http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx">Scott Gu&#8217;s chapter 1 preview of his upcoming ASP.NET MVC book</a> recommends using a custom-shaped ViewModel for those cases.<span id="more-102"></span></p>
<p>One thing that still puzzled me after reading and trying to follow the chapter was how to create complex custom ViewModels (as opposed to putting all data in the ViewData dictionary or using vanilla Linq to SQL entities). Scott mentions on page 107 of the book  that you &#8220;might have the action method update a ViewModel object with the form-posted data, and then use the ViewModel instance to map or retrieve an actual domain model object&#8221;, but there is no actual example of how this would look in source code.</p>
<p>For example, let&#8217;s assume you have an edit action method with the following view:</p>
<p><a href="http://devermind.com/wp-content/uploads/2009/04/form1.png"><img class="alignnone size-full wp-image-103" title="EditForm" src="http://devermind.com/wp-content/uploads/2009/04/form1.png" alt="EditForm" width="274" height="334" /></a></p>
<p>So your edit form displays data coming from a Linq entity representing a customer (FirstName, LastName, Email, Country, AccountType), but you also need SelectLists to populate the Country and AccountType DropDownLists.</p>
<p><strong>The simple, but untyped approach: the ViewData dictionary</strong></p>
<p>The simplest approach is to use the Customer Linq entity as ViewModel and to put the two SelectLists in the ViewData dictionary. This works fine, but I dislike the fact that there is no type-safety for the two SelectLists. Instead you have to use a type cast from object to SelectList:</p>
<pre class="brush: xml;">
&lt;label for=&quot;CountryCode&quot;&gt;Country&lt;/label&gt;&lt;br /&gt;
&lt;%= Html.DropDownList(&quot;CountryCode&quot;,ViewData[&quot;Countries&quot;] as SelectList)%&gt;

&lt;%= Html.ValidationMessage(&quot;CountryCode&quot;, &quot;*&quot;)%&gt;
</pre>
<p><strong>The fully typed approach: Custom ViewModels</strong></p>
<p>So you want fully typed model data, but the linq entity does not hold all the data you need to render the view. Since you don&#8217;t want to clutter my Customer Linq to SQL entity with two properties that return the two SelectLists, the only alternative to get a fully typed view is to use a custom ViewModel:</p>
<pre class="brush: csharp;">public class CustomersFormViewModel
{
public SelectList AccountTypes { get; set; }
public SelectList Countries { get; set; }
public Customer Customer { get; set; }
}</pre>
<p>Note that the ViewModel is not a mere Linq entity anymore. Instead, it contains the one Customer Linq entity instance, plus the two SelectLists for my DropDownLists.</p>
<p>Now you can implement your view without using any typecasts:</p>
<pre class="brush: html;">

&lt;p&gt;

&lt;label for=&quot;Customer.FirstName&quot;&gt;

FirstName:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.TextBox(&quot;Customer.FirstName&quot;)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.FirstName&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;

&lt;p&gt;

&lt;label for=&quot;Customer.LastName&quot;&gt;

LastName:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.TextBox(&quot;Customer.LastName&quot;)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.LastName&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;

&lt;p&gt;

&lt;label for=&quot;Customer.Email&quot;&gt;

Email:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.TextBox(&quot;Customer.Email&quot;)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.Email&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;

&lt;p&gt;

&lt;label for=&quot;Customer.CountryCode&quot;&gt;

Country&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.DropDownList(&quot;Customer.CountryCode&quot;,Model.Countries)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.CountryCode&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;

&lt;p&gt;

&lt;label for=&quot;Customer.AccountType&quot;&gt;

AccountType:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.DropDownList(&quot;Customer.AccountType&quot;,Model.AccountTypes)%&gt;

&lt;%= Html.ValidationMessage(&quot;Customer.AccountType&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;</pre>
<p>I was wondering if the MVC framework can automatically map the form values and reconstruct a CustomersFormViewModel. In other words, can I simply implement a strongly typed POST edit action method and receive a fully populated ViewModel as a parameter like this:</p>
<pre class="brush: csharp;">
//POST: /CustomersController/Edit

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(CustomersFormViewModel model)
{
//validate data, save customer, handle validation errors...
}</pre>
<p>The answer is yes! The MVC framework even maps object hierarchies of any depth as ViewModels.</p>
<p><strong>How not to do it</strong></p>
<p>This is all really easy, but still there were few things that threw me off at the beginning.</p>
<p>The ViewModelBinder only maps properties, not public fields. A ViewModel like this cannot be mapped:</p>
<pre class="brush: csharp;">public class CustomersFormViewModel
{
public electList AccountTypes;
public SelectList Countries;
public Customer Customer;
}</pre>
<p>The names of your POSTed form values must match the object hiearchy you want them to be mapped to. Something like this will not work:</p>
<p style="margin: 0in; font-family: Calibri; font-size: 11pt;">
<pre class="brush: xhtml;">&lt;p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;

&lt;label for=&quot;FirstName&quot;&gt;

FirstName:&lt;/label&gt;&lt;br /&gt;

&lt;%= Html.TextBox(&quot;FirstName&quot;,Model,Customer,FirstName)%&gt;

&lt;%= Html.ValidationMessage(&quot;FirstName&quot;, &quot;*&quot;)%&gt;

&lt;/p&gt;</pre>
<p>In hindsight both restrictions are perfectly logic and reasonable, but it&#8217;s easy enough to do it wrong nevertheless and also quite difficult to figure out what went wrong if binding does not work. Hopefully this article will help you avoid any problems with using Custom ViewModels with POST action methods.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2flinq%2faspnet-mvc-using-custom-viewmodels-with-post-action-methods"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2flinq%2faspnet-mvc-using-custom-viewmodels-with-post-action-methods" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<div class="shoutIt"><a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods"><br />
<img style="border:0px" src="http://dotnetshoutout.com/image.axd?url=http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods" alt="Shout it" /><br />
</a></div>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Beginner&#8217;s Guide</title>
		<link>http://devermind.com/aspnet-mvc/aspnet-mvc-beginners-guide/</link>
		<comments>http://devermind.com/aspnet-mvc/aspnet-mvc-beginners-guide/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 12:19:23 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[guide]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=98</guid>
		<description><![CDATA[I&#8217;ve decided take Microsoft&#8217;s brand new ASP.NET MVC framework for a small test drive by building a small proof of concept application with it. The frame work sure looks promising, even despite it&#8217;s early stage of development and relatively small features as compared to ASP.NET web forms. 
It seems there are no good books available [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve decided take Microsoft&#8217;s brand new ASP.NET MVC framework for a small test drive by building a small proof of concept application with it. The frame work sure looks promising, even despite it&#8217;s early stage of development and relatively small features as compared to ASP.NET web forms. </p>
<p>It seems there are no good books available on the subject yet. The few that are already in stock at Amazon are based on the community preview, and it seems that there have been quite a few changes in the the framework since then. </p>
<p>Fortunately, ScottGu hat just released a free sample chapter of his upcoming &#8220;Professional ASP.NET&#8221; (Wrox) book. It contains a 200-page walkthrough guide on how to build a simple ASP.NET MVC application. </p>
<p>The chapter is available for download <a href="http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx">here</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/aspnet-mvc/aspnet-mvc-beginners-guide/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Interview on Shareware Radio</title>
		<link>http://devermind.com/business/interview-on-shareware-radio/</link>
		<comments>http://devermind.com/business/interview-on-shareware-radio/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 13:03:36 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[Business]]></category>
		<category><![CDATA[games]]></category>
		<category><![CDATA[shareware]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=91</guid>
		<description><![CDATA[Mike Dulin has just published an interview we recorded at last year&#8217;s European Shareware Conference. We talked a bit about shareware games vs. casual games, how I got into the games business and the current market climate in both areas. The Interview is available here.
]]></description>
			<content:encoded><![CDATA[<p>Mike Dulin has just published an interview we recorded at last year&#8217;s European Shareware Conference. We talked a bit about shareware games vs. casual games, how I got into the games business and the current market climate in both areas. The Interview is available <a href="http://www.sharewareradio.com/week090226.htm">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/business/interview-on-shareware-radio/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Updated: Generic base class for LINQ2SQL data layers</title>
		<link>http://devermind.com/linq/updated-generic-base-class-for-linq2sql-data-layers/</link>
		<comments>http://devermind.com/linq/updated-generic-base-class-for-linq2sql-data-layers/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 14:23:32 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[DAL]]></category>
		<category><![CDATA[multi-tier]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=79</guid>
		<description><![CDATA[Hi,
It&#8217;s been a while since I posted the first version of my generic base class for LINQ2SQL data layers. The idea behind this class was to provide a quick and simple way to implement a repository with LINQ2SQL and therefore also a solid foundation for implementing your n-tier architecture data layer. If you missed the [...]]]></description>
			<content:encoded><![CDATA[<p>Hi,</p>
<p>It&#8217;s been a while since I posted the first version of my generic base class for LINQ2SQL data layers. The idea behind this class was to provide a quick and simple way to implement a repository with LINQ2SQL and therefore also a solid foundation for implementing your n-tier architecture data layer. If you missed the article, you can read more about the base class <a href="http://devermind.com/linq/a-linq-disconnected-mode-abstract-base-class">here</a>.</p>
<p>The version I previously posted has worked fine for me, but it was still lacking a way to retrieve the ID and version attributes of saved entities. Due to a typo, it also did not work with entities that have more than one unique identity column. Thanks to Mike and Fabrizio for pointing out these limitations!</p>
<p>Version 0.2 available here fixes both of these issues:</p>
<p><a href="http://devermind.com/wp-content/uploads/2009/02/repositorybase_demo_02.zip">Download RepositoryBase Demo Website</a></p>
<p><a href="http://devermind.com/wp-content/uploads/2009/02/repositorybase_source_02.zip">Download RepositoryBase Source Code Only</a></p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/linq/updated-generic-base-class-for-linq2sql-data-layers/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>A generic base class for LINQ to SQL Data Layers</title>
		<link>http://devermind.com/linq/a-linq-disconnected-mode-abstract-base-class/</link>
		<comments>http://devermind.com/linq/a-linq-disconnected-mode-abstract-base-class/#comments</comments>
		<pubDate>Mon, 13 Oct 2008 15:04:01 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[DAL]]></category>
		<category><![CDATA[multi-tier]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=29</guid>
		<description><![CDATA[It&#8217;s hard not to fall in love with LINQ to SQL. It provides a type safe, powerful and extremely flexible way to implement data access in .NET applications. And it looks so easy to use in those nifty Microsoft evangelist presentations!
Unfortunately, after having a closer look at LINQ, I found that using LINQ in a [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s hard not to fall in love with LINQ to SQL. It provides a type safe, powerful and extremely flexible way to implement data access in .NET applications. And it looks so easy to use in those nifty Microsoft evangelist presentations!</p>
<p>Unfortunately, after having a closer look at LINQ, I found that using LINQ in a multi-tier application can be quite a struggle. This article shows the typical pitfalls of implementing the data layer with LINQ to SQL and provides an simple, convenient and flexible way to circumvent most of them.<span id="more-29"></span></p>
<p>The generic base class for a LINQ-to-SQL Database Abstraction Layers (DAL) that comes with this article has the following features:</p>
<ul>
<li>Implements the Repository pattern, allowing you to conveniently implement CRUD (Create, Update, Delete) operations with less than ten lines of code per LINQ entity type.</li>
<li>Works seamlessly in disconnected LINQ mode</li>
<li>Supports transparent database updates of LINQ entity hierarchies in one single database roundtrip.</li>
<li>As a convenience feature, it also writes all executed SQL statements to the output console when debugging your application.</li>
</ul>
<p>I&#8217;m going to assume that you have a basic understanding of what LINQ to SQL (also known as DLINQ) does and how it is used. If you don&#8217;t, have a look at this tutorial first and come back to this page to see how to use LINQ to SQL in multi-tier applications.</p>
<p><strong>The Problem</strong></p>
<p>LINQ to SQL is incredibly easy to use if you simply hook your UI layer directly to the database with LinqToDataSource objects. But that&#8217;s not very object-oriented, and certainly not an advisable architecture unless you are coding a quick and dirty application and do not plan on extending it in the long run.</p>
<p>Instead, most developers divide their applications into several layers, for example the following:</p>
<ul>
<li>Data Access Layer</li>
<li>Business Layer</li>
<li>UI Layer</li>
</ul>
<p>This is known as a multi-tier database application design. LINQ to SQL would be used in the Data Access Layer.</p>
<p>The problem with LINQ to SQL is that – despite it&#8217;s many advantages – it&#8217;s not very simple to use when implementing the data layer.</p>
<p>Have a look at the following database schema:</p>
<p>As long as you are loading and saving LINQ entities to the same data context instance (this is known as “connected mode”), implementing your Data layer with LINQ is very straightforward.</p>
<p>For example, let&#8217;s fetch the customer entity with ID==1 from the database, change its first name to “Homer” and save it back to the database. In an multi-tier database application the code might be somewhere in the UI or business layer and look like this:</p>
<pre class="brush: csharp;">

//create a new repository instance
CustomersRepository customersRepository = new CustomersRepository();
//load a customer instance and change it's FirstName;
Customer customer = customersRepository.Load(2);
customer.FirstName = &quot;Homer&quot;;
//commmit customer to database
customersRepository.Save(customer);
</pre>
<p>The easiest way to implement the data layer Load and Save functions used above is this:</p>
<pre class="brush: csharp;">
static DataClassesDataContext context=new DataClassesDataContext();
public Customer Load(int CustomerID)
{
return context.Customers.Single(c =&gt; c.ID == CustomerID);
}
public void Save(Customer toSave)
{
context.SubmitChanges();
}
</pre>
<p>This approach is using connected LINQ mode: The data context never goes out of scope, so it can always be reused to save entities to the database which are still connected to it.</p>
<p>Granted, it is convenient and works for the isolated example above, but it has severe concurrency issues because one database context is used for all database operations:<br />
When calling Save(), SubmitChanges commits ALL changed entities, not only those related to the LINQ entity that the Save Method received in the toSave parameter.</p>
<p>But even setting this flaw aside, you can&#8217;t implement the data layer in the same manner when using LINQ in a multi-tier ASP.NET application. Here, chances are that your LINQ entity is loaded with the one page request, then updated and saved to the database with the next page request. Meanwhile, your original data context has gone out of scope, making your LINQ entity disconnected.</p>
<p>And there are also many other scenarios where you need to use disconnected LINQ mode: For example you might want to implement your Database Layer as a web service, commit previously serialized LINQ entities to your database, etc.</p>
<p>Implementing the data layer with disconnected LINQ to SQL</p>
<p>So, how do we implement a Data layer Save() method that works in disconnected LINQ mode?</p>
<p>We have to</p>
<ul>
<li>Detach the entity from the old data context</li>
<li>Create a new data context</li>
<li>Attach the entity to the new context</li>
<li>Submit changes</li>
</ul>
<p>In source code, it looks like this:</p>
<pre class="brush: csharp;">
public Customer Load(int CustomerID)
{
DataClassesDataContext context = new DataClassesDataContext();
return context.Customers.Single(c =&gt; c.ID == CustomerID);
}

public void Save(Customer toSave)
{
//the old data context is no more, we need to create a new one
DataClassesDataContext context = new DataClassesDataContext();
//serialize and deserialize the entity to detach it from the
//old data context. This is not part of .NET, I am calling
//my own code here
toSave = EntityDetacher&lt;Customer&gt;.Detach(toSave);
//is the entity new or just updated?
//ID is the customer table's identity column, so new entities should
//have an ID == 0
if (toSave.ID == 0)
{
//insert entity into Customers table
context.Customers.InsertOnSubmit(toSave);
}
else
{
//attach entity to Customers table and mark it as &quot;changed&quot;
context.Customers.Attach(toSave, true);
}
}
</pre>
<p>Now you can load and alter as many entities as you like and only commit some of them to the database. But due to using disconnected LINQ, this implementation does not account for associations between LINQ entities.</p>
<p>For example, imagine you want to do the following in your business or UI layer:</p>
<pre class="brush: csharp;">
//load currently selected customer from database
Customer customer = new CustomersRepository().Load(1);
//change the customer's first name
customer.FirstName = &quot;Homer&quot;;
//add a new bill with two billingitems to the customer
Bill newbill = new Bill
{
Date = DateTime.Now,
BillingItems =
{
new BillingItem(){ItemPrice=10, NumItems=2},
new BillingItem(){ItemPrice=15, NumItems=1}
}
};
customer.Bills.Add(newbill);
//create a new provider to simulate new ASP.NET page request
//save the customer
new CustomersRepository().Save(customer);
</pre>
<p>The disconnected mode Save() method above would commit the change to the FirstName column, but simply forget about the new bill and billing items. In order to make it work, we also need to recursively Attach or Insert all associated child entities:</p>
<pre class="brush: csharp;">

public void Save(Customer toSave)
{
//the old data context is no more, we need to create a new one
DataClassesDataContext context = new DataClassesDataContext();
//serialize and deserialize the entity to detach it from the
//old data context. This is not part of .NET, I am calling
//my own code here
toSave = EntityDetacher.Detach(toSave);
//is the entity new or just updated?
//ID is the customer table's identity column, so new entities should
//have an ID == 0
if (toSave.ID == 0)
{
//insert entity into Customers table
context.Customers.InsertOnSubmit(toSave);
}
else
{
//attach entity to Customers table and mark it as &quot;changed&quot;
context.Customers.Attach(toSave, true);
}
//attach or save all &quot;bill&quot; child entities
foreach (Bill bill in toSave.Bills)
{
if (bill.ID == 0)
{
context.Bills.InsertOnSubmit(bill);
}
else

{
context.Bills.Attach(bill, true);
}
//attach or save all &quot;BillingItem&quot; child entities
foreach (BillingItem billingitem in bill.BillingItems)
{
if (bill.ID == 0)
{
context.BillingItems.InsertOnSubmit(billingitem);
}
else
{
context.BillingItems.Attach(billingitem, true);
}
}
}
}
</pre>
<p>Not very complicated, but a lot of typing. And that&#8217;s only for a trivial database scheme and one single entity type. Imagine you were implementing the database layer for several dozen entity types with a few dozen foreign key relationships. You would have to write dozens of nested foreach loops for every single LINQ entity you need a DAL Repository class for. This is not only tedious, but also error-prone. Whenever you add a new table, you&#8217;d have to add a few dozen foreach loops to various DAL Repository classes.</p>
<p><strong>How I avoided all these problems</strong></p>
<p>After quite a bit of online research, I implemented a class called RepositoryBase that you can use to quickly implement your data layer that works fine with the examples shown above.</p>
<p>In order to use it, you must first instruct the Object Relational Mapper to generate serializable LINQ entities: Open your dbml file in Visual Studio, left-click somewhere in the white area, and set “Serialization Mode” to “Unidirectional” in the “Properties” panel:</p>
<p><a href="http://devermind.com/wp-content/uploads/2008/10/linq-dal-base-class_html_m2847c2b7.png"><img class="alignnone size-medium wp-image-40" title="linq-dal-base-class_html_m2847c2b7" src="http://devermind.com/wp-content/uploads/2008/10/linq-dal-base-class_html_m2847c2b7.png" alt="" width="254" height="300" /></a></p>
<p>Now you can derive from RepositoryBase to implement your own Repository:</p>
<pre class="brush: csharp;">public class CustomersRepository :
//derive from RepositoryBase with the entity name and
//data context as generic parameters
DeverMind.RepositoryBase
{
override protected Expression&lt;Func&lt;Customer, bool&gt;&gt; GetIDSelector(int ID)
{
//ID needs to be the entity's ID column name
return (Item) =&gt; Item.ID == ID;
}
}
public partial class Customer
{
public static RepositoryBase CreateRepository()
{
//create and return an instance of this entity type's repository
return new CustomersRepository();
}
}</pre>
<p>Do this for each of your entity types, and you have a data layer working seamlessly in disconnected mode. Your derived Repository classes automatically implement the following methods:</p>
<p><a href="http://devermind.com/wp-content/uploads/2008/10/providerbase-interface.png"><img class="alignnone size-medium wp-image-41" title="providerbase-interface" src="http://devermind.com/wp-content/uploads/2008/10/providerbase-interface.png" alt="" width="178" height="300" /></a></p>
<p>As a small bonus, you can also see the SQL commands that were run against the database by ProviderBase in your debug output console when debugging your application. Thanks to Kris Vandermotten for the handy DebuggerWriter component, which is used by RepositoryBase for the SQL debug output!</p>
<p><strong>There&#8217;s no free lunch&#8230;</strong></p>
<p>There is no significant performance penalty for the Load operations, but there is a bit of reflection going on behind the scenes when you are calling the Save or Delete<br />
methods.</p>
<p>For the vast majority of your DAL needs, this probably has no significant impact on your application either. However, if you are performing a lot of update / insert / delete operations, especially with lots of nested child entities involved, then you might want to hand-code your own Save / Delete functions for the Repository classes of those child applications as described above. All Save / Delete functions are virtual, so you can easily override them.</p>
<p>Also, please note that RepositoryBase does not support recursive save or delete operations with circular dependencies.</p>
<p><strong>Conclusion</strong></p>
<p>This article and the included source code provide a simple, convenient and extensible way to implement your multi-tier LINQ data layer CRUD methods. It works in disconnected mode and supports saving and loading of nested child entities. There is a small performance penalty on Save and Load operations, but you can override those for those Repositories where Save or Load performance is critical.</p>
<p>For everything else, you&#8217;re good to go with just a few lines of code.</p>
<p><strong>Source Code</strong></p>
<p>The updated source code for this article can be found <a href="http://devermind.com/linq/updated-generic-base-class-for-linq2sql-data-layers">here</a>.</p>
<p><strong>Feedback Wanted!</strong></p>
<p>Thanks for your interest in this article. If you have any hints, questions or suggestions, please let me know. I&#8217;m using this class on a daily basis and am therefore always interested on how to improve it even further.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fdevermind.com%2flinq%2fa-linq-disconnected-mode-abstract-base-class"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fdevermind.com%2flinq%2fa-linq-disconnected-mode-abstract-base-class" border="0" alt="kick it on DotNetKicks.com" /></a><br />
<a rev="vote-for" href="http://dotnetshoutout.com/A-generic-base-class-for-ASPNET-Webforms-LINQ-to-SQL-Data-Layers-devermindcom"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fdevermind.com%2Flinq%2Fa-linq-disconnected-mode-abstract-base-class" style="border:0px"/></a></p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/linq/a-linq-disconnected-mode-abstract-base-class/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Linq entity Version property in databound controls</title>
		<link>http://devermind.com/linq/linq-entity-version-property-in-databound-controls/</link>
		<comments>http://devermind.com/linq/linq-entity-version-property-in-databound-controls/#comments</comments>
		<pubDate>Fri, 03 Oct 2008 14:39:50 +0000</pubDate>
		<dc:creator>Adrian Grigore</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CSharp]]></category>

		<guid isPermaLink="false">http://devermind.com/?p=24</guid>
		<description><![CDATA[Since I am currently working on a multi-tier ASP.NET application, I frequently have to display Linq entities in data-driven controls such as GridView, DetailView, etc.
Most of my Linq entities have a version attribute to speed up database operations, and sometimes the entities are not only displayed, but also updated and saved back to the database. [...]]]></description>
			<content:encoded><![CDATA[<p>Since I am currently working on a multi-tier ASP.NET application, I frequently have to display Linq entities in data-driven controls such as GridView, DetailView, etc.</p>
<p>Most of my Linq entities have a version attribute to speed up database operations, and sometimes the entities are not only displayed, but also updated and saved back to the database. The first time I tried this, I got the following exception:</p>
<p><strong>A first chance exception of type &#8216;System.Data.Linq.ChangeConflictException&#8217; occurred in System.Data.Linq.dll<br />
</strong></p>
<p>The reason for this is that I was not displaying the version anywhere in the Detailsview. When saving the entity back to the database, the ObjectDataSource created a new entity with default values for all properties that were not bound to any datafields in the DetailsView. So, the entity was re-instantiated with Version==null and when trying to update the database table for the Linq entity, Linq was looking for a row with a 0 version column.</p>
<p>I thought I might work around this by simply version property of the Linq entity to an invisible Column in the Detailsview. But that only gave me a new exception when trying to update the entity:</p>
<p><strong>Sytem. InvalidOperationException: Cannot convert value of parameter &#8216;Version&#8217; from &#8216;System.String&#8217; to &#8216;System.Data.Linq.Binary&#8217;</strong></p>
<p>The reason for this is that the Version attribute in Linq entities is of the type System.Data.Linq.Binary, which can be converted to a string, but not back from string to System.Data.Linq.Binary.</p>
<p>It took me quite a while to find at least some workaround for this problem. A working &#8211; but somewhat awkward &#8211; solution is to create a VersionString propery in each entity:</p>
<pre class="brush: csharp;">
public partial class Customer
{
public string VersionString
{
get { return _Version.TimestampToString(); }
set { _Version = value.StringToTimestamp(); }
}
}

public static class DateTimeExtensions
{
public static string TimestampToString(this Binary binary)
{
return Convert.ToBase64String(binary.ToArray());
}
public static Binary StringToTimestamp(this string s)
{
return new Binary(Convert.FromBase64String(s));
}
}
</pre>
<p>Then I bound the VersionString to a hidden field in the DetailsView and the problem was gone. But this solution is not ideal since it requires the VersionString property to be defined for every single Linq entity type that uses a timestamp.</p>
<p><strong>But wait, there&#8217;s a much easier way</strong>, I stumbled across this solution while playing around with Detailsview a few days ago: Simply add the Version propery to the DataKeyNames property of the DetailsGrid. For example, if your DataKeyNames propery is usually DataKeyNames=&#8221;ID&#8221;, write DataKeyNames=&#8221;ID,Version&#8221; instead.</p>
<p>This way the DetailsView serializes the Version property to it&#8217;s view state and deserializes it again when the entity has to be recreated. No need to fiddle with the VersionString approach above.</p>
]]></content:encoded>
			<wfw:commentRss>http://devermind.com/linq/linq-entity-version-property-in-databound-controls/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
