Wednesday, April 18, 2018

How to add two strings that are long numbers?

Please click here for running code

using System;
namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string str1 = "123123123123123123213123",
                str2 = "212321312312312312312312312321312312312312",
                strResult;
            StrLongInteger v1 = new StrLongInteger(str1);
            StrLongInteger v2 = new StrLongInteger(str2);
            strResult = (v1 + v2).ToString();
            Console.WriteLine("Sum of Two number:  " + strResult);
        }
    }
    public class StrLongInteger
    {
        private string strNumber;
        public StrLongInteger(string numberAsString)
        {
            this.strNumber = numberAsString;
        }
        // Adds two string long numbers.
        public static StrLongInteger operator +(StrLongInteger strLI1, StrLongInteger strLI2)
        {
            char[] outputChars = new char[500];
            string longStr1 = Reverse(strLI1.ToString());
            string longStr2 = Reverse(strLI2.ToString());
            int length1 = longStr1.Length;
            int length2 = longStr2.Length;
            int maxLength = length1 > length2 ? length1 : length2;
            int carry = 0;
            int j = 0;
            for (j = 0; j < maxLength; j++)
            {
                int digit1 = (j > length1 - 1) ? 0 : Convert.ToInt32(longStr1[j].ToString());
                int digit2 = (j > length2 - 1) ? 0 : Convert.ToInt32(longStr2[j].ToString());
                int digitSum = digit1 + digit2 + carry;
                if (digitSum >= 10)
                {
                    digitSum -= 10;
                    carry = 1;
                }
                else
                    carry = 0;
                outputChars[j] = Convert.ToChar(Convert.ToString(digitSum));
            }
            if (carry == 1)
                outputChars[j++] = '1';
            return new StrLongInteger(Reverse(new string(outputChars)));
        }
        // reverses the string.
        private static string Reverse(string strNumber)
        {
            int j = 0;
            char[] outputChars = new char[strNumber.Length];
            for (int i = strNumber.Length - 1; i >= 0; i--)
            {
                outputChars[j] = strNumber[i];
                j++;
            }
            return new string(outputChars);
        }
        public override string ToString()
        {
            return strNumber.TrimStart('\0');
        }
    }
}

//Output
//Sum of Two number:212321312312312312435435435444435435525435

Sunday, September 10, 2017

Fetch data from json using angular2 js


Setup Angular 2 with Visual studio code editor.

     



 Fetch data from json using angular2 js


File structure on code editor

Result:
               
1. Create  dummy JSON file  or use existing file :https://api.myjson.com/bins/1fgw4x

              

2. Create employee service class and make a http call from emp service

[file name:employee.service.ts]


import { Injectable } from '@angular/core';
import { Http , Response} from '@angular/http';
// Import the map operator
import 'rxjs/add/operator/map';
@Injectable()
export class EmployeeService {
private _url:string = 'https://api.myjson.com/bins/1fgw4x';
constructor(private _http: Http) { }
getEmployees() {
return this._http.get(this._url)
.map((response: Response) => response.json());
}
}

3. Create employee details file[file name:employee-details.component.ts]


import { Component, OnInit } from '@angular/core';
import { EmployeeService } from './employee.service';
@Component({
selector: 'app-employeedetail',
template: `<h2>Employee Detail</h2>
<ul *ngFor="let employee of employees">
<li>{{employee.id}} | {{employee.name}} | {{employee.gender}} </li>
</ul>`
})
export class EmployeeDetailComponent implements OnInit {
employees: any = [];
constructor(private _employeeService: EmployeeService) { }
ngOnInit() {
this._employeeService.getEmployees()
.subscribe(resEmployeeData => this.employees = resEmployeeData )
}
}



