TECH - MyView

Inscribing Programming Notion Into Blog

Some Useful Extension Methods for Enums


MSDN Definition of Enum - The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list. In programming, enums are used pretty heavily for defining constants. While programming I found few very widely used scenarios for which extension methods would make developers life easy.

Parse String to Enum

How often do we need to convert string value to Enum? In my honest opinion, if you are using enums for constants declaration, you would come across to this situation very often. E.g. Consider following scenario -

//Enum Declaration
enum SortOptions
{
    ASC
    , DESC
}
 
//Convert string to enum
string value = "ASC";
SortOptions sort = (SortOptions)Enum.Parse(typeof(SortOptions), value, true);

To achieve same result, we can write an extension method -

public static class StringExtensions
{
    public static Nullable<T> ParseEnum<T>(this string value) where T : struct
    {
        //Check if T is Enum and value is not null and not empty
        if (typeof(T).IsEnum && !string.IsNullOrEmpty(value))
            return (T)Enum.Parse(typeof(T), value, true);
        else
            return null;
    }
}

Parse String to Enum with default value

If given string is not found in Enum collection then it would return default value as specified in input. It is an extension method to be used on Enum.

public static T ParseEnum<T>(this string value, T defaultValue) where T : struct
{
    //Check if T is Enum and value is not null and not empty
    if (typeof(T).IsEnum && !string.IsNullOrEmpty(value))
    {
        T enumValue;
        bool success = Enum.TryParse(value, out enumValue);
 
        if (success)
            return enumValue;
        else
            return defaultValue;
    }
    else
        return defaultValue;
}

Hope it helps and adds value to your programming. Suggestions and comments are most welcome.
Enjoy coding!!!

There are whole bunch of Extension Method available for C#, Javascript etc on ExtensionMethods. Check them out too.


Using Dynamic OrderBy in LINQ


Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic. With LINQ we can query any set of data, apply filter, sort it as long as data represents some collection. E.g. List, Array, Dictionary etc.

Sorting collection using LINQ

Let’s first create a collection of some class and see how order by clause can be applied to it.

class Student
{
    public int RoleNo { get; set; }
    public string Division { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
}

Create List of Student class.

List<Student> students = new List<Student>();
students.Add(new Student { FirstName = "Sachin", LastName = "Muley", RoleNo = 1, Division = "A" });
students.Add(new Student { FirstName = "Rama", LastName = "Reddy", RoleNo = 2, Division = "B" });
students.Add(new Student { FirstName = "Shardul", LastName = "Waikar", RoleNo = 3, Division = "C" });
students.Add(new Student { FirstName = "Jaydeep", LastName = "Chaudhari", RoleNo = 4, Division = "D" });

Let’s write a function which would sort the given list according to given column name.

public IEnumerable<Student> SortList(List<Student> students, string sortOrder)
{
    IEnumerable<Student> sortedCollection = new List<Student>();
 
    if (sortOrder == "FirstName")
        sortedCollection = students.OrderBy(x => x.FirstName);
 
    else if (sortOrder == "LastName")
        sortedCollection = students.OrderBy(x => x.LastName);
 
    return sortedCollection;
}

If you observe in above code, the code would become too messy because of too many if else statements which are necessary because of order by column name. What if there is some method which would convert column name to the correct order by LINQ query.

Signature of OrderBy Extension method in LINQ?

First thing to achieve this thing is to know what is order by clause in LINQ. Taken from MSDN.

public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector
)

It is an extension method. So first parameter to the extension method is nothing but the type instance only. While the second parameter is Fuc<TSource, TKey>. It is A function to extract a key from an element. We are going to write one generic method to return us this function only.

Dynamic OrderBy Func using LINQ Expression Tree for IEnumerable

public static Func<T, dynamic> Construct<T>(string propertyName)
{
    //Resulting function - OrderBy(type => type.PropertyName)
    //Get the property name from given class type
    PropertyInfo property = typeof(T).GetProperty(propertyName);
 
    //Create parameter expression for the given type
    ParameterExpression typeExpression = Expression.Parameter(typeof(T), "type");
 
    //Create property expression for the input property
    MemberExpression propExpression = Expression.Property(typeExpression, property);
 
    //int32, byte etc types need to boxed
    UnaryExpression objectpropExpression = Expression.Convert(propExpression, typeof(object));
 
    //Since the input is Func<,>, compile the expression tree to function
    return Expression.Lambda<Func<T, dynamic>>(objectpropExpression, new ParameterExpression[] { typeExpression }).Compile();
}

Since we made our function generic, it can be used for any type not only for Student class. Let’s use it in our code.

static IEnumerable<Student> SortList(List<Student> students, string sortOrder)
{
    IEnumerable<Student> sortedCollection = students.OrderBy(Construct<Student>(sortOrder));
    return sortedCollection;
}

