MVC 4.0: How to support client-side custom validation

mvcI talked about CUSTOM VALIDATION LOGIC  and we saw how to implement custom validation logic to our model classes.

Here we will see how to support client-side validation for our custom validation attribute.

I will start with the solution then I will explain it in details.

    public class MaxWordsAttribute : ValidationAttribute,
                                     IClientValidatable
    {
        public MaxWordsAttribute(int wordCount)
            :base("Too many words in {0}")
        {
            WordCount = wordCount;
        }

        public int WordCount { get; set; }

        protected override ValidationResult IsValid(
            object value,
            ValidationContext validationContext)
        {
            if (value != null)
            {
                var wordCount = value.ToString().Split(' ').Length;
                if (wordCount > WordCount)
                {
                    return new ValidationResult(
                        FormatErrorMessage(validationContext.DisplayName)
                    );
                }
            }
            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
            ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("wordcount", WordCount);
            rule.ValidationType = "maxwords";
            yield return rule;
        }
    }

To support client-side validation, you need your attribute to implement an interface.
The IClientValidatable interface defines a single method: GetClientValidationRules.
When the MVC framework finds a validation object with this interface present, it invokes GetClientValidationRules to retrieve — you guessed it — a sequence of ModelClientValidationRule objects. These objects carry the metadata, or the rules, the framework sends to the client.

If you think about the scenario, there are a few pieces of information you’d need on the client to run the validation:

  • What error message to display if the validation fails (Error Message)
  • How many words are allowed (Validation Parameters)
  • An identifi er for a piece of JavaScript code that can count the words (ValidationType)

The MVC framework takes the rules given back from the GetClientValidationRules method and serializes the information into data dash attributes on the client:

<input
data-val="true"
data-val-length="The field Title must be a string with a maximum length of 160."
data-val-length-max="160"

data-val-maxwords="Too many words in Title"
data-val-maxwords-wordcount="10"

data-val-required="An Album Title is required" id="Title" name="Title"
type="text" value="For Those About To Rock We Salute You" />

Now you have metadata on the client, but you still need to write some script code to execute the validation logic.

You’ll need two pieces of script in place for validation to work:

  • The adapter: The adapter works with the unobtrusive MVC extensions to identify the required metadata. The unobtrusive extensions then take care of retrieving the values from data dash attributes and adapting the data to a format jQuery validation can understand.
  • The validation rule itself: This is called a validator in jQuery parlance.
/// <reference path="jquery-1.6.2.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

if ($.validator && $.validator.unobtrusive) {

    $.validator.unobtrusive.adapters.addSingleVal("maxwords", "wordcount");

    $.validator.addMethod("maxwords", function (value, element, maxwords) {
        if (value) {
            if (value.split(' ').length > maxwords) {
                return false;
            }
        }
        return true;
    });

}

You have four kinds of Adapter Methods (addBool, addSingleValue, addMinMax, add). For the maximum words scenario, you could use either addSingleVal or addMinMax (or add, because it can do anything).

The validator method takes two parameters:

  • The name of the validator, which by convention matches the name of the adapter (which matches the ValidationType property on the server).
  • A function to invoke when validation occurs.

The validator function accepts three parameters and can return true (validation passed) or false (validation failed):

  • The fi rst parameter to the function will contain the input value (like the title of an album).
  • The second parameter is the input element containing the value to validate (in case the value itself doesn’t provide enough information).
  • The third parameter will contain all the validation parameters in an array, or in this case, the single validation parameter (the maximum number of words).