4.Update on app.module.ts file

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { EmployeeDetailComponent } from './employee-details.component';
@NgModule({
imports: [BrowserModule, HttpModule ],
declarations: [AppComponent, EmployeeDetailComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }




5.Update code on app.component.ts

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { EmployeeService } from './employee.service';
@Component({
selector: 'app-root1',
template: `<h1>Hello Angular</h1>
<app-employeedetail></app-employeedetail>`,
providers : [EmployeeService]
})
export class AppComponent {}
                    


6. HTML file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyApp2</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root1></app-root1>
</body>
</html>


Optional:we can also replace template with template url in employee-details.component.ts  .
<style>
table {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: large;
border-collapse: collapse;
}

td {
border: 1px solid #369;
padding:5px;
}

th{
border: 1px solid #369;
padding:5px;
}
</style>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let employee of employees'>
<td>{{employee.id}}</td>
<td>{{employee.name}}</td>
<td>{{employee.gender}}</td>
</tr>
<tr *ngIf="!employees || employees.length==0">
<td colspan="5">
No employees to display
</td>
</tr>
</tbody>
</table>

Tuesday, October 20, 2015

upload and download demo using asp.net




1. Out put

2. Source Code:


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div style="font-family: Arial">


            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
            <br />
            <br />
            <br />
            <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4"
                 AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
                <Columns>
                    <asp:TemplateField HeaderText="File">
                        <ItemTemplate>
                            <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Eval("File") %>' CommandName="Download" Text='<%# Eval("File") %>'></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="Size" HeaderText="Size In Bytes" />
                    <asp:BoundField DataField="Type" HeaderText="File Type" />
                </Columns>
                <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                <RowStyle BackColor="White" ForeColor="#330099" />
                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                <SortedAscendingCellStyle BackColor="#FEFCEB" />
                <SortedAscendingHeaderStyle BackColor="#AF0101" />
                <SortedDescendingCellStyle BackColor="#F6F0C0" />
                <SortedDescendingHeaderStyle BackColor="#7E0000" />
            </asp:GridView>
        </div>
    </form>
</body>
</html>









3. Code Behind


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;

namespace UploadAndDownload
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            gridBind();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Data/") + FileUpload1.FileName);
            }
            gridBind();
         
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Download")
            {
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.Buffer = true;
                Response.ContentType = "application/octect-stream";
                Response.AppendHeader("Content-Disposition", "filename=" + e.CommandArgument);
                Response.TransmitFile(Server.MapPath("~/Data/") + e.CommandArgument);
                Response.End();
            }
        }

        private void gridBind()
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("File", typeof(String));
            dt.Columns.Add("Size", typeof(String));
            dt.Columns.Add("Type", typeof(String));

            foreach (string strFile in Directory.GetFiles(Server.MapPath("~/Data/")))
            {
                FileInfo fi = new FileInfo(strFile);

                dt.Rows.Add(fi.Name, fi.Length, fi.Extension);

            }

            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}























Tuesday, September 15, 2015

WCF Backward Compatibility and Versioning Strategies

Versioning Strategies
Once services are pushed to production their associated WSDL documents – which represent service endpoints, protocols and related contracts describing operations and messaging – must not be changed. Or, at a minimum, any changes should be backward compatible so that existing clients are not affected when changes are published. In this section I will discuss how WCF contracts support backward compatibility, and explain a few versioning strategies that you might consider for your WCF applications.

WCF Contracts and Backward Compatibility

WCF contracts are version tolerant by default. Figure 1 and Figure 2 summarize typical changes to service contracts and data contracts and describe the impact to existing clients. In short, the DataContractSerializer allows missing, non-required data and ignores superfluous data for service contracts, data contracts and similarly, message contracts. Only the removal of operations or the addition or removal of required data causes problems with existing clients.
Figure 1: Service contracts and backward compatibility
Service Contract ChangesImpact to Existing Clients
Adding new parameters to an operation signature
Client unaffected. New parameters initialized to default values at the service.
Removing parameters from an operation signature
Client unaffected. Superfluous parameters pass by clients are ignored, data lost at the service.
Modifying parameter types
An exception will occur if the incoming type from the client cannot be converted to the parameter data type.
Modifying return value types
An exception will occur if the return value from the service cannot be converted to the expected data type in the client version of the operation signature.
Adding new operations
Client unaffected. Will not invoke operations it knows nothing about.
Removing operations
An exception will occur. Messages sent by the client to the service are considered to be using an unknown action header.
Figure 2: Data contracts and backward compatibility
Data Contract ChangesImpact to Existing Clients
Add new non-required members
Client unaffected. Missing values are initialized to defaults.
Add new required members
An exception is thrown for missing values.
Remove non-required members
Data lost at the service. Unable to return the full data set back to the client, for example. No exceptions.
Remove required members
An exception is thrown when client receives responses from the service with missing values.
Modify existing member data types
If types are compatible no exception but may receive unexpected results.

Choosing a Versioning Strategy