Our SortList function won’t contain any If Else statement now as it has been taken care in Construct function itself.

var sortedCollection = SortList(students, "FirstName");

Above code would fail if we pass any property name which is not contained in the given type. E.g. If we pass some property name say FullName, the code would break as the FullName property name is not contained in the class. Let’s change our function definition to address this issue.

public static Func<T, dynamic> Construct<T>(string propertyName, string defaultOrderBy)
{
    //Resulting function - OrderBy(type => type.PropertyName)
    //Get the property name from given class type
    PropertyInfo property;
 
    //If given property is not present in the class then use default property
    if (typeof(T).GetProperty(propertyName) == null)
        property = typeof(T).GetProperty(defaultOrderBy);
    else
        property = typeof(T).GetProperty(propertyName);
 
    //Create parameter expression for the given type
    ParameterExpression typeExpression = Expression.Parameter(typeof(T), "type");
 
    //Create property expression for the input property
    MemberExpression propExpression = Expression.Property(typeExpression, property);
 
    //int32, byte etc types need to boxed
    UnaryExpression objectpropExpression = Expression.Convert(propExpression, typeof(object));
 
    //Since the input is Func<,>, compile the expression tree to function
    return Expression.Lambda<Func<T, dynamic>>(objectpropExpression, new ParameterExpression[] { typeExpression }).Compile();
}

SortList function becomes -

static IEnumerable<Student> SortList(List<Student> students, string sortOrder, string defaultOrder)
{
    IEnumerable<Student> sortedCollection = students.OrderBy(Construct<Student>(sortOrder, defaultOrder));
    return sortedCollection;
}

Calling SortList function -

var sortedCollection = SortList(students, "FullName", "FirstName");

Dynamic OrderBy Func using LINQ Expression Tree for IQueryable

public static Expression<Func<T, dynamic>> Construct<T>(string propertyName, string defaultOrderBy)
{
    //Resulting function - OrderBy(type => type.PropertyName)
    //Get the property name from given class type
    PropertyInfo property;
 
    //If given property is not present in the class then use default property
    if (typeof(T).GetProperty(propertyName) == null)
        property = typeof(T).GetProperty(defaultOrderBy);
    else
        property = typeof(T).GetProperty(propertyName);
 
    //Create parameter expression for the given type
    ParameterExpression typeExpression = Expression.Parameter(typeof(T), "type");
 
    //Create property expression for the input property
    MemberExpression propExpression = Expression.Property(typeExpression, property);
 
    //int32, byte etc types need to boxed
    UnaryExpression objectpropExpression = Expression.Convert(propExpression, typeof(object));
 
    //Since the input is Func<,>, compile the expression tree to function
    return Expression.Lambda<Func<T, dynamic>>(objectpropExpression, new ParameterExpression[] { typeExpression });
}

Dynamic OrderBy for multiple columns

What if we want to sort by multiple columns. We would use ThenBy extension method provided by LINQ. Let’s change our sorting function a little.

public IEnumerable<Student> SortList(List<Student> students, string primarySort, params string[] secondarySorts)
{
    //Sort by primary column, we have used IOrderedEnumerable to use ThenBy clause
    IOrderedEnumerable<Student> sortedCollection = students
                                                .OrderBy(Construct<Student>(primarySort));
 
 
    //Sort by all secondayr colummns
    foreach (string secondarySort in secondarySorts)
    {
        sortedCollection = sortedCollection
                                .ThenBy(Construct<Student>(secondarySort));
 
    }
 
    return sortedCollection;
}

Best Way to use this function – Create Extension Method

Create extension method for IEnumerable or IQueryable or IList type whichever you want to use in your project.

public static IEnumerable<T> OrderBy<T>(this List<T> collection, string propertyName, string defaultOrderBy)
{
    //Construct method and sorting code goes here
}

Hope it helps and adds value to your programming. Suggestions and comments are most welcome.
Enjoy coding!!!


Where can I download SQL Server 2014 Upgrade Advisor?


Upgrading your database from earlier version of SQL Server to the newer version? Check for any issues first using SQL Server Upgrade Advisor. SQL Server Upgrade Advisor helps you prepare for upgrades to SQL Server 2014. Upgrade Advisor analyzes installed components from earlier versions of SQL Server, and then generates a report that identifies issues to fix either before or after you upgrade.

If you only want to download the Advisor for SQL Server 2014 and not the management studio, then following URL - would help you. It has all the feature packs available for SQL Server 2014 - Download SQL Server 2014 Feature Packs.

Click on Download button on the page which would open a pop up. You need to install SQLDom as well in order to install Upgrade Advisor -

  1. ENU\x86\SqlDom.msi – 32 bit version of SqlDom
  2. ENU\x64\SqlDom.msi – 64 bit version of SqlDom