Thank You,
Keep It Simple & Straightforward 🙂
~:H}{H:~

MVC 4.0: CUSTOM VALIDATION LOGIC

The extensibility of the ASP.NET MVC framework means an infinite number of possibilities exist for implementing custom validation logic. However, this post focuses on two core scenarios:

  • Packaging validation logic into a custom data annotation
  • Packaging validation logic into a model object itself

Custom Annotations

Imagine you want to restrict the last name value of a customer to a limited number of words. For example, you might say that 10 words are too many for a last name.

    public class MaxWordsAttribute : ValidationAttribute
    {
        public MaxWordsAttribute(int maxWords)
            :base("{0} has too many words.")
        {
            _maxWords = maxWords;
        }

        protected override ValidationResult IsValid(
            object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                var valueAsString = value.ToString();
                if (valueAsString.Split(' ').Length > _maxWords)
                {
                    var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                    return new ValidationResult(errorMessage);
                }
            }
            return ValidationResult.Success;
        }

        private readonly int _maxWords;
    }

With the validation logic in place, you can apply the attribute to any model property:

    [Required]
    [StringLength(160)]
    [MaxWords(10, ErrorMessage="There are too many words in {0}")]
    public string LastName { get; set; }

Now if the customer types in too many words, he’ll see the message in the following figure in the view.
maxwords validation

IValidatableObject

A self-validating model is a model object that knows how to validate itself. A model object can announce this capability by implementing the IValidatableObject interface.

    public class Order : IValidatableObject
    {
        public IEnumerable<ValidationResult> Validate(
        ValidationContext validationContext)
        {
            if (LastName != null &&
            LastName.Split(' ').Length > 10)
            {
                yield return new ValidationResult("The last name has too many words!",
                new[] { "LastName" });
            }
        }
        // rest of Order implementation and properties
        // ...
    }

This has a few notable differences from the attribute version.

  • The method the MVC run time calls to perform validation is named Validate instead of IsValid, but more important, the return type and parameters are different.
  • The return type for Validate is an IEnumerable instead of a single ValidationResult, because the logic inside is ostensibly validating the entire model and might need to return more than a single validation error.
  • There is no value parameter passed to Validate because you are inside an instance method of the model and can refer to the property values directly.

Many validation scenarios are easier to implement using the IValidatableObject approach, particularly scenarios where the code needs to compare multiple properties on the model to make a validation decision.

Thank you,
Keep It Simple and Straightforward 🙂
~:H}{H:~

MVC 4.0: Normal vs. Ajax Search

I’m reading now Wrox Professional ASP.NET MVC 4.0, this book is really useful that I recommend to read if you want to learn MVC 4.0 and be professional.

Suppose that we have a Home Controller, in the Index View there will be a text box to enter text to search for and a button to view the search result.

We can do that by two ways:

  1. Normal Search
  2. Ajax Search

1. Normal Search

In the Index view we will Create a Form with Text box and a Search button.

@using (Html.BeginForm("Search", "Home", FormMethod.Get))
{

    <h3>Search Music Albums:</h3>
    <input type="text" name="q" />
    <input type="submit" value="Search" />
}

We can use the Html helper method to create the form, When you press the Search button the model binder will pass the text you entered as q parameter to the Search action method located in the Home controller.

        private MusicStoreDBContext storeDb = new MusicStoreDBContext();

        public ActionResult Search(string q)
        {
            var albums = storeDb.Albums.Include("Artist").Where(a => a.Title.Contains(q)).Take(10);
            return this.View(albums);
        }

The Search action method will search our Music Store and get all albums with Title contains the search text and display the result in a new view called Search.

@model IEnumerable<MvcMusicStore.Models.Album>

@{
    ViewBag.Title = "Search";
}

<h2>Search Result</h2>

<table>
    <tr>

        <th>
           Artist
        </th>
        <th>
            Title
        </th>
        <th>
            Price
        </th>

        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>

        <td>
           @item.Artist.Name
        </td>
        <td>
            @item.Title
        </td>
        <td>
            @string.Format("{0:c}", item.Price)
        </td>

    </tr>
}

</table>

In the previous scenario you enter the search text in one view and the result appears in another one.
What if we want to display the search result in the same view??

2. Ajax Search

 

In the Index view we will use the Ajax helper to create Ajax Form.