Version tolerance is a good thing since it gives developers a flexible way to handle change. Since the DataContractSerializer is version tolerant, in theory you can refrain from officially versioning contracts and endpoints that expose those contracts until a breaking change is introduced such as removing operations from a service contract, or adding or removing required members from a data contract.
There are also potential side-effects of version tolerance:
  • If you add new operations to a service contract only clients that reference the latest WSDL will know about those operations and you will not be able to track which of your existing clients have updated their WSDL unless you expose a new endpoint when changes are made.
  • If you add non-required data members to a data contract you may have to write extra code to initialize missing values to something meaningful – as opposed to using the default value.
  • If you remove non-required data members from a data contract you may have round-trip issues where data passed to services or returned to clients is lost.
  • It may be difficult to track problems if you do not keep track of different versions of contracts, as changes are made to production.
It is important to choose an appropriate versioning strategy that satisfies the sometimes conflicting need for agility and productivity vs. change control. Here are a few versioning strategies to consider:
  • Agile Versioning: Rely on backward compatibility for as long as possible and avoid formal contract and endpoint versioning until compatibility is broken. This approach is useful in agile environments that require frequent updates to production code.
  • Strict Versioning: Perform formal contract and endpoint versioning for any change to a service contract, data contract, message contract or other contract-related or endpoint-related changes. This approach is best in environments what have less frequent production updates or that require detailed tracking of any and all changes.
  • Semi-Strict Versioning: Perform formal contract and endpoint versioning when contracts or endpoints are modified in a way that your policy requires tracking the change. For example, your policy might be to allow new operations to be added to a service contract, but if any changes are made to existing operations, or if any data contracts change such that they are semantically different, it requires versioning. This approach lies somewhere between agile and strict versioning.
The agile approach to versioning – shown in Figure 3 – means making changes to existing data contracts and service contracts without versioning them, or supplying new endpoints. Strict versioning means providing new data contracts, service contracts and endpoints as shown in Figure 4. 
Figure 3: Agile versioning through the same service contract and endpoint
Figure 4: Strict versioning through a new service contract and unique endpoint
It is best to decide on a versioning policy before you release the first version to production.

Versioning Service Contracts

To formally version a service contract you should do the following:
  • Make a copy of the original contract with a new interface type name, the same contract name and a new namespace.
  • Make any required modifications to the contract definition.
  • Implement the new service contract on the same service type if possible. You can use explicit contract implementation to funnel requests to the different method implementations if necessary.
  • Add a new endpoint for the new service contract to the existing <service> configuration.
  • As an alternative, you can use a common base class that implements core service operations and provide overrides in each version’s derived type. This can be a better approach if there are significant changes to the service implementation, or if the service security behaviors will be different from the original service. This will require a separate <service> entry in the configuration file.
Figure 5 shows an example of strict service contract versioning with a shared service implementation. Note that the Name property of the ServiceContractAttribute is the same for both versions of the contract, while the interface type name changes from IServiceA to IServiceA2. Also notice that two service endpoints are configured – one for each contract.
Figure 5: Version 1 and 2 of ServiceAContract with related endpoint configuration
[ServiceContract(Name = "ServiceAContract",
Namespace = "urn:WCFEssentials/Samples/2008/12")]
public interface IServiceA
{
   [OperationContract]
    void Operation1();
    [OperationContract]
    void Operation2();
}
[ServiceContract(Name = "ServiceAContract",
Namespace = "urn:WCFEssentials/Samples/2009/01")]
public interface IServiceA2
{
    [OperationContract]
    void Operation1();
    [OperationContract]
    void Operation2();
    [OperationContract]
    void Operation3();
}
<service name="BusinessServices.ServiceA"
behaviorConfiguration="serviceBehavior">
  <endpoint address="ServiceA" binding="wsHttpBinding"
contract="BusinessServiceContracts.IServiceA"  />
  <endpoint address="ServiceA2" binding="wsHttpBinding"
contract="BusinessServiceContracts.IServiceA2"  />
  <host>
    <baseAddresses>
      <add baseAddress="http://localhost:8000"/>
    </baseAddresses>
  </host>
</service>
In the accompanying code download for this paper, the following directories contain samples that illustrate service contract versioning: WCFEssentials\ContractVersioning\ServiceContractVersioningAgile, WCFEssentials\ContractVersioning\ServiceContractVersioningStrict.

Versioning Data Contracts