Once you install SqlDom, you can download and install Upgrade Advisor which is following file in the same pop up -

  1. ENU\x86\SqlUA.msi - 32 bit version of Upgrade Advisor
  2. ENU\x64\SqlUA.msi - 32 bit version of Upgrade Advisor

Hope this helps.

Enjoy upgrading!!!


Best practice to pass parameter values to JQuery Function/Plugin


As with any other language, function is the most important aspect of JQuery library too. Everyone who is going to use JQuery would end up using functions sooner or later. A function may or may not accept any parameters. One of the most welcomed feature of  .NET 4.0 framework was named arguments. E.g. Consider following C# code -

/// <summary>
/// Validates the input string
/// </summary>
/// <param name="input">Input String</param>
/// <param name="minLength">Min Length</param>
/// <param name="maxLength">Max Length</param>
/// <returns></returns>
public bool ValidateInput(string input, int minLength, int maxLength)
{
    //Validation code
}

The above function accepts three parameters. If we have to call this function, then we would do so as follows -

ValidateInput("Test String", 0, 10);

There is nothing wrong with above code, But if we use named parameters, then the same can be achieved as -

ValidateInput(input: "Test String", minLength: 0, maxLength: 10);

The above two codes would produce the same result, only difference being the readability. Second code is more readable as just by looking at the code we know what value is being passed to what parameter. Also order of parameters do not matter in second call. The same could have been written as follows -

ValidateInput(maxLength: 10, input: "Test String", minLength: 0);

There was one more best feature added with .NET 4.0 framework. It was default parameters. What if I have to pass only input string in above example and rest two parameters should have some default value if not supplied. Then the signature of the function would be -

/// <summary>
/// Validates the input string
/// </summary>
/// <param name="input">Input String</param>
/// <param name="minLength">Min Length</param>
/// <param name="maxLength">Max Length</param>
/// <returns></returns>
public bool ValidateInput(string input, int minLength = 0, int maxLength = 10)
{
    //Validation code
    return true;
}
 
/// <summary>
/// Validate function
/// </summary>
public void Validate()
{
    ValidateInput(input: "Test String");
}

 

Could we implement these two best features in JQuery? Yes we can. That is what we are going to discuss in following secction.

Named Parameters and Default Values for JQuery Function

Let’s consider a JQuery function.

function validateInput(input, minLength, maxLength, maxSpecialCharactersAllowed, maxNumbersAllowed, spaceAllowed) {
    //Some code
};

Above function accepts 6 parameters. Also If I have to call this function then all the six parameters should be passed and also in the same sequence. What if I have to pass only first parameter and last parameter, rest all parameters should have some default value. In order to deal with this, we are going to make use of JQuery.extend() function. With the use of this extend() function provided by JQuery library, our code would become -

function validateInput(options) {
    //Default values
    var defaults = {
        input: "",
        minLength: "0",
        maxLength: "100",
        maxSpecialCharactersAllowed: "0",
        maxNumbersAllowed: "0",
        spaceAllowed: "0"
    };
 
    //Extend the default parameters and mask with given values if any
    var params = $.extend({}, defaults, options);
 
    console.log(params);
};

If you observe above code, the number of input parameters to the function is not six but only one now. The function would accept the input in the form of key, value pair same as we used for C# code in above example.

validateInput({
    input: "Test String",
    minLength: "0",
    maxLength: "50",
    maxSpecialCharactersAllowed: "1",
    maxNumbersAllowed: "2",
    spaceAllowed: "0"
});

We have used nothing but the named parameters. We get two advantages with above approach -

  1. More readability as just by looking at the code we understand what value is getting passed to what parameter.
  2. The sequence of the parameters do not matter. We can pass minLength at the last and spaceAllowed in the first place as long as the name of the parameter is maintained.


Coming back to the JQuery code. We defined default variable in our function which would have default values if none is passed by the user. The syntax is very much like JSON. Then we are merging these default values with the values provided by the caller by using $.extend() function. You can find the complete documentation for $.extend() function at JQuery website. Now I can call this function by passing only the values which are needed for my purpose, rest all parameters for which no value is passed would assume default value as specified in default variable.

validateInput({
    input: "Test String"
});

The above call to the validateInput would be passed only input value, rest all the parameters would assume default values. I have written console.log() method of JQuery to check the values in params after $.extend() is called. console.log() simply writes to the console window provided by the browser. I am using Chrome browser for this example. The screenshot for the console windows is as follows -

image

 

We have passed only input as “Test String”, but still all the parameters have default values. Thus we have used $.extend() method to have named parameters and default values for those named parameters in JQuery. In my programming career so far, I have used this technique to have JQuery functions which in my opinion is one of the best practices for JQuery functions. It not applies to functions but also to the JQuery plugins.

Also it doesn’t matter if you are passing six or more or less parameters to a function. Named parameters and default values always add to the quality of the code. If you do not wish to use default parameters then be it, still you can think of using named parameters. Even if a function is accepting only one parameter, let’s stick to named parameter only.