@using (Ajax.BeginForm("AjaxSearch", "Home",
    new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchResults" }))
{
    <h3>Search Music Albums:</h3>
    <input type="text" name="q" />
    <input type="submit" value="Ajax Search" />
}

<table id="searchResults">

</table>

Note the AjaxOptions parameter with InsertionMode and UpdateTargetId fields.

Lets have a look at AjaxSearch action method.

        private MusicStoreDBContext storeDb = new MusicStoreDBContext();

        public PartialViewResult AjaxSearch(string q)
        {
            var albums = storeDb.Albums.Include("Artist").Where(a => a.Title.Contains(q)).Take(10);
            return this.PartialView(albums);
        }

The Ajax Search uses PartialViewResult to build the search result and place it in the Index view.
The Ajax Search Partial View will only contains a table for listing the search result.

@model IEnumerable<MvcMusicStore.Models.Album>

<table>
    <tr>

        <th>
           Artist
        </th>
        <th>
            Title
        </th>
        <th>
            Price
        </th>

        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>

        <td>
           @item.Artist.Name
        </td>
        <td>
            @item.Title
        </td>
        <td>
            @string.Format("{0:c}", item.Price)
        </td>

    </tr>
}

</table>

Don’t forget to add reference to JQuery Unobtrusive Ajax script file in the _Layout.cshtml.


<script src="~/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>

When you run your application you should have something like that:

search

Thank you and Keep It Simple and Straightforward 🙂
~:H}{H:~

Caller Info In C# 5.0

Here we are with the second new feature in C# 5.0 “Caller Info“.

Lets start with C# evolution chart, then with an example shows How to use Caller Information.

C# Evolution Chart

Caller Information Example

Suppose we have DoSomething method that will do some important thing.

And we need to log some information about Who call it and When.
We can do the following…

    class Program
    {
        static void Main(string[] args)
        {
            InsertLog("Main");
            DoSomething();

            MethodA();

            MethodB();

            Console.ReadLine();
        }

        static void MethodA()
        {
            InsertLog("MethodA");
            DoSomething();
        }

        static void MethodB()
        {
            InsertLog("MethodB");
            DoSomething();
        }

        static void DoSomething()
        {
            // Some important thing will be here.
        }

        static void InsertLog(string methodName)
        {
            Console.WriteLine("{0} called DoSomething at {1}", methodName, DateTime.Now);
            Console.WriteLine("-----------------------------------------------------");
        }
    }

Each time before calling DoSomething we call InsertLog and pass the caller method name for logging.

Now note how we can do the same thing but using the Caller Info. It’s really simple 🙂

    using System.Runtime.CompilerServices;

    class Program
    {
        static void Main(string[] args)
        {
            DoSomething();

            MethodA();

            MethodB();

            Console.ReadLine();
        }

        static void MethodA()
        {
            DoSomething();
        }

        static void MethodB()
        {
            DoSomething();
        }

        static void DoSomething([CallerMemberName] string memberName = "",
                            [CallerFilePath] string sourceFilePath = "",
                            [CallerLineNumber] int sourceLineNumber = 0)
        {
            InsertLog(memberName, sourceFilePath, sourceLineNumber);
            // Some important thing will be here.
        }

        static void InsertLog(string methodName, string sourceFilePath, int sourceLineNumber)
        {
            Console.WriteLine("{0} called methodB at {1}", methodName, DateTime.Now);
            Console.WriteLine("Source file path: {0}", sourceFilePath);
            Console.WriteLine("Source line number: {0}", sourceLineNumber);
            Console.WriteLine("-----------------------------------------------------");
        }
    }

Instead of passing the caller method name we can use CallerMemberName.
Note that InsertLog now exists in only one place DoSomething and now we can know who call DoSomething, the source file path, and the source line number. All without need to do extra work. It’s really amazing and helpful 🙂

You can find here more information about Caller Info and how to use it.

Thank you,

Keep It Simple & Straightforward 🙂

~:H}{H:~

Async & Await in C# 5.0

Most software engineers are used to programming in a linear manner, at least that is how they are taught when they begin their careers.

Linear versus nonlinear code

The following figure assumes that we have an order system in place that will help us to fetch a collection of orders from somewhere.

The flow of an event-based system is such that it fires off a call somewhere and expects the result to be delivered through a raised event, can be visualized like the diagram in the following figure.

Introducing a new pattern

To simulate a small portion of a real order system, the OrderHandler and Order will look like the following:


class Order
{
    public string OrderNumber { get; set; }
    public decimal OrderTotal { get; set; }
    public string Reference { get; set; }
}

class OrderHandler
{
    private readonly IEnumerable _orders;
    public OrderHandler()
    {
        _orders = new[]
        {
            new Order {OrderNumber = “F1”,OrderTotal = 100,Reference = “Filip”},
            new Order {OrderNumber = “F1”,OrderTotal = 100,Reference = “Filip” }
        };
    }

    public IEnumerable GetAllOrders()
    {
        return _orders;
    }
}

As this is about asynchronous programming, we want to have something to ask for in an asynchronous manner. In order to simulate this, we can simply modify GetAllOrders() as follows:

public IEnumerable GetAllOrders()
{
    System.Threading.ManualResetEvent(false).WaitOne(2000);
    return _orders;
}

Now we will  create a new blank Windows 8 Store Application project, then add the following XAML to the MainPage.xaml:


   <Grid.RowDefinitions>

         <ProgressBar.RenderTransform>

   <button></button>

Before we can actually run the application, we need to add some things to the code file as well.

public MainPage()
{
    this.InitializeComponent();
    Information.Text = “No orders have been loaded yet.”;
}

private void LoadOrders_Click(object sender, RoutedEventArgs e)
{
    OrderLoadingProgress.Visibility = Visibility.Visible;
    var orderHandler = new OrderHandler();
    var orders = orderHandler.GetAllOrders();
    OrderLoadingProgress.Visibility = Visibility.Collapsed;
}

Now you can run the application you should see something like the following:

Now when you press the Load orders button, you will notice that you will not see any loading indicator and that the button is left in its pressed state for 2 seconds. This is because we are locking up the application.

In previous C# versions, we could have solved this by wrapping the code in a BackgroundWorker. That when finished would have raised an event in which we had to invoke a delegate in order for us to change the UI. This is a non-linear approach which tends to mess up the readability of the code. In an older application that is not WinRT, using a BackgroundWorker would have looked something like this:

public sealed partial class MainPage : Page
{
    private BackgroundWorker _worker = new BackgroundWorker();
    public MainPage()
    {
        InitializeComponent();
        _worker.RunWorkerCompleted += WorkerRunWorkerCompleted;
        _worker.DoWork += WorkerDoWork;
    }

    void WorkerDoWork(object sender, DoWorkEventArgs e)
    {
        var orderHandler = new OrderHandler();
        var orders = orderHandler.GetAllOrders();
    }

    private void LoadOrders_Click(object sender, RoutedEventArgs e)
    {
        OrderLoadingProgress.Visibility = Visibility.Visible;
        _worker.RunWorkerAsync();
    }

    void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Dispatcher.BeginInvoke(new Action(() =>
            {
                // Update the UI
                OrderLoadingProgress.Visibility = Visibility.Collapsed;
            }));
    }
}