To formally version data contracts is a little more complicated since each data contract is likely tied to business entities that are used by the service tier, the business tier and the data access tier in the application. I recommend the following approach:
  • Make a copy of the original data contract and type, but rename the type to V1 since this will no longer be actively used each application tier.
  • Modify the business entity implementation as needed to work with the application, and update its data contract providing a new namespace.
  • Make a copy of the original service contract and implementation and update it to use the V1 type name. Note that this will not alter the service implementation since the V1 type name should have the original data contract with an explicit name and namespace.
  • Version any service contracts that rely on this new data contract following instructions in the previous section. That includes exposing new endpoints.
  • Modify the original service implementation to forward calls to a V2 service instance after mapping the V1 business entity to the V2 business entity.
Figure 6 illustrates this approach.
Figure 6: Versioning data contracts
Client-side data contracts should also implement IExtensibleDataObject so that V1 clients will preserve unknown data from a V2 service – assuming that non-strict versioning is used. Although you can implement IExtensibleDataObject at the service as well, it is less likely that a service needs to preserve unknown data since it is the system of record for the application. Suppressing IExtensibleDataObject behavior can protect the service from potential DoS attacks alongside message size and reader quotas set on the binding. If you are sharing metadata such as data contract definitions between clients and services – you can implement IExtensibleDataObject on the data contract types and disable support for this extensibility at the service only. This is best done in code so that it can’t be inadvertently changed on production – by setting the IgnoreExtensionDataObject property of the ServiceBehaviorAttribute to true, as shown here:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall,
IgnoreExtensionDataObject=true)]
public class ArticlesManagerService : IArticlesManager
{…}
This can also be configured declaratively in the <behaviors> section as follows:
<behaviors>
  <serviceBehaviors>
    <behavior name="serviceBehavior"  >
      <dataContractSerializer ignoreExtensionDataObject="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
In the accompanying code download for this paper, the following directories contain samples that illustrate data contract versioning and IExtensibleDataObject: WCFEssentials\ContractVersioning\DataContractVersioning, WCFEssentials\ContractVersioning\IExtensibleDataObject.

Recommendations: Versioning Strategies

  1. Use an agile versioning strategy that relies heavily on backward compatibility for environments that must tolerate frequent change.
  2. Use a strict versioning policy for environments that are less frequently updated or require strict change control.
  3. Feel free to come up with a customized, semi-strict versioning policy that meets your application's needs.
  4. Establish a versioning policy ahead of time so that contracts and endpoints can be defined accordingly.
  5. Provide explicit name and namespace properties to contracts to support formal versioning.
  6. Implement IExtensibleDataObject on data contracts for clients and suppress support for this at the service.




Ref by : https://msdn.microsoft.com/en-us/library/ff384251.aspx

Monday, September 15, 2014

how to check data type size in sql server 2008


select COLUMN_NAME 
from INFORMATION_SCHEMA.COLUMNS
where DATA_TYPE = 'Data type of column like varchar ,char etc. '
and CHARACTER_MAXIMUM_LENGTH = size of col like 100 ,200 etc
and TABLE_NAME = 'your_table'
 
 
 
 
Ex:
select COLUMN_NAME 
from EmpDB.INFORMATION_SCHEMA.COLUMNS 
where DATA_TYPE = 'varchar'
and CHARACTER_MAXIMUM_LENGTH = 2000
and TABLE_NAME = 'EmpDemo' 

Wednesday, June 25, 2014

LESS CSS With MVC4 Web Optimization



MVC4 has a built in bundler and optimizer for javascript and css, but when you want to use LESS CSS, there’s a few things you need to do to get set up.

Step 1: Add BundleTransformer.Less from Nuget

BundleTransformer.Less is an excellent modular extension to Web.Optimization by taritsyn, allowing us to get our css and js bundling set up quickly.
We’re going to use the BundleTransformer.Less Nuget Package which will add the bundler core and dotless as well. This package is where most of the magic is performed. In the background it’s just setting up dotless to transform the css before bundling.

Step 2: Set up your CSS and JS bundles