$(document).ready(function () {
    validateInput({
            input: "Test String",
            minLength: "0",
            maxLength: "55",
            maxSpecialCharactersAllowed: "5",
            maxNumbersAllowed: "10",
            spaceAllowed: "2"
        });
});
 
function validateInput(options) {
    console.log("input - " + options.input);
    console.log("minLength - " + options.minLength);
    console.log("maxLength - " + options.maxLength);
    console.log("maxSpecialCharactersAllowed - " + options.maxSpecialCharactersAllowed);
    console.log("maxNumbersAllowed - " + options.maxNumbersAllowed);
    console.log("spaceAllowed - " + options.spaceAllowed);
};

image

Hope it helps and adds value to your programming. Suggestions and comments are most welcome.
Enjoy coding!!!


Best Solution for Implementing Tag Cloud using JQuery


Every blog, no matter if it is a technology blog or any other topic blog, has TagCloud as indispensable part of it. Tag Cloud gives reader a fair idea as to which topics are trending on that blog. Tag Cloud highlights the tags according to number of articles/post for that tag. If there are 10 articles tagged as MVC and 5 articles tagged as JQuery then tag cloud would highlight MVC more than JQuery. This highlight could be done in various ways – Adjust the Weight/Color/Size of the tag word etc. Number of JQuery solutions are available for implementing this tag cloud. I tried few solutions but the best I found is – JQuery Tag Cloud provided by Adam Groves (a.k.a. addywaddy). I recently implemented Tag Cloud for my Book Reviews website using this JQuery Tag Cloud solution only. It is perhaps the simplest yet very powerful solution for Tag Cloud.

Tag Cloud Basic Set Up

Tag Cloud is nothing but set of HTML links which need to be highlighted depending on number of articles tagged under it. JQuery solution which I am recommending for implementing Tag Cloud requires very basic set up. Only a div or span containing the anchor elements with the “rel” attribute set to the number of articles for that tag.

<div style="margin:5px; border:1px solid black; padding:10px;width:150px" id="tagCloud">
    <a href="http://bookreviews.techmyview.com/tagged/crime" rel="4">Paranormal</a>
    <a href="http://bookreviews.techmyview.com/tagged/murder-mystery" rel="2">Murder Mystery</a>
    <a href="http://bookreviews.techmyview.com/tagged/paranormal" rel="6">Crime</a>
    <a href="http://bookreviews.techmyview.com/tagged/thriller" rel="1">Thriller</a>
    <a href="http://bookreviews.techmyview.com/tagged/fantasy" rel="8">Fantasy</a>
</div>

Then add JQuery and TagCloud.Js reference to the page.

<script src="jquery-1.10.2.min.js"></script>
<script src="TagCloud.js"></script>

TagCloud.js could be downloaded from Jquery.tagcloud.js.

We just need to add following code to the page to get Tag Cloud going.

<script>
    $(document).ready(function () {
        $.fn.tagcloud.defaults = {
            size: { start: 8, end: 20, unit: 'pt' },
            color: { start: '#F78181', end: '#3B0B0B' }
        };
 
        $("#tagCloud a").tagcloud();
    })
</script>

Above code is self-explanatory. In the very first line we are setting default values for the plug-in. And second line just makes the plug-in work. We are done. You can adjust and check the default values at the demo page of this plug in – JQuery Tag Cloud Demo.

image

Other Solutions

This is not the only solution available for Tag Cloud. There are others too. But I preferred this plug-in for it’s simplicity. While I was finding the solution for my need, I stumbled upon two more JQuery Tag Cloud plug-ins -

  1. CSS Globe Tag Cloud – It is second best solution I found. This plug-in offers sorting as well. We can sort the tags alphabetically as well by number of articles. It offers ability to change CSS too. One good thing about this plug-in is, it offers two different styles in which Tag Cloud could be shown – Inline and Block-level. We implemented Block-level tag cloud in our example.
  2. Goat 1000 HTML5 Canvas Cloud – If you wish to show certain amount of animation in your tag cloud then this is the plug-in for you. It uses HTML5 canvas for animation. Number of animations are provided by it.

 

I wanted Tag Cloud to be simpler to implement and easy to read and interpret. If this is what is your requirement then JQuery Tag Cloud provided by Adam Groves is the best solution for you too!!!


Fluent Validation + NInject + MVC - Why & How : Part 2


In the previous article, I had showed how and why to use Fluent Validation framework. Also we learnt how to use it with NInject. Now in this article, let’s learn two most important things -

1. How to use conditional validation

2. Unit test validation rules

Conditional Validation using FluentValidation.Net

It is one of the prominent features of FluentValidation. It lets us do conditional validation. Consider the same model as in the previous article -

public class Student
    {
        public string Name { get; set; }

        public string Email { get; set; }

        public string AddressLine1 { get; set; }

        public string AddressLine2 { get; set; }

        public string City { get; set; }
    }

