Friday, 15 April 2016

Create Custom Data Annotation Validators in MVC



To create a custom data annotation validator follow these gudelines:
1)    Your class has to inherit from System.ComponentModel.DataAnnotations.ValidationAttribute class.
2)    Override bool IsValid(object value) method and implement validation logic inside it.

Sometimes developers check that value is not null/empty and return false. This is usually incorrect behaviour, because that's on Required validator to check which means that your custom validators should only validate non-null data but return true otherwise (see example). This will make them usable on mandatory (required) and non-mandatory fields.
public class StringLengthRangeAttribute : ValidationAttribute
{
    public int Minimum { get; set; }
    public int Maximum { get; set; }

    public StringLengthRangeAttribute()
    {
        this.Minimum = 0;
        this.Maximum = int.MaxValue;
    }

    public override bool IsValid(object value)
    {
        string strValue = value as string;
        if (!string.IsNullOrEmpty(strValue))
        {
            int len = strValue.Length;
            return len >= this.Minimum && len <= this.Maximum;
        }
        return true;
    }
}
All properties can be set in attribute as you wish to set them. Some examples:
[Required]
[StringLengthRange(Minimum = 10, ErrorMessage = "Must be >10 characters.")]

[StringLengthRange(Maximum = 20)]

[Required]
[StringLengthRange(Minimum = 10, Maximum = 20)]

When a particular property isn't set, its value is set in the constructor, so it always has a value. In above usage examples I deliberately added the Required validator as well, so it's in sync with the above caution I've written.
So this validator will still work on your model value that's not required, but when it's present it validates (think of a text field in a web form, that's not required, but if a user enters a value in, it has to be valid).


Difference between Select and SelectMany in LINQ



Select and SelectMany are projection operators.
Select operator is used to select value from a collection and SelectMany operator is used to select values from a collection of collection i.e. nested collection.
Select operator produce one result value for every source value while SelectMany produce a single result that contains a concatenated value for every source value. Actually, SelectMany operator flatten IEnumerable<IEnumerable<T>> to IEnumrable<T> i.e. list of list to list.
class Employee
{
    public string Name { get; set; }
    public List<string> Skills { get; set; }
}

public void TestSelectAndSelectMany()
{
    List<Employee> Employees = new List<Employee>();

    Employee Emp1 = new Employee { Name = "Ravi", Skills = new List<string> { "C", "C++", "Java" } };

    Employee Emp2 = new Employee { Name = "Minu", Skills = new List<string> { "SQL Server", "C#", "ASP.NET" } };

    Employee Emp3 = new Employee { Name = "Aditi", Skills = new List<string> { "C#", "ASP.NET MVC", "Windows Azure", "SQL Server" } };

    Employees.Add(Emp1);
    Employees.Add(Emp2);
    Employees.Add(Emp3);

    //-- Query using Select()
    IEnumerable<List<String>> ResultSelect = Employees.Select(e => e.Skills);

    Console.WriteLine("**************** Select ******************");

    //-- Two foreach loops are required to iterate through the results
    //-- because the query returns a collection of arrays.
    foreach (List<String> SkillList in ResultSelect)
    {
        foreach (string Skill in SkillList)
        {
            Console.WriteLine(Skill);
        }
        Console.WriteLine();
    }

    //-- Query using SelectMany()
    IEnumerable<string> ResultSelectMany = Employees.SelectMany(emp => emp.Skills);

    Console.WriteLine("**************** SelectMany ******************");

    //-- Only one foreach loop is required to iterate through the results
    //-- since query returns a one-dimensional collection.
    foreach (string skill in ResultSelectMany)
    {
        Console.WriteLine(skill);
    }
}

Output:

**************** Select ******************
C
C++
Java

SQL Server
C#
ASP.NET

C#
ASP.NET MVC
Windows Azure
SQL Server

**************** SelectMany ****************
C
C++
Java
SQL Server
C#
ASP.NET
C#
ASP.NET MVC
Windows Azure
SQL Server



Monday, 28 March 2016

Difference between ApiController and Controller in ASP.NET MVC



1)    You can use controller to render your normal views only.
But using the ApiController action only returns the data which is serialized and sent to client. So, that you can use it in any Html based application.
2)    You can self-hosting using ApiController but not from MVC Controllers.
3)    If you are aware with ASP.NET MVC then you are already knows about the controllers.
And the APIControllers are same as MVC controllers, but it inherits the ApiController class instead of the Controller class.
4)    APIControllers is a lightweight architecture excepting the web Apps. 
5)    MVC Controller shows the URL Samples matching the default route pattern"{controller}/{action}/{id}". and the ApiController shows "api/{controller}/{id}".
6)    Web API Supports the self hosting, content (you can send content to the client in variety of formats such as images or files) negotiation where the MVC doesn't support it.
7)    Use Controller when - If you're writing an HTML based web/internet application (with the occasional AJAX call returning json here and there).
Use ApiControllers When - If you want to provide a data driven/REST-ful interface to a system.

So, you have to use the API which is compatible with the browsers and all the modern devices apps.
Actually, the Web API is a open source platform for building a REST-ful services over the .Net Framework.