A bundle is just a group of css or js references. When starting a new MVC4 project, you’ll have a file called BundleConfig.cs in your App_Start folder. This is where all our css and js references will go.
Take a look at how I’ve set this up:
public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        var cssTransformer = new CssTransformer();
        var jsTransformer = new JsTransformer();
        var nullOrderer = new NullOrderer();

        var css = new Bundle("~/bundles/css")
            .Include("~/Content/site.less");
        css.Transforms.Add(cssTransformer);
        css.Orderer = nullOrderer;

        bundles.Add(css);
        
        var jquery = new Bundle("~/bundles/jquery")
            .Include("~/Scripts/jquery-1.*");
        jquery.Transforms.Add(jsTransformer);
        jquery.Orderer = nullOrderer;

        bundles.Add(jquery);
        
        // If you'd like to test the optimization locally,
        // you can use this line to force it.
        //BundleTable.EnableOptimizations = true;            
    }
}
A couple of things to note here:
  • The cssTransformer and jsTransformer variables tie in the BundleTransformer to the pipeline.
  • The nullOrderer variable forces the optimizer to reference the files in the order they are defined.
  • The string we pass to the Bundle constructor is a virtual path. Don’t use a real path otherwise you’ll run into some funky routing issues.
  • The BundleTable.EnableOptimizations = true; allows you to force the optimizations to render as they would in release mode.

Step 3: Reference the Bundles in your Layout View

Open up your _Layout.cshtml and add the following code to your head tag:
@Styles.Render("~/bundles/css")
This will render any of the stylesheets we included earlier. Note that we’re referencing the virtual path we gave to the StyleBundle class.
You can also add the javascript bundle to the bottom of the page in the same way:
@Scripts.Render("~/bundles/jquery")
That’s It!
Thanks to Andrey Taritsyn for giving me some pointers about the code I’ve posted. You should absolutely check out the rest of the Bundle Transformer Range for other useful modules including SASS, CoffeeScript, YUI, JSMin, WebGrease and much more
 
More details about less please click here

Ref:benjii.me




Monday, May 5, 2014

ASP.NET MVC’s Validation



Model Validation: 
Validations are used for ensure that the expected data is valid and correct so that we can change according to requirement.

Validate in action method: We can validate model in action method. We can check the values of properties of the model object and register any errors we find with the ModelState property.
We can check to see whether the model binder was able to assign a value to a property by using the ModelState.IsValidField method. We do this make sure that the model binder was able to parse the value the user submitted; so that can perform additional checks.

Example:

if (string.IsNullOrEmpty(model. Email))
{
      ModelState.AddModelError("Email", "Please enter your Email");
}

if (ModelState.IsValid)
{
      //send model for further processing
}

ValidationSummary: The validation summary displays the error messages that we registered with the ModelState in our action method. There are a number of overloaded versions of the ValidationSummary method.

Method
Description
Html.ValidationSummary()
Generates a summary for all validation errors.
Html.ValidationSummary(bool)
If the bool parameter is true, then only model-level errors are displayed. If the parameter is
false, then all errors are shown.
Html.ValidationSummary(string)
Displays a message before a summary of all the validation errors.
Html.ValidationSummary(bool,string)
Displays a message before the validation errors. If the bool parameter is true, only model-level errors will be shown.


ValidationMessage: The Html.ValidationMessageFor helper displays validation errors for a single model property.
@Html.ValidationMessageFor(t => t.Email)

Validation in the Model Binder: The default model binder performs validation as part of the binding process. The model binder performs some basic validation for each of the properties in the model object. If value has not been supplied or value that cannot be parsed into the model property type. DefaultModelBinder, provides us with some useful methods that we can override to add validation to a binder. Find detail in below table.

Method Name
Description
Default Implementation
OnModelUpdated
Called when the binder has tried to assign values to all of the properties in the model object. Model level validation.
Applies the validation rules defined by the model metadata and registers any errors with ModelState.
SetProperty
Called when the binder wants to apply a value to a specific property. Property level validation
Required or not valid message will show.

Data Annotations: The MVC Framework supports the use of metadata to express model validation rules. We can easily add validation to our application by including Data Annotations namespace and use attributes to our model classes. Data Annotations allow us to describe the rules we want applied to our model properties, and ASP.NET MVC will take care of enforcing them and displaying appropriate messages to our users. There is number of attribute classes which inherits validation attribute class, use to manage different types of validation.

Some of important build in data annotation attributes are:
  • Required – Indicates that the property is a required field
  • DisplayName – Defines the text we want used on form fields and validation messages
  • StringLength – Defines a maximum length for a string field
  • Range – Gives a maximum and minimum value for a numeric field
  • RegularExpression – Validate input value as per defined regular expression
  • Compare – Two property must have same value.


Custom validation class: We can also create custom validation attribute by deriving from the ValidationAttribute class and implementing our own validation logic. We can override the IsValid method of the base class, this method get called by binder while passing value provided by user as the parameter.