Now the requirement is, AddressLine1 is not-required field and City is required only when AddressLine1 is not empty. That means If AddressLine1 is present then City is mandatory too. If AddressLine1 is empty then City could be empty too. With Data Annotation attributes it would be very tricky to do. Fluent Validation exposes two very important methods to achieve this – When & Unless. Let’s them into use. If we consider above scenario then our Validator Rules class would be as follows -

public class StudentValidator : AbstractValidator<Student>
    {
        public StudentValidator()
        {
            RuleFor(x => x.Name)
                .NotEmpty()
                .WithMessage("Please enter Name!!!");

 

            RuleFor(x => x.City)
                .NotEmpty()
                .When(x => !string.IsNullOrEmpty(x.AddressLine1));
        }
    }

Observe second rule, We are saying City field is required but only when AddressLine1 is not empty. So easy to do conditional validation. Right?

image

But remember, conditional validation would be performed on server side. It can be modified to be performed on client side. But let’s keep that aside for this article. I would post that part as well very soon. As “when” there is one more helper – “unless”. “unless” works exactly opposite to “when”. So if we were to use unless instead of when in above example, then our code would turn out as follows -

public class StudentValidator : AbstractValidator<Student>
    {
        public StudentValidator()
        {
            RuleFor(x => x.Name)
                .NotEmpty()
                .WithMessage("Please enter Name!!!");

 

            RuleFor(x => x.City)
                .NotEmpty()
                .Unless(x => string.IsNullOrEmpty(x.AddressLine1));
        }
    }

We can perform any complex validation now using this simple lambda expression.

Unit Testing of Validation Rules

Fluent Validation became popular because of one more good feature of it. It is unit testable. In today’s world software engineering, architects emphasize on Automated Unit Testing. You write code once but test it many times that too automatically. We would use NUnit as a unit testing framework. But you can use any other framework as well if you are comfortable with it.

image

For unit testing project we need to add a class library project. Name it as FluentValidationUnitTest. You also need to add NUnit, FluentValidation nuget package to the project and reference of our MVC project as well as we are going to use models and it’s validator for testing. Our test class looks like this -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using FluentValidationMVC5Demo.Models;
using FluentValidation.TestHelper;
using FluentValidation.Validators;

 

namespace FluentValidationUnitTest
{
    [TestFixture]
    public class StudentValidatorUnitTest
    {
        StudentValidator validator;

 

        [SetUp]
        public void Init()
        {
            validator = new StudentValidator();
        }

 

        [Test]

        public void Should_Have_Error_When_Name_IsNull()
        {
            Student s = new Student { Name = ""};
            validator.ShouldHaveValidationErrorFor(student => student.Name, s);
        }

 

        [Test]
        public void Should_Have_Error_When_AddressLine1_IsNotNull()
        {
            Student s = new Student { Name = "abc", AddressLine1 = "test", City = "" };
            validator.ShouldHaveValidationErrorFor(student => student.AddressLine1, "");
        }

 

        [Test]
        public void Should_Not_Have_Error_When_AddressLine1_IsNull()
        {
            Student s = new Student { Name = "abc", AddressLine1 = "", City = "asd" };
            validator.ShouldHaveValidationErrorFor(student => student.City, "");
        }
    }
}

 

Just load this DLL in NUnit runner and see the result. The code is pretty self-explanatory. We use helper method of FluentValidation – ShouldHaveValidationErrorFor. It checks if FluentValidation shows any error for given model. So we have automated the unit testing. Our code is neat, clean. We have three classes now -

1. Model / View Model

2. It’s Validator

3. It’s Unit test

No mess up and easy integration with MVC. The best thing about Fluent Validation is that it is well documented. You can find full documentation at it’s home page.

I hope this article would be very helpful to you. Happy coding!!! Feel free to comment if you any question, suggestion or feedback.


Fluent Validation + NInject + MVC - Why & How : Part 1


Validation is one of the most important aspects of programming. “To err is human”. Every human being is prone to commit errors. Our application must be smart enough to catch those errors and let user know about the actions he/she needs to perform in order to proceed further. But when we say that application must have validation logic, we also consider this aspect from development and maintenance perspective. Our validation logic must be easy to integrate, easy to test and easy to change as well if the need be. Taking into consideration let’s first dig why do we need a third party validation library instead of using built in MVC validation framework.

Why to use FluentValidation.Net library instead of MVC built-in Validation Framework?

This should be first thing which needs to be answered before we explore any new framework or any alternative to existing thing? Why? Why should I go for FluentValidation when I have built-in validation framework in MVC and it is working just fine. Does FluentValidation do anything different than built-in MVC validation framework? When we understand “why” part, understanding the framework and playing with it becomes much much easier. Let’s take the question again?