The BackgroundWorker is what is known as event-based asynchronicity, the pattern is called event-based asynchronous pattern (EAP).

In WinRT however, there is no BackgroundWorker so we have to adapt to the new linear approach, which is only a good thing!
Our solution to this is to adapt to the new pattern introduced in .NET 4.5, async & await. When we use async & await, it is mandatory that we are using it together with the task parallel library (TPL).


private async void LoadOrders_Click(object sender, RoutedEventArgs e)
{
    OrderLoadingProgress.Visibility = Visibility.Visible;
    var orderHandler = new OrderHandler();
    var orderTask = Task<IEnumerable>.Factory.StartNew(() =>
        {
            return orderHandler.GetAllOrders();
        });
    var orders = await orderTask;
    Orders.Items.Clear();
    foreach (var order in orders)
        Orders.Items.Add(order);
    OrderLoadingProgress.Visibility = Visibility.Collapsed;
}

We can now run this application and load the orders without the UI locking up and then having a nice list of order numbers presented to us.

Thank you 🙂

Keep It Simple & Straightforward!

~:H}{H:~

Clean Code

I was reading this book ” Prentice Hall Clean Code A Handbook of Agile Software Craftsmanship ” and its really very useful. I recommend you to read it.

Some sentences and phrases that I liked. 🙂

Writing clean code is what you must do in order to call yourself a professional.

There is no reasonable excuse for doing anything less than your best.

“Honesty in small things is not a small thing.”

In our profession, we desperately need all the help we can get. If a clean shop floor reduces accidents, and well-organized shop tools increase productivity, then I’m all for them.

There are two parts to learning craftsmanship: knowledge and work. You must gain the knowledge of principles, patterns, practices, and heuristics that a craftsman knows, and you must also grind that knowledge into your fingers, eyes, and gut by working hard and practicing.

Learning to write clean code is hard work. It requires more than just the knowledge of principles and patterns. You must sweatover it.

You must practice it yourself, and watch yourself fail. You must watch others practice it and fail. You must see them stumble and retrace their steps. You must see them agonize over decisions and see the price they pay for making those decisions the wrong way.

You are reading this book for two reasons. First, you are a programmer. Second, you want to be a better programmer. Good. We need better programmers.

It was the bad code that brought the company down.

Later equals never.

Why does this happen to code? Why does good code rot so quickly into bad code? We have lots of explanations for it.

  • We complain that the requirements changed in ways that thwart the original design.
  • We bemoan يندب يتحسر the schedules that were too tight to do things right.
  • We blather about stupid managers and intolerant customers.

But the fault, dear Dilbert, is not in our stars, but in ourselves.

We are unprofessional.

 

“But wait!” you say. “If I dont do what my manager says, Ill be fired.” Probably not.

Most managers want the truth, even when they don’t act like it. Most managers want good code, even when they are obsessing about the schedule.

They may defend the schedule and requirements with passion; but thats their job. Its your job to defend the code with equal passion.

 

The onlyway to make the deadline—the only way to go fast—is to keep the code as clean as possible at all times.

 

The bad news is that writing clean code is a lot like painting a picture. Most of us know when a picture is painted well or badly. But being able to recognize good art from bad does not mean that we know how to paint. So too being able to recognize clean code from dirty code does not mean that we know how to write clean code!

 

We are Authors, The next time you write a line of code, remember you are an author, writing for readers who will judge your effort.

 

The ratio of time spent reading vs. writing is well over 10:1.

We are constantly reading old code as part of the effort to write new code.

 

Making it easy to read actually makes it easier to write.

 

Leave the campground cleaner than you found it.

 

Thank you and Keep It Simple & Straightforward 🙂

~:H}{H:~

Hands-on labs for Windows 8

ImageImage

Now you can learn to create a Windows Store app using C# and XAML.

The hands-on labs in this package immerse you in Windows 8 app development—specifically, development of a Windows Store app using C# and XAML.

What’s in the package

  • Assets
  • Lab 1 – Creating a Windows Store app
  • Lab 2 – Orientation, snapping, and Semantic Zoom
  • Lab 3 – Searching and sharing
  • Lab 4 – App bars and media capture
  • Lab 5 – Process Lifetime Management
  • Lab 6 – Settings and preferences
  • Lab 7 – Tiles and notifications
  • Lab 8 – The Windows Store APIs

You can download the package from here.

Thank you and Keep It Simple & Straightforward!

~:H}{H:~