Example:
public override bool IsValid(object value)
        {           
               
                if (String.IsNullOrEmpty(Convert.ToString(value)))
                {
                    return false;
                }

                return true;
        }

 [IsEmailReq(ErrorMessage = "Email is Required")]
public string Email { get; set; }


Model Validation Attribute: We can also create a custom attribute at model level instead of property level. Model validator attribute will use only if property-level attributes does not register a validation error. We must apply a model validation attribute to the model class itself.

Example:
public class IsEmailReqAttribute: ValidationAttribute
    {
        public RegisterValidatorAttribute()
        {
            ErrorMessage = "Please enter valid email";
        }

        public override bool IsValid(object value)
        {
            RegisterModel model = value as  RegisterModel;

            if (model.Email.Contains("test") || model.Email.Contains("test.com"))
            {
                return false;
            }
            return true;
        }
    }

[IsEmailReq]
public class RegisterModel


Client-Side Validation: In web application user expect immediately validation, without having to submit data to the server. This is client site validation and usually we implement JavaScript for this. This allow user to correct data before sending to the server for further processing.
The MVC Framework supports unobtrusive client-side validation. The term unobtrusive means that validation rules are expressed using attributes added to the HTML elements that we generate. These are interpreted by a JavaScript library that is included as part of the MVC Framework, which uses the attribute values to configure the jQuery Validation library, which does the actual validation work. There are few advantages using this approach.

  • We do not have to include client-side validation logic into our views
  • If JavaScript disabled in browser then server side validation will fire in same manner.
  • Mitigate the effect of browser inconsistencies and behaviors.


Enable/Disable Client validation: Developer can enable and disable client side validation by setting in web.config. By default it’s enabled.

<appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
 </appSettings>

Both of these settings must be true for client-side validation to work. We can also set value programmatically like in global.asax page application start method.

protected void Application_Start()
{
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}

We can enable or disable client-side validation for individual views as well by setting above value in view page.

In addition to the configuration settings, we must references three specific JavaScript libraries.

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

After all above setting client side validation will start to work based on applied metadata attributes in model properties such as Required, Range, Regular Expression and String Length.
Client side validation works faster and also perform validation on key stroke like key press or focus change.

In MVC Framework validation rules are expressed using HTML attributes. MVC client-side validation is that the same attributes we use to specify validation rules are applied at the client and at the server.  

Example:
Without validation attribute:
public string Email { get; set; }
Output:
<input id="Email" name="Email" value="" type="text">

With validation attribute:
[Required]
public string Email { get; set;
Output:
<input id="Email" name="Email" value="" type="text" data-val-required="The Email is required." data-val="true">

Note: The MVC client-validation features are built on top of the jQuery Validation library; developer can use the Validation library directly and ignore the MVC features if required. The MVC client-validation features hide the JavaScript, and they have the advantage of taking effect for both client- and server-side validation.

Example:

<script type="text/javascript">
$(document).ready(function ()
{
    $('form').validate({
    errorLabelContainer: '#validtionSummary',
    wrapper: 'li',
    rules: {
        Email: {
            required: true,
        }
    },
    messages: {
        Email: "Please enter your Email"
    }
    });
});
</script>


The jQuery Validation library supports some more complex validation rules like email, url, date, number, digits and credit card or we can create new rules.

Creating attributes for client-side validation: To enable client-side validation, we must implement the IClientValidatable in model attribute class. We can create custom validation attributes that work in the same way as the built-in ones and that trigger client- and server-side validation.

The interface defines one method, GetClientValidationRules, which returns an enumeration of
ModelClientValidationRule objects. Each ModelClientValidationRule object describes the client-side validation rule that we want to apply, the error message to display when the rule is broken, and any parameters that the rule needs to operate.

Example:
Example to create a new rule called checkboxmusttrue to ensure that a checkbox is checked.
Developer has to add custom jQuery validation rule to unobtrusive adaptor.

<script type="text/javascript">

    jQuery.validator.unobtrusive.adapters.add("checkboxmusttrue", function (options) {
        if (options.element.tagName.toUpperCase() == "INPUT" &&
options.element.type.toUpperCase() == "CHECKBOX") {
            options.rules["required"] = true;
            if (options.message) {
                options.messages["required"] = options.message;
            }
        }
    });
</script>

public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            return value is bool && (bool)value;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new ModelClientValidationRule[] {    new ModelClientValidationRule {
            ValidationType = "checkboxmusttrue",
                    ErrorMessage = this.ErrorMessage
            }};
        }
    }




Source:MSDN and some other blogs.