Q - Does FluentValidation do anything different than built-in MVC validation framework?
The answer is NO. But it does it differently and in a much more better way. All validation frameworks do the same thing – Validate the model and make the validation errors available to the MVC framework so that the same can be displayed on the view. But how do they do it is more important.

Let’s consider the built-in MVC validation framework. It makes use of Data Annotation attributes to perform the validation. Consider following example.

public class Student
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Range(2, 5)]
    public int NoOfSubjects { get; set; }
}


In order to add Data Annotations we need to add namespace - System.ComponentModel.DataAnnotations;
Data Annotations are nothing but attributes over the desired properties. Required attribute indicated MVC that this field in required on the form. If user doesn’t fill this value and post back occurs then MVC framework would show an error stating that Name field is required. On the same line Email and NoOfSubjects would be validated (If you are new to Data Annotation thing then please see a running example at – MSDN). So what is wrong with above validation? Logically nothing. It would work seamlessly the way we want it. But there are few drawbacks with this approach.

  1. Models becomes dirty“Single Responsibility” principle of the software engineering says that every class should be responsible for carrying out only that task which is assigned to it. In our case the task of Model/ViewModel is nothing but to show the data to the user. Why does it need to have validation logic as well? Some people may argue that Model’s responsibility is to show the data to the user and validation is nothing but the provision to the data correct. But in my honest opinion these two are different responsibilities. Don’t overburden our model. Let it do it’s own job only – show data to the view. If you don’t agree with me, please read second and third point and come back to first point and agree with me now.
  2. Unit Testing of the Validation logic – I won’t say that with this logic you can’t unit test the validators but it is tricky. When we cover FluentValidation you would realize how. For those who don’t know how to unit test Data Annotations they may find this post useful.
  3.  Conditional Validation – Conditional validation is not straightforward to perform using Data Annotation approach. e.g. If we wish to perform validation on Email in above example only when NoOfSubjects field is not empty then using Data Annotation it will be a difficult task. We would end up writing custom validator for that.


In order to overcome all the above three main issues of Data Annotation approach we need some framework. It would provide us to write validation logic in different class than model and still be able to bind the logic to the model with least efforts, to perform unit testing of validation rules, to perform conditional validation, to have better control over validation rules etc. If you are looking for these things then FluentValidation.Net is the answer for it. FluentValidation.Net is a very small library written in .Net which lets us write Validation rules using clean, easy to understand lambda expressions.

Fluent Validation in Action

Enough of the theory part. Now that we understood the need of FluentValidation, let’s put it in some action. We would create a simple MVC5 application and would perform validation of model/view model using fluent validation and then we would put NInject into action for dependency injection of validators. We will use Visual Studio Express 2013 for Web to build our demo project in step by step way.

image

 

image

Create an MVC5 application and add FluentValidation nuget package as shown below.

image

image

If you are using MVC4 or MVC3, still you can follow same steps. Just replace FluentValidation.MVC5 with MVC4 or MVC3 whichever version you are using. Click on install. It would add FluentValidation references to the project. You are all set to use FluentValidation now.

Add a class in model folder. I have added following class -

public class Student
{
    public string Name { get; set; }

    public string Email { get; set; }

    public string AddressLine1 { get; set; }

    public string AddressLine2 { get; set; }

    public string City { get; set; }
}


I have added a simple plain class. Let’s add one view also to show this model.

@model FluentValidationMVC5Demo.Models.Student

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email)
                @Html.ValidationMessageFor(model => model.Email)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AddressLine1, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AddressLine1)
                @Html.ValidationMessageFor(model => model.AddressLine1)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AddressLine2, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AddressLine2)
                @Html.ValidationMessageFor(model => model.AddressLine2)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.City, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.City)
                @Html.ValidationMessageFor(model => model.City)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
 

I have also added two action methods in HomeController.

 
[HttpGet]
public ActionResult Index()
{
    Student model = new Student();
    return View(model);
}

[HttpPost]
public ActionResult Index(Student model)
{
    return View(model);
}

 

I hope you are familiar with HTTPGet and HTTPPost methods. Also I assumed that you have understood the Index view. I have simple added the code to show model and submit button on the view. No validation logic yet. Let’s add validation rules for the Student class. Create a new class with the name StudentValidator. I use this convention that validator class name would be model name + Validator. You may use different convention if you wish. My validator class looks like following -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentValidation;

namespace FluentValidationMVC5Demo.Models
{
    public class StudentValidator : AbstractValidator<Student>
    {
        public StudentValidator()
        {

        }
    }
}

 

Note the namespace at the top – FluetValidation. We need to add this namespace in order to use the validation framework.  Now let’s understand the code. We are saying that this class would be the validator for Student class then we need to tell the Fluent Validator by inheriting the validator class with the generic class – AbstractValidaor<>. Also this generic class would accept Student as the entity to validate. So first line says that StudentValidator would server as the validator for the Student class. Simple?

Now, second thing is you just need a parameter-less constructor in this validator class. We would write all the validation rules inside this constructor. Also we would end up using lambda expression to write validation rule.

RuleFor(x => x.Name)
    .NotEmpty();
.WithMessage("Please enter Name!!!");

 

I have written this simple rule inside the constructor. Let’s understand the line. RuleFor is the method of AbstractValidator and since we are inheriting from it we get direct access to this method inside the constructor. It takes lambda expression as input. I hope you understand lambda expression. So the code simple means that we are writing validation rule for property Name of Student class. If you press . after RuleFor(x => x.Name) you would get the whole list of validation rules available. It includes many rules viz. NotEmpty, LessThan, GreaterThan etc. You can explore those validation rules on your own. Let’s stick to NotEmpty for time being. It means that Name property is required field. And then third line says that if validation fails you have show this error message. You can explore all the validation rules and validation methods at the home page.

Now we have written validation logic also. Let’s wire it with the MVC framework. How would MVC framework know that validation rules for Student class are there in StudentValidator class? We need to tell it. Right?

I assume that you know NInject and Dependency Injection. If you are new to NInject then I suggest you to go through NInject Tutorial and NInject Home Page. We would directly proceed here assuming you having basic knowledge of Dependency Injection. Add NInject Nuget package to our application. You can add Nuget package the same we added FluentValidation or you can go to View –> Other Window –> Package Manager Console and type folllwing -

Install-Package Ninject.MVC4 -Version 3.2.0

It does the same job as that of Nuget dialogue. I told this way just to show you another way of adding Nuget references.

MVC is all plug-n-play framework. You can plug your validator framework, authentication framework etc into MVC and MVC would use this plugged framework and neglect it’s built in framework for that particular module. We are going to use this feature of MVC. We are going to override MVC’s built in validation framework. For that, first thing we have to do is we need to write some logic which would return a validator class for a given model/view model. Let’s name it as FluentValidationConfig. It would create and return specific validator given model as input. e.g. It would return StudentValidator if we give Student as input. (Don’t worry we don’t have to do anything, MVC & NInject would take care of everything).

As a next step, we would create this class under App_Start folder. Just to be consistent with MVC folder structure, we would put all config related files under App_Start folder. I have written following code in the file -

public class FluentValidationConfig : ValidatorFactoryBase
{
    private IKernel kernel;

    public FluentValidationConfig()
    {
        kernel = new StandardKernel();
    }

    public void AddBinding()
    {

    }

    public override IValidator CreateInstance(Type validatorType)
    {
            
    }
}

 

Let’s understand the code first. If we are writing our custom validator factory overriding MVC’s built in feature then we need to implement IValidatorFactory interface. It has following definition -

public interface IValidatorFactory {
  IValidator<T> GetValidator<T>();
  IValidator GetValidator(Type type);
}
 
But instead of implementing this interface, FluentValidation makes us available a simpler solution by exposing ValidatorFactoryBase. It would do most of the work for us. We just to need to override CreateInstance method of this class which would return the specific validator. We have created an instance of StandardKernel in the constructor which would deal with bindings. In the AddBindigs method we would wire the validator and it’s viewmodel. It is done as follows -
 
kernel.Bind<IValidator<ViewModell>>().To<ViewModelValidator>();
 

Where ViewModel is nothing but our model and ViewModelValidator is nothing but it’s Validator. So in our case it get’s transformed as -

 
kernel.Bind<IValidator<Student>>().To<StudentValidator>();
 
Before you put this code in AddBindings method, you may need to add using for the Model namespace as Student and StudentValidaor class are in Models folder. Now last part, we need to add code in CreateInstance method.
 
return (validatorType == null) ? null : (IValidator)kernel.TryGet(validatorType);
 
The code is self explanatory. NInject would simple resolve IValidator<Student> to StudentValidator and we are done. Full code of FluentValidationConfig file is as follows -
 
using FluentValidation;
using Ninject;
using FluentValidationMVC5Demo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FluentValidationMVC5Demo.App_Start
{
    public class FluentValidationConfig : ValidatorFactoryBase
    {
        private IKernel kernel;

        public FluentValidationConfig()
        {
            kernel = new StandardKernel();
            AddBinding();
        }

        public void AddBinding()
        {
            kernel.Bind<IValidator<Student>>().To<StudentValidator>();
        }

        public override IValidator CreateInstance(Type validatorType)
        {
            return (validatorType == null) ? null : (IValidator)kernel.TryGet(validatorType);
        }
    }
}
 
And last step, we need to inform MVC to use this validation configuration when it wants to get validator for any model. This would be done in Global.asax file. Just one line -
 
 
FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(
                provider => { provider.ValidatorFactory = new FluentValidationMVC5Demo.App_Start.FluentValidationConfig(); });
 
 
It is self explanatory again. It configures FluentValidationConfig as the default validator factory for our MVC application. Now run the application and navigate to home page and just click on submit button, we should get that “Please enter name” error. We added the validation error only for Name fields, now you try to add validation for as many fields as you want and the way you want.
 
image

If we look at the AddBinding method, we observe that we need to add binding for each validator to it’s model. So everytime we add new model and it’s respective validator we would have to change this function to accommodate this new model. It is difficult to maintain. Right? Don’t worry, there is a workaround for that also. NInject offers Assembly scanning. We would instruct NInject to scan entire assembly to look for all classes which inherit AbstractValidator and add the binding automatically. It can be done in following way – AddBinding function code changes to

AssemblyScanner.FindValidatorsInAssembly(Assembly.GetExecutingAssembly())
                            .ForEach(match => kernel.Bind(match.InterfaceType)
                                .To(match.ValidatorType));
 

If we put this code in AddBinding then we do not need to worry about any binding manually. Validators would be auto bound to it’s respective models. Now replace AddBinding code with above lines and see if your code works.

 

Done!!!

 

Now if you see, Our model class is clean and it’s validation logic is clean too. Validation rules are easy to write, easy to maintain and easy to change without having to change model class any way. In next article we would learn how to unit test and use conditional validators in FluentValidation.

 

I hope you enjoyed the article. Feel free to comment if you have any doubt, suggestion or any comment on this article.


Customize Context Menu Search in Chrome to search in any Website


GoogleSearchChrome browser allows searching any text in Google by clicking on “Search Google for xxx”, where xxx stands for the selected text as shown in image (Search option in the context menu in Google Chrome). But Google might not be the favorite search engine for all. What if someone wants to search in Bing or Yahoo instead of Google? Isn’t there any way to customize Google Chrome Context Menu Search option? Also, a movie freak might want to search selected text in IMDB while Book lover might prefer searching in his/her favorite Book Review website. No doubt about the clever Google which is going to show most relevant websites even if we click on “Search Google for xxx” context menu, but it makes little sense when I want to search the selected text in any of the preferred sites.

There is an answer to all the questions raised in above paragraph and that is – Context Menu Search Google Chrome Extension. It is a very flexible extension which allows customizing context menu search of Google Chrome to search the selected text in any website we desire. when you add Context Menu Search Google Extension in Google Chrome it will add new context menu named “Context Menu Search” with many predefined websites to search desired text from any webpage.CustomContextMenu Now enjoy searching in website you wish. Also, the most adorable feature of this extension is that the extension is not limited to the already provided websites in the context menu. You can add as many sites as you wish. Just click on “Options” and it would open you a configuration window which allows to extend the extension to search desired text in any website on net that supports searching it’s own catalogue.

The extension has added many popular websites by default viz. Google, Bing, Yahoo, Bing Images, Ask.com, Reddit, Wikipedia, Google Images, Social Media Websites like Facebook, Twitter, Myspace, Orkut, Many News Websites, Shopping Websites, Music and Movie Websites. Just check the box against the website name to let it appear in the context menu.

Add New Website In Context Menu Search

Don’t feel disheartened not to see your favorite website. You can add your favorite website as a custom search engine in the context menu. Just click on “Options” menu in the Google Chrome Context Menu to open configuration window as shown below. It will by default open in “Add Search Engine NewSearchEngineOption” tab. Under Display Name you can add the name that you desire to appear in the Google Chrome Context Menu while Link is the one where the text would be provided as search parameter. You have to provide the selected text as “TESTSEARCH” keyword to the URL. When the extension redirects to this URL it will replace “TESTSEARCH” by the selected text.

I always prefer to use Vocabulary.com to search for English vocabulary, Synonyms, Antonyms. Image on the left shows how to add Vocabulary.com as search engine for vocabulary search.

When you are done adding your custom search engine just click “Add New Option” and it will be added in the Chrome Context Menu under “Context Menu Search”. Enjoy searching in your favorite website now.

How to create link for your favorite search engine to appear in Context Menu?

It is pretty simple. For example we will consider one Book Reviews Website – Book Reviews. To form the link follow the below steps -

  1. Navigate to Book Reviews website and look for search button. (Most of the websites provide internal search facility. This extension makes use of this feature only).
  2. Type anything in the search box and click on search.
  3. Replace anything with “TESTSEARCH” without quotes and paste link text box as shown in above figure.
  4. You can directly put “TESTSEARCH” without quotes in the search box, but for understanding purpose I followed longer approach!!!
  5. You are done. Enjoy searching.

Other Popular Search Engines for Google Chrome Context Menu

  1. About.com - http://search.about.com/?q=TESTSEARCH
  2. CodeProject.com - http://www.codeproject.com/search.aspx?q=TESTSEARCH
  3. StackOverflow.com - http://stackoverflow.com/search?q=TESTSEARCH

Searching World Wide Web made easier now!!!