Monday, March 1, 2010

WCF

WCF Service

-----------------------
Data Contract Basics
-----------------------

Windows Communication Foundation (WCF) uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML). All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts. Many .NET Framework types also have existing data contracts. For a full list of serializable types

This is normally done by applying the DataContractAttribute attribute to the type.

This attribute can be applied to classes, structures, and enumerations.

The DataMemberAttribute attribute must then be applied to each member of the data contract type to indicate that it is a data member, that is, it should be serialized.

DataMemberAttribute can only be applied to fields and properties.


Examples :-

using System;
using System.Runtime.Serialization;

[DataContract]
public class Person
{
// This member is serialized.
[DataMember]
internal string FullName;

// This is serialized even though it is private.
[DataMember]
private int Age;

// This is not serialized because the DataMemberAttribute
// has not been applied.
private string MailingAddress;

// This is not serialized, but the property is.
private string telephoneNumberValue;

[DataMember]
public string TelephoneNumber
{
get { return telephoneNumberValue; }
set { telephoneNumberValue = value; }
}
}


// Example to Create WCF Service

// Interface

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using PjtBDto1;
using System.ComponentModel;

[ServiceContract]
public interface Iuser
{
[OperationContract]
[FaultContract(typeof(ExceptionClass))]
BindingList< BDto1 > GettList(Int32 unicId);

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
bool InsertUpdate(BDto1 obj1BDto);

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
BindingList< BDto1 > GettList(Int32 unicId);

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
Int32 Del1(BDto1 obj1BDto);

}

//ExceptionFields is an enum containing two members
//“ERROR” and “INCORRECT_OPERATION”.
[DataContract]
public class ExceptionClass
{
[DataMember]
public ExceptionFields errorcode;
[DataMember]
public string message;
[DataMember]
public string details;
}
// Used for holding exception fields
public enum ExceptionFields
{
[EnumMember]
ERROR,
[EnumMember]
INCORRECT_OPERATION
}


// Service class

using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.ComponentModel;
using PjtDao;
using PjtBc;
using PjtBDto;

public class Service1 : IService1
{
public BindingList< BDto1 > GetList(Int32 UnicId)
{
using(BC1 ObjBc1=new BC1)
{
return objBc1.GetList(UnicId);
}
return null;
}
}

// Exception Handling in WCF Service Layer

try

{

}

catch(Exception ex)
{
ExceptionClass error=new ExceptionClass();
error.errorcode = ExceptionFields.ERROR;
error.message = "General Exception"
error.details = ex.StackTrace;
throw new FaultException< ExceptionClass > (error);

}

// Service Exceptions in class of Catch block

ActionNotSupportedException
AddressAccessDeniedException
AddressAlreadyInUseException
ChannelTerminatedException
CommunicaitonException
Exception

// Handling same in all catch block
--------
ExceptionClass error=new ExceptionClass();
error.errorcode = ExceptionFields.ERROR;
error.message = "General Exception"
error.details = ex.StackTrace;
throw new FaultException< ExceptionClass > (error);

// In UI
---------

service1.ServiceClient objSerice1=new service1.ServiceClient();
System.ComponentModel.BindingList< BDto1 > objBL = new System.ComponentModel.BindingList< BDto1 >
objBL = objService1.GetList(UnicId);
objService1.close();


---------------------------------------------------------
enable windows authentication on WCF BasicHttpBinding
---------------------------------------------------------

Introduction and Goal

Step 1:- Create WCF project

public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}

Step 2 :- Ensure authentication mode is windows

Step 3 :- Define the binding in web.config file

system.serviceModel >
.........
.........

Step 4 :- Bind the bindings with service interface

bindingConfiguration="BasicHttpEndpointBinding"
name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1" >

Step 5 :- Ensure that anonymous access is disabled

In IIS uncheck Enable anonymous access (Authentication Methods)

Step 6:- Host your WCF service on IIS

We need to host our service in the IIS. So make the directory as an IIS application so that your service can be hosted. Now if you try to browse the service i.e. the SVC file you will see that it pops up the authentication authorization security dialog box. So this service cannot be executed with windows authentication.

Step 7 :- Consume the WCF service

add an ASP.NET webapplication and do a add webreference. You will be popped up with a dialog box as shown below. Click on add reference so that a proxy is generated for the WCF service.

Step 8:- Create the WCF client

Server1 obj=new Service1();
obj.Credentials = System.Net.CredentialCache.DefaultCredentials;
Response.Write(obj.GetData(1,true));

----------------------------------------------------
Form Authentication
----------------------------------------------------

1.
propertyName1="value1"

propertyName2="value2"

...

propertyNameN="valueN"

/ >


2.
cookieless :-
This attribute specifies under what conditions the authentication ticket is stored in a cookie versus being embedded in the URL. Allowable values are: UseCookies; UseUri; AutoDetect; and UseDeviceProfile (the default). Step 2 examines this setting in more detail.
defaultUrl
Indicates the URL that users are redirected to after signing in from the login page if there is no RedirectUrl value specified in the querystring. The default value is default.aspx.

------------------------
Steps for WCF Security
------------------------

There are FOUR core security features that WCF addresses:-

Confidentiality:- This feature ensures that the information does not go in wrong hands when it travels from the sender to the receiver.

Integrity:- This feature ensures that the receiver of the message gets the same information that the sender sends without any data tampering.

Authentication:- This feature verifies who the sender is and who the receiver is.

Authorization:- This feature verifies whether the user is authorized to perform the action they are requesting from the application.

--------------------------------------------------------------
advantages and disadvantages of transport VS message security
--------------------------------------------------------------

transport security :-
-------------------
When there are no intermediate systems in between this is the best methodology.
If it’s an intranet type of solution this is most recommended methodology.

advantages :-
Does not need any extra coding as protocol inherent security is used.
Performance is better as we can use hardware accelerators to enhance performance.
There is lot of interoperability support and communicating clients do not need to understand WS security as it’s built in the protocol itself.

disadvantages :-
As it’s a protocol implemented security so it works only point to point.
As security is dependent on protocol it has limited security support and is bounded to the protocol security limitations.

message security :-
----------------
When there are intermediate systems like one more WCF service through which message is routed then message security is the way to go.

advantages :-
Provides end to end security as it’s not dependent on protocol. Any intermediate hop in network does not affect the application. Supports wide set of security options as it is not dependent on protocol. We can also implement custom security.

disadvantages :-
Needs application refactoring to implement security.
As every message is encrypted and signed there are performance issues.
Does not support interoperability with old ASMX webservices/

----------------------------------------------------------------------
What is the difference between BasicHttpBinding and WsHttpBinding ?
----------------------------------------------------------------------

Security support

BasicHttpBinding
This supports the old ASMX style i.e WS-BasicProfile 1.1.

WsHttpBinding
This exposes web services using WS-* specifications.

Compatibility

BasicHttpBinding :
This is aimed for clients who do not have .Net 3.0 installed and it supports wider ranges of client. Many of clients like Windows 2000 still do not run .NET 3.0. So older version of .NET can consume this service.

WsHttpBinding :
As its built using WS-* specifications it does not support wider ranges of client and it cannot be consumed by older .NET version less than 3 version.

Soap version

BasicHttpBinding :
SOAP 1.1

WsHttpBinding :
SOAP 1.2 and WS-Addressing specification.

Reliable messaging

BasicHttpBinding
Not supported. In other words if a client fires two or three calls you really do not know they will return back in the same order.

WsHttpBinding
Supported as it supports WS-* specifications.

Default security options

BasicHttpBinding
By default there is not security provided for messages when the client calls happen. In other words data is sent as plain text.

WsHttpBinding
As WsHttBinding supports WS-* it has WS-Security enabled by default. So the data is not sent in plain text.

Security options

BasicHttpBinding:
None
Windows – default authentication.
Basic
Certificate

WsHttpBinding:
None
Transport.
Message.
Transport with message credentials.

By default ‘BasicHttpBinding’ sends data in plain text while ‘WsHttpBinding’ sends in encrypted and secured manner.

By Default security is not enabled on ‘BasicHttpBinding’ for interoperability purpose

Java Script and Telerik Control Validations

Alert message with Body onload
-------------------------------
< head >
< script type="text/javascript" >
function msg()
{
alert("This alert box was called with a onload event");
}
< /script >

< /head >

< body onload="msg()" >

< /body

Write text in Javascript in body
-------------------------------
< body >
< script type="text/javascript" >
document.write("< h1 >Hello World!< /h1 >");
< /script >
< /body >


Call external Javascript xxx.js in body
-------------------------------

< body >

< script type="text/javascript" src="xxx.js" >
< /script >

< p >
The actual script is in an external script file called "xxx.js".
< /p >

< /body >



JavaScript statements.
-------------------------------

< body >

< script type="text/javascript" >
document.write("< h1 >This is a heading< /h1 >");
document.write("< p >This is a paragraph.< /p >");
document.write("< p >This is another paragraph.< /p >");
< /script >

< /body >




JavaScript Commants
-------------------------------
// Write a heading


/*
The code below will write
one heading and two paragraphs
*/




JavaScript Blocks
-------------------------------
Blocks start with a left curly bracket {, and ends with a right curly bracket }.

< script type="text/javascript" >
{
document.write("< h1 >This is a heading< /h1 >");
document.write("< p >This is a paragraph.< /p >");
document.write("< p >This is another paragraph.< /p >");
}
< /script >






JavaScript with Variable
-------------------------------

< script type="text/javascript" >
var firstname;
firstname="Hege";
document.write(firstname);
document.write("< br / >");
firstname="Tove";
document.write(firstname);
< /script >



JavaScript with If Statement
-------------------------------
< script type="text/javascript" >
var d = new Date();
var time = d.getHours();

if (time < 10)
{
document.write("< b >Good morning< /b >");
}
< /script >








JavaScript with If else Statement
-------------------------------

< script type="text/javascript" >
var d = new Date();
var time = d.getHours();

if (time < 10)
{
document.write("< b >Good morning< /b >");
}
else
{
document.write("< b >Good day< /b >");
}
< /script >




JavaScript with Random link
-------------------------------
< script type="text/javascript" >
var r=Math.random();
if (r >0.5)
{
document.write("< a href='http://www.w3schools.com' >Learn Web Development!< /a >");
}
else
{
document.write("< a href='http://www.refsnesdata.no' >Visit Refsnes Data!< /a >");
}
< /script >




JavaScript with Switch statement
--------------------------------
< script type="text/javascript" >
var d = new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("< b >Finally Friday< /b >");
break;
case 6:
document.write("< b >Super Saturday< /b >");
break;
case 0:
document.write("< b >Sleepy Sunday< /b >");
break;
default:
document.write("< b >I'm really looking forward to this weekend!< /b >");
}
< /script >




JavaScript with Alert Message
--------------------------------

< head >
< script type="text/javascript" >
function show_alert()
{
alert("I am an alert box!");
}
< /script >
< /head >
< body >

< input type="button" onclick="show_alert()" value="Show alert box" / >

< /body >



JavaScript with Alert box with line breaks
--------------------------------------------

< head >
< script type="text/javascript" >
function disp_alert()
{
alert("Hello again! This is how we" + '\n' + "add line breaks to an alert box!");
}
< /script >
< /head >
< body >

< input type="button" onclick="disp_alert()" value="Display alert box" / >

< /body >



JavaScript with Confirm message with display text
-------------------------------------------------

< script type="text/javascript" >
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
{
document.write("You pressed OK!");
}
else
{
document.write("You pressed Cancel!");
}
}
< /script >
< /head >
< body >

< input type="button" onclick="show_confirm()" value="Show a confirm box" / >

< /body >






JavaScript with Prompt box with display text
---------------------------------------------
< head >
< script type="text/javascript" >
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
{
document.write("Hello " + name + "! How are you today?");
}
}
< /script >
< /head >
< body >

< input type="button" onclick="show_prompt()" value="Show a prompt box" / >

< /body >





JavaScript Functions
-----------------------------

< script type="text/javascript" >
function displaymessage()
{
alert("Hello World!");
}
< /script >
< /head >

< body >
< form >
< input type="button" value="Click me!" onclick="displaymessage()" / >
< /form >

< p >By pressing the button above, a function will be called. The function will alert a message.< /p >

< /body >





JavaScript Functions with Argument
-------------------------------------
< head >
< script type="text/javascript" >
function myfunction(txt)
{
alert(txt);
}
< /script >
< /head >
< body >

< form >
< input type="button" onclick="myfunction('Hello')" value="Call function" >
< /form >

< p >By pressing the button above, a function will be called with "Hello" as a parameter. The function will alert the parameter.< /p >

< /body >



JavaScript Functions with 2 argument
-------------------------------------
< head >
< script type="text/javascript" >
function myfunction(txt)
{
alert(txt);
}
< /script >
< /head >

< body >
< form >
< input type="button"
onclick="myfunction('Good Morning!')"
value="In the Morning" >

< input type="button"
onclick="myfunction('Good Evening!')"
value="In the Evening" >
< /form >

< p >
When you click on one of the buttons, a function will be called. The function will alert
the argument that is passed to it.
< /p >

< /body >



JavaScript Functions call to another function with return value body to head tag
---------------------------------------------------------------------------------
< head >
< script type="text/javascript" >
function myFunction()
{
return ("Hello world!");
}
< /script >
< /head >
< body >

< script type="text/javascript" >
document.write(myFunction())
< /script >

< /body >




JavaScript Function with arguments, that returns a value
-------------------------------------------------
< head >
< script type="text/javascript" >
function product(a,b)
{
return a*b;
}
< /script >
< /head >

< body >
< script type="text/javascript" >
document.write(product(4,3));
< /script >

< p >The script in the body section calls a function with two parameters (4 and 3).< /p >
< p >The function will return the product of these two parameters.< /p >
< /body >




JavaScript FOR Loops
--------------------------



< body >

< script type="text/javascript" >
for (i = 0; i < = 5; i++)
{
document.write("The number is " + i);
document.write("< br / >");
}
< /script >

< p >Explanation:< /p >

< p >This for loop starts with i=0.< /p >

< p >As long as < b >i< /b > is less than, or equal to 5, the loop will continue to run.< /p >

< p >< b >i< /b > will increase by 1 each time the loop runs.< /p >

< /body >





JavaScript FOR Looping through HTML headers
---------------------------------------------
< body >

< script type="text/javascript" >
for (i = 1; i < = 6; i++)
{
document.write("< h" + i + " >This is heading " + i);
document.write("< /h" + i + " >");
}
< /script >

< /body >





JavaScript While loop
----------------------------
< body >

< script type="text/javascript" >
i=0;
while (i< =5)
{
document.write("The number is " + i);
document.write("< br / >");
i++;
}
< /script >

< p >Explanation:< /p >
< p >< b >i< /b > is equal to 0.< /p >
< p >While < b >i< /b > is less than , or equal to, 5, the loop will continue to run.< /p >
< p >< b >i< /b > will increase by 1 each time the loop runs.< /p >

< /body >





JavaScript Do While loop
-------------------------------------

< script type="text/javascript" >
i = 0;
do
{
document.write("The number is " + i);
document.write("< br / >");
i++;
}
while (i < = 5)
< /script >

< p >Explanation:< /p >

< p >< b >i< /b > equal to 0.< /p >

< p >The loop will run< /p >

< p >< b >i< /b > will increase by 1 each time the loop runs.< /p >

< p >While < b >i< /b > is less than , or equal to, 5, the loop will continue to run.< /p >


< /body >






JavaScript Break a loop
----------------------------

< body >
< script type="text/javascript" >
var i=0;
for (i=0;i< =10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("< br / >");
}
< /script >
< p >Explanation: The loop will break when i=3.< /p >
< /body >





JavaScript Break and continue a loop
---------------------------------------

< body >
< script type="text/javascript" >
var i=0;
for (i=0;i< =10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("< br / >");
}
< /script >

< p >Explanation: The loop will break the current loop and continue with the next value when i=3.< /p >

< /body >




JavaScript Use a for...in statement to loop through the elements of an array
----------------------------------------------------------------------------
< body >
< script type="text/javascript" >
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (x in mycars)
{
document.write(mycars[x] + "< br / >");
}
< /script >
< /body >





JavaScript Error Handling The try...catch statement
----------------------------------------------------------------------------


< head >
< script type="text/javascript" >
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.description + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
< /script >
< /head >

< body >
< input type="button" value="View message" onclick="message()" / >
< /body >




JavaScript Error Handling the try...catch statement with a confirm box
----------------------------------------------------------------------------

< head >
< script type="text/javascript" >
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Click OK to continue viewing this page,\n";
txt+="or Cancel to return to the home page.\n\n";
if(!confirm(txt))
{
document.location.href="http://www.w3schools.com/";
}
}
}
< /script >
< /head >

< body >
< input type="button" value="View message" onclick="message()" / >
< /body >


JavaScript Error Handling The onerror event
-------------------------------------------------



< head >
< script type="text/javascript" >
onerror=handleErr;
var txt="";

function handleErr(msg,url,l)
{
txt="There was an error on this page.\n\n";
txt+="Error: " + msg + "\n";
txt+="URL: " + url + "\n";
txt+="Line: " + l + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
return true;
}

function message()
{
adddlert("Welcome guest!");
}
< /script >
< /head >

< body >
< input type="button" value="View message" onclick="message()" / >
< /body >





JavaScript Detect the visitor's browser and browser version
-------------------------------------------------------------

< body >
< script type="text/javascript" >
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);
document.write("Browser name: "+ browser);
document.write("< br / >");
document.write("Browser version: "+ version);
< /script >
< /body >




JavaScript Detect the visitor's browser and browser version with more details
----------------------------------------------------------------------------
< body >
< script type="text/javascript" >
document.write("< p >Browser: ");
document.write(navigator.appName + "< /p >");

document.write("< p >Browserversion: ");
document.write(navigator.appVersion + "< /p >");

document.write("< p >Code: ");
document.write(navigator.appCodeName + "< /p >");

document.write("< p >Platform: ");
document.write(navigator.platform + "< /p >");

document.write("< p >Cookies enabled: ");
document.write(navigator.cookieEnabled + "< /p >");

document.write("< p >Browser's user agent header: ");
document.write(navigator.userAgent + "< /p >");
< /script >
< /body >




JavaScript Detect All details about the visitor's browser
------------------------------------------------------------

< body >

< script type="text/javascript" >
var x = navigator;
document.write("CodeName=" + x.appCodeName);
document.write("< br / >");
document.write("MinorVersion=" + x.appMinorVersion);
document.write("< br / >");
document.write("Name=" + x.appName);
document.write("< br / >");
document.write("Version=" + x.appVersion);
document.write("< br / >");
document.write("CookieEnabled=" + x.cookieEnabled);
document.write("< br / >");
document.write("CPUClass=" + x.cpuClass);
document.write("< br / >");
document.write("OnLine=" + x.onLine);
document.write("< br / >");
document.write("Platform=" + x.platform);
document.write("< br / >");
document.write("UA=" + x.userAgent);
document.write("< br / >");
document.write("BrowserLanguage=" + x.browserLanguage);
document.write("< br / >");
document.write("SystemLanguage=" + x.systemLanguage);
document.write("< br / >");
document.write("UserLanguage=" + x.userLanguage);
< /script >

< /body >







JavaScript Alert user, depending on browser
-----------------------------------------------

< head >
< script type="text/javascript" >
function detectBrowser()
{
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(b_version);
if ((browser=="Netscape"||browser=="Microsoft Internet Explorer") && (version >=4))
{
alert("Your browser is good enough!");
}
else
{
alert("It's time to upgrade your browser!");
}
}
< /script >
< /head >

< body onload="detectBrowser()" >
< /body >





JavaScript Create a welcome cookie
------------------------------------------

< head >
< script type="text/javascript" >
function getCookie(c_name)
{
if (document.cookie.length >0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1 ;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end));
}
}
return ""
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; expires="+exdate.toGMTString());
}

function checkCookie()
{
username=getCookie('username');
if (username!=null && username!="")
{
alert('Welcome again '+username+'!');
}
else
{
username=prompt('Please enter your name:',"");
if (username!=null && username!="")
{
setCookie('username',username,365);
}
}
}
< /script >
< /head >
< body onLoad="checkCookie()" >
< /body >



JavaScript Button animation
--------------------------------
< head >
< script type="text/javascript" >
function mouseOver()
{
document.getElementById("b1").src ="b_blue.gif";
}
function mouseOut()
{
document.getElementById("b1").src ="b_pink.gif";
}
< /script >
< /head >

< body >
< a href="http://www.w3schools.com" target="_blank" >
< img border="0" alt="Visit W3Schools!" src="b_pink.gif" id="b1" width="26" height="26" onmouseover="mouseOver()" onmouseout="mouseOut()" / >< /a >
< /body >






JavaScript Button animation Image map with added JavaScript
------------------------------------------------------------
< head >
< script type="text/javascript" >
function writeText(txt)
{
document.getElementById("desc").innerHTML=txt;
}
< /script >
< /head >

< body >
< img src ="planets.gif" width ="145" height ="126" alt="Planets" usemap="#planetmap" / >

< map name="planetmap" >
< area shape ="rect" coords ="0,0,82,126"
onMouseOver="writeText('The Sun and the gas giant planets like Jupiter are by far the largest objects in our Solar System.')"
href ="sun.htm" target ="_blank" alt="Sun" / >

< area shape ="circle" coords ="90,58,3"
onMouseOver="writeText('The planet Mercury is very difficult to study from the Earth because it is always so close to the Sun.')"
href ="mercur.htm" target ="_blank" alt="Mercury" / >

< area shape ="circle" coords ="124,58,8"
onMouseOver="writeText('Until the 1960s, Venus was often considered a twin sister to the Earth because Venus is the nearest planet to us, and because the two planets seem to share many characteristics.')"
href ="venus.htm" target ="_blank" alt="Venus" / >
< /map >

< p id="desc" >< /p >

< /body >





JavaScript Button Simple timing
-------------------------------------------

< head >
< script type="text/javascript" >
function timedMsg()
{
var t=setTimeout("alert('5 seconds!')",5000);
}
< /script >
< /head >

< body >
< form >
< input type="button" value="Display timed alertbox!" onClick = "timedMsg()" >
< /form >
< p >Click on the button above. An alert box will be displayed after 5 seconds.< /p >
< /body >





JavaScript Another Simple timing
-------------------------------------------
< head >
< script type="text/javascript" >
function timedText()
{
var t1=setTimeout("document.getElementById('txt').value='2 seconds!'",2000);
var t2=setTimeout("document.getElementById('txt').value='4 seconds!'",4000);
var t3=setTimeout("document.getElementById('txt').value='6 seconds!'",6000);
}
< /script >
< /head >

< body >
< form >
< input type="button" value="Display timed text!" onClick="timedText()" >
< input type="text" id="txt" >
< /form >
< p >Click on the button above. The input field will tell you when two, four, and six seconds have passed.< /p >
< /body >



JavaScript Timing event in an infinite loop
-------------------------------------------------
< head >
< script type="text/javascript" >
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
< /script >
< /head >

< body >
< form >
< input type="button" value="Start count!" onClick="doTimer()" >
< input type="text" id="txt" >
< /form >
< p >Click on the button above. The input field will count forever, starting at 0.< /p >
< /body >







JavaScript Timing event in an infinite loop - with a Stop button
------------------------------------------------------------------

< head >
< script type="text/javascript" >
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}

function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
< /script >
< /head >

< body >
< form >
< input type="button" value="Start count!" onClick="doTimer()" >
< input type="text" id="txt" >
< input type="button" value="Stop count!" onClick="stopCount()" >
< /form >
< p >
Click on the "Start count!" button above to start the timer. The input field will count forever, starting at 0. Click on the "Stop count!" button to stop the counting.
< /p >
< /body >




JavaScript A clock created with a timing event
-----------------------------------------------

< head >
< script type="text/javascript" >
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers< 10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}

function checkTime(i)
{
if (i< 10)
{
i="0" + i;
}
return i;
}
< /script >
< /head >

< body onload="startTime()" >
< div id="txt" >< /div >
< /body >



JavaScript Create a direct instance of an object
-------------------------------------------------

< body >

< script type="text/javascript" >
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";

document.write(personObj.firstname + " is " + personObj.age + " years old.");
< /script >

< /body >








JavaScript Create a template for an object
----------------------------------------------------------------------------
< body >

< script type="text/javascript" >
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}

myFather=new person("John","Doe",50,"blue");

document.write(myFather.firstname + " is " + myFather.age + " years old.");
< /script >

< /body >







--------------------------------------------------------
How to Use Java Script Validation
--------------------------------------------------------

function ConfirmDelete() {

if (confirm("Are you sure you want to delete the Subject?")) {
return true;
}
else {
return false;
}
}




-------------------------------
Empty Check validation
----------------------------------

Radalert (Telerik control)


function validate()
{
if (document.getElementById('< %=txtSubjectId.ClientID % >').value == "") {
radalert('Please Enter BusinessRole Name');
return false;
} else if (document.getElementById('< %=txtSubjectName.ClientID % >').value == "") {
radalert('Please Select Application Role Number');
return false;
} else if (document.getElementById('< %=txtSubShortName.ClientID % >').value == "") {
radalert('Please Select Application Role Number');
return false;
}
else {
return true;
}
}



In Button
---------
OnClientClick="return validate();"




--------------------------------------------------------
Java Script with Time Validation
--------------------------------------------------------

In UI
-------

< html xmlns="http://www.w3.org/1999/xhtml" >
< head runat="server" >
< title >Untitled Page< /title >
< script language="javascript" type="text/javascript" >
function startclock() {
var thetime = new Date();

var nhours = thetime.getHours();
var nmins = thetime.getMinutes();
var nsecn = thetime.getSeconds();
var AorP = " ";

if (nhours >= 12)
AorP = "P.M.";
else
AorP = "A.M.";

if (nhours >= 13)
nhours -= 12;

if (nhours == 0)
nhours = 12;

if (nsecn < 10)
nsecn = "0" + nsecn;

if (nmins < 10)
nmins = "0" + nmins;

document.clockform.clockspot.value = nhours + ":" + nmins + ":" + nsecn + " " + AorP;

setTimeout('startclock()', 1000);

}

< /script >
< /head >
< body onLoad="startclock()" >
< form id="clockform" runat="server" >
< div >
Current Time: < input type="text" name="clockspot" size="15" / >
< /div >
< /form >
< /body >
< /html >


--------------------------------------------------------
In Numberic Validation in JavaScript
--------------------------------------------------------



< html xmlns="http://www.w3.org/1999/xhtml" >
< head runat="server" >
< title >Numeric Entry Only< /title >
< script language='javascript' type="text/javascript" >
function isNumeric()
{
if(!(event.keyCode==48||event.keyCode==49||event.keyCode==50||event.keyCode==51||event.keyCode==52||event.keyCode==53||event.keyCode==54||event.keyCode==55||event.keyCode==56||event.keyCode==57))
{
event.returnValue=false;
}
}
< /script >
< /head >
< body >
< form id="form1" runat="server" >
< div >
< asp:TextBox ID="TextBox1" onkeypress="return isNumeric();" runat="server" >< /asp:TextBox >
< /div >
< /form >
< /body >
< /html >





--------------------------------------------------------
PopUp Script in JavaScript PopupScript.js
--------------------------------------------------------



function gradient(id, level) {
var box = document.getElementById(id);
box.style.opacity = level;
box.style.MozOpacity = level;
box.style.KhtmlOpacity = level;
box.style.filter = "alpha(opacity=" + level * 100 + ")";
box.style.display = "block";
return;
}


function fadein(id) {
var level = 0;
while (level < = 1) {
setTimeout("gradient('" + id + "'," + level + ")", (level * 1000) + 10);
level += 0.01;
}
}
function openbox(fadin, bgdiv, contentdiv,msgid,msg) {
var box = document.getElementById(contentdiv);
document.getElementById(bgdiv).style.display = 'block';
document.getElementById(msgid).innerHTML = msg;
//alert(document.getElementById(msgid).innerHTML);
if (fadin) {
gradient(contentdiv, 0);
fadein(contentdiv);
}
else {
box.style.display = 'block';
}
}


// Close the lightbox

function closebox(bgdiv, contentdiv) {
document.getElementById(contentdiv).style.display = 'none';
document.getElementById(bgdiv).style.display = 'none';
}




---------------------------------
Time Validation in JavaScript
---------------------------------

// Time Validation
// IsValidTime(document.timeform.time.value);

function IsValidTime(timeStr) {

var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
var matchArray = timeStr.match(timePat);
if (matchArray == null) {
alert("Time is not in a valid format.");
return false;
}


hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];


if (second=="") { second = null; }
if (ampm=="") { ampm = null }

if (hour < 0 || hour > 23) {
alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
return false;
}
if (hour < = 12 && ampm == null) {
if (confirm("Please indicate which time format you are using. OK = Standard Time, CANCEL = Military Time")) {
alert("You must specify AM or PM.");
return false;
}
}
if (hour > 12 && ampm != null) {
alert("You can't specify AM or PM for military time.");
return false;
}
if (minute< 0 || minute > 59) {
alert ("Minute must be between 0 and 59.");
return false;
}
if (second != null && (second < 0 || second > 59)) {
alert ("Second must be between 0 and 59.");
return false;
}
return false;
}



============================================
Validate Date format in javascript
=====================================

function isValidDate(strDate){
var dteDate;
var day, month, year;
var datePat = /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/;
var matchArray = strDate.match(datePat);

if (matchArray == null)
return false;

day = matchArray[1]; // p@rse date into variables
month = matchArray[3];
year = matchArray[5];
month--;

dteDate=new Date(year,month,day);
return ((day==dteDate.getDate()) && (month==dteDate.getMonth()) && (year==dteDate.getFullYear()));
}


----------------------------------------------
Java script Validation with restrict the user entering file name directly to the textbox
----------------------------------------------
You can restrict the user entering file name directly to the textbox by writing a Keypress event as

Script

< script language="javascript" >
function onkeyPress(e)
{
var key = window.event ? e.keyCode : e.which;
if (key == 13)
StartClick();
e.cancelBubble = true;
e.returnValue = false;
return false;
}
< /script >

Html

< input id="File1" style="position: relative" type="file" onkeypress="return onkeyPress(event);" >

Can u be still clear on the other validation to be done.


----------------------------------------------
Validation with file name directly to the textbox for regular expression
----------------------------------------------

var reg = new RegExp("^(? >[a-z]:)?(? >\\|/)?([^\\/?%*:|\"< >\r\n]+(? >\\|/)?)+$", "i");






====================================
Client side : Name Validation using JavaScript
====================================

// ascii code between (65 to 90) and (97 to 122) and (32)
// in regName /^[a-zA-Z]/


function IsValidName(objTextbox)
{
var regName;
regName = /^[a-zA-Z]/
strTitle = objTextbox.value;

if(!(regName.test(strTitle)))
{
return false;
}
return true;

}



OR


function OnlyAlphabets()
{
if(document.all)
{
if(event.keyCode >=65 && event.keyCode < =90) || (event.keyCode >=97 && event.keyCode < =122) || (event.keyCode == 32)
event.returnValue = true;
else
event.returnValue = false;
}
else
{
if((event.which >= 65 && event.which < =90) || (event.which >=97 && event.which< =122) || (event.which == 32))
return true;
else
return false;
}
}

OR

// Validate enter only Alphabetic char only

function AlphabaticCharactervalidate(event) {
var keyCode = (event.which) ? event.which : (window.event) ? window.event.keyCode : -1;
if (keyCode >= 65 && keyCode < = 90 || keyCode >= 97 && keyCode < = 122) {
return true;
}
if (keyCode == 8 || keyCode == -1 || keyCode == 32) {
return true;
}
else {
return false;
}
}

// Code Behand add fire event
txtSchoolname.Attributes.Add("onKeyPress", "javascript:return AlphabaticCharactervalidate(event);");

====================================
Client side : Address Validation using JavaScript
====================================

function Addressvalidate(event) {
var keyCode = (event.which) ? event.which : (window.event) ? window.event.keyCode : -1;
if (keyCode >= 65 && keyCode < = 90 || keyCode >= 97 && keyCode < = 122 || keyCode >= 48 && keyCode < = 57) {
return true;
}
if (keyCode == 8 || keyCode == -1 || keyCode == 32 || keyCode == 35 || keyCode == 46 || keyCode == 40 || keyCode == 41 || keyCode == 44) {
return true;
}
else {
return false;
}
}

// In code Behand page_load call event
TextBox address = (TextBox)usrcontrol.FindControl("txtAddress");
address.Attributes.Add("onKeyPress", "javascript:return Addressvalidate(event);");
address.Attributes.Add("onPaste", "javascript:return false;");



====================================
Client side : File Type Validation using JavaScript
====================================

function ValidateFileType() {
var FileLength = document.getElementById('< %=uploadStudentImage.ClientID% >').value.length;
var filename = document.getElementById('< %=uploadStudentImage.ClientID% >').value;
var dot = filename.lastIndexOf(".");
var extension = filename.substr(dot, filename.length);
if (extension == ".gif" || extension == ".jpg" || extension == ".png" || extension == ".GIF" || extension == ".JPG" || extension == ".PNG" || extension == ".jpeg" || extension == ".JPEG") {
return true;
}
else {
radalert(extension + " File Not Allowed.", 230, 110);
return false;
}




====================================
Client side : Number Validation using JavaScript
====================================
// ascii code between (45 to 57) and (Not 47)
// regName = /^[0-9]/


function(objTextBox)
{
var regName;
regName = /^[0-9]/
objTitle = objTextBox.value

if(!(regName(objTitle)))
{
return false
}
return true
}




OR


function OnlyNumberic()
{
if(document.all)
{
if(event.keyCode < =45 && event.keyCode >=57) || (event.keyCode == 47)
event.returnValue = false;
else
event.returnValue = true;
}
else
{
if(event.which < = 45 && event.which >=57) || (event.which == 47)
return false;
else
return true;
}

}

OR

function(value)
{
var ichar = "0123456789";
var objvalue = value;

for(var i=0;i< =ichar.length;i++)
{
if(ichar.IndexOf(objvalue.charAt(i)) == -1)
return false;
}
return true;
}


OR

// validate enter only numbers

function digitvalidate(event) {
var keyCode = (event.which) ? event.which : (window.event) ? window.event.keyCode : -1;
if (keyCode >= 48 && keyCode < = 57) {
return true;
}
if (keyCode == 8 || keyCode == -1 || keyCode == 43 || keyCode == 32) {
return true;
}
else {
return false;
}
}

// Code behand fire event like control name txtPhone

TextBox phone = (TextBox)usrcontrol.FindControl("txtPhone");
phone.Attributes.Add("onKeyPress", "javascript:return digitvalidate(event);");
phone.Attributes.Add("onPaste", "javascript:return false;");






=============================================
Client side : only AlphaNumberic Validation using JavaScript
=============================================
// check total 30 special charactors
// if charactors like ( \ " ') available than before that charactor add ( \ ) charactor

function OnlyAlphaNumberic(val)
{
var iChars = "!@#$%^&*()_+=-[]\\\';,./{}\":< >?~";
for(var i=0; i< val.length; i++)
{
if(iChars.indexOf(val.charAt(i)) != -1)
{
return false;
}
}
return true;
}







=============================================
Client side : only Get Date (change format) Validation using JavaScript
=============================================

function getDate(day,month,year)
{
var Day = day.selectedIndex
var Month = month.selectedIndex
var Year = year.selectedIndex
if(Day==0 && Month==0 && Year==0)
{
return "";
}
Day = day.options[Day].value
Month = month.options[Month].value
Year = year.options[Year].value
return Month + "/" + Day + "/" + Year
}





=============================================
Client side : Telerik : This function check and uncheck all checkbox of rad gridview by Header checkbox click event. using JavaScript
=============================================


function CheckBox_Click(gridControlId, cellIndex, checkBoxClentId) {
var radGrid = $find(gridControlId);
var objGrid = radGrid.get_masterTableView().get_element().tBodies[0];
var objCheckBox = document.getElementById(checkBoxClentId);

var cell;
if (objGrid.rows.length > 0) {
//loop starts from 0. rows[0] points to the header.
for (i = 0; i < objGrid.rows.length; i++) {
//get the reference of first column
cell = objGrid.rows[i].cells[cellIndex];

//loop according to the number of childNodes in the cell
for (j = 0; j < cell.childNodes.length; j++) {
//if childNode type is CheckBox
if (cell.childNodes[j].type == "checkbox") {
//assign the status of the Select All checkbox to the cell checkbox within the grid
cell.childNodes[j].checked = objCheckBox.checked;
}
}
}
}
}




=============================================
Client side : This function display rad telerik calander above podel popup panel.using JavaScript
=============================================


function displayCalender(sender, args) {
//Set Z-Index of calender control.
Telerik.Web.UI.Calendar.Popup.zIndex = 100100;
}




=============================================
Client side : Telerik : This function check wether any checkbox is checked/selected or not in rad telerik gridview.If not checked then alert to user
=============================================

function clientSideValidation(event, sender, buttonId, hdfClassVacancy, hdfClassName) {
//var grid = document.getElementById("< %=radgrdStudentForAdmissionNo.ClientID % >");
//masterTableView.get_element().tBodies[0].rows.length
var radGrid = $find(sender);
var classVacancy = document.getElementById(hdfClassVacancy);
var className = document.getElementById(hdfClassName);
var grid = radGrid.get_masterTableView().get_element().tBodies[0];
var isChecked = 0;
if (grid.rows.length > 0) {
//loop starts from 0. rows[0] points to the header.
for (i = 0; i < grid.rows.length; i++) {
//get the reference of first column
cell1 = grid.rows[i].cells[0];

//loop according to the number of childNodes in the cell
for (j = 0; j < cell1.childNodes.length; j++) {
//if childNode type is CheckBox
if (cell1.childNodes[j].type == "checkbox") {
if (cell1.childNodes[j].checked) {
//if it is checked then set isChecked to 1.
isChecked++;
}
}
}
}
}

if (isChecked == 0) {
showMessage("Select atleast one record.", "Eduquer");
return false;
}
else {
__doPostBack(buttonId);
}

}

function clientSideValidationAlert(event, sender, buttonId, dueDate, hdfClassVacancy, hdfClassName) {
var radGrid = $find(sender);
var date = $find(dueDate);
var grid = radGrid.get_masterTableView().get_element().tBodies[0];
var classVacancy = document.getElementById(hdfClassVacancy);
var className = document.getElementById(hdfClassName);
var isChecked = 0;
if (grid.rows.length > 0) {
//loop starts from 0. rows[0] points to the header.
for (i = 0; i < grid.rows.length; i++) {
//get the reference of first column
cell1 = grid.rows[i].cells[0];

//loop according to the number of childNodes in the cell
for (j = 0; j < cell1.childNodes.length; j++) {
//if childNode type is CheckBox
if (cell1.childNodes[j].type == "checkbox") {
if (cell1.childNodes[j].checked) {
//if it is checked then set isChecked to 1.
isChecked++;
}
}
}
}
}

if (isChecked == 0) {
showMessage("Select atleast one record.", "Eduquer");
return false;
}
else {
if (className.value != '') {
if (parseInt(classVacancy.value) < isChecked) {
blockConfirm("Vacancy is less than your selection,< br/ >Are you sure to send admission slip anyway.", event, 400, 150, null, "Eduquer");
}
else {
if (date.get_textBox().value == '') {
showMessage("Due date is required.", "Eduquer");
return false;
}
else {
__doPostBack(buttonId);
}
}
}
else {
radalert("Class selection is mandatory to send admission slip.< br/ > Please select class from search criteria.", 325, 150, "Eduquer");
return false;
}
}
}




=============================================
Client side : Telerik : This functon open modal popup from client side with validation.
=============================================

function openPopupWindowClientSide(popupControl, gridControl, hdfClassName) {
var radGrid = $find(gridControl);
var popup = $find(popupControl);
var className = document.getElementById(hdfClassName);
var grid = radGrid.get_masterTableView().get_element().tBodies[0];
var isChecked = 0;
if (grid.rows.length > 0) {
//loop starts from 0. rows[0] points to the header.
for (i = 0; i < grid.rows.length; i++) {
//get the reference of first column
cell1 = grid.rows[i].cells[0];

//loop according to the number of childNodes in the cell
for (j = 0; j < cell1.childNodes.length; j++) {
//if childNode type is CheckBox
if (cell1.childNodes[j].type == "checkbox") {
if (cell1.childNodes[j].checked) {
//if it is checked then set isChecked to 1.
isChecked = 1;
}
}
}
}
}

if (isChecked != 1) {
//alert if checked is 0
//alert("Select at least one record.");
showMessage("Select atleast one record.", "Eduquer");
}
else {
//display model popup panel
if (className.value != '')
popup.show();
else
showMessage("Class selection is mandatory to send invitation mail.< br/ > Please select class from search criteria.", "Eduquer");
}
return false;
}






=============================================
Client side : This function allow user to enter only interger value.
=============================================


function validNumber(event) {
//if Keycode not between 0 to 9 return false
var keyCode = (event.which) ? event.which : (window.event) ? window.event.keyCode : -1;
if (keyCode >= 48 && keyCode < = 57) {
return true;
}
if (keyCode == 8 || keyCode == -1) {
return true;
}
else {
return false;
}
}



=============================================
Client side : This function E-mail Validation
=============================================

if (email.value.length > 0) {
var emailfilter = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;
var emailid = email.value;
var returnval = emailfilter.test(emailid);
if (returnval == false) {
ShowRadAlertAndFocusObject("Please Enter Valid Email Address.", email);
return false;
}



=============================================
Client side : Telerik : This function validate selection of independent combobox item selection.
=============================================

function validateSelection(cmbParent, message) {
var cmbParentCombo = $find(cmbParent);
if (cmbParentCombo._value == '-1' || cmbParentCombo._value == '0' || cmbParentCombo._value == '') {
showMessage(message, "Eduquer");
return false;
}
}




=============================================
Client side : Telerik : This function shows rad alert message box
=============================================

function showMessage(message, title) {
radalert(message, 300, 150, title);

}





=============================================
Client side : Telerik : This function clear all field of Student Written test filter panel
of student short list page.
=============================================


function clearStudentWrittenTestFilterPanel() {
$find(radCmbStudSeekClassWrTId).clearSelection();
$find(radCmbStudSeekMediumWrTId).clearSelection();
$find(radCmbStudAcademicYearWrTId).clearSelection();
return false;
}





=============================================
Client side : Telerik : This function shows rad alert message box : radComboBox Validation
=============================================


function ValidateSibling() {
var objSiblingFName = document.getElementById(SiblingFName);
var objSiblingRelation = document.getElementById(SiblingRelation);
objSiblingFName.value = trim(objSiblingFName.value);
if (objSiblingFName.value == "") {
ShowRadAlertAndFocusObject('Enter Sibling First Name.', objSiblingFName);
return false;
}
else if (objSiblingRelation.value == "--Select One--") {
radalert('Select Sibling Relation', 300, 150, 'Eduquer');
objSiblingRelation.focus();
return false;
}
else {
return true;
}
}




=============================================
Client side : Telerik : This function shows rad alert message box : Empty Check
=============================================


// TextBox Empty Check

function ValidateFeeDetails() {
var objPaidAmount = document.getElementById(PaidAmount);
objPaidAmount.value = trim(objPaidAmount.value);
if (objPaidAmount.value == "") {
ShowRadAlertAndFocusObject('Enter Paid Amount', objPaidAmount);
return false;
}
else
return true;
}


// Combo Selection Check


function ValidateLanguage() {
var objLanguageKnown = document.getElementById(LanguageKnown);

if (objLanguageKnown.value == "--Select One--") {
radalert('Select Language', 300, 150, 'Eduquer');
return false;
}



// show the rad alert message with focus

function ShowRadAlertAndFocusObject(strMessage, objToFocus) {
var rdAlert = radalert(strMessage, 300, 150, 'Eduquer');
var focusObject = function() { SetFocusAfterRadAlert(objToFocus); }
rdAlert.add_close(focusObject);
}


// set the focu for input object

function SetFocusAfterRadAlert(obj) {
obj.focus();
}


// trim the input values

function trim(strValue) {
return strValue.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
}


OR
--

function trim(sString) {
while (sString.substring(0, 1) == ' ') {
sString = sString.substring(1, sString.length);
}
while (sString.substring(sString.length - 1, sString.length) == ' ') {
sString = sString.substring(0, sString.length - 1);
}
return sString;
}









============================================================================
Client side : This function shows telerik Grid Columns and rows Identfying and Validating
============================================================================


//percentage txt box tab out
function preventExtraSeats(curentTxtBxId) {

var currentPercentage = 0;
var totalDiscountPercentage = 0;
var grid = $find(VacancyGridId).get_masterTableView().get_dataItems().length;
var txtBxTtlSeats = document.getElementById(txtTotalSeatsId).value;
var enteredPercentage = 0;

for (var i = 0; i < grid; i++) {
var txtSeatId = $find(VacancyGridId).get_masterTableView().get_dataItems()[i].findElement("txtPercentage").id;
if (txtSeatId != curentTxtBxId) {
if (trim($find(VacancyGridId).get_masterTableView().get_dataItems()[i].findElement("txtPercentage").value) != "") {
totalDiscountPercentage += parseFloat($find(VacancyGridId).get_masterTableView().get_dataItems()[i].findElement("txtPercentage").value);
}
}
else { enteredPercentage = $find(VacancyGridId).get_masterTableView().get_dataItems()[i].findElement("txtPercentage").value; }
}

// //alert(totalDiscountPercentage);

if (trim(enteredPercentage) != '' && !isNaN(enteredPercentage)) {
currentPercentage = parseFloat(enteredPercentage);
}
// //alert(currentPercentage);
if ((totalDiscountPercentage + currentPercentage) > 100) {
showRadAlert('Entered seat distribution % is more than 100%.');
//setTimeout(function() { document.getElementById(curentTxtBxId).value = ''; document.getElementById(curentTxtBxId).focus() }, 10);
document.getElementById(curentTxtBxId).value = '';
ShowRadAlertAndFocusObject(document.getElementById(curentTxtBxId));
return false;
}

}


Multi Layers Application Development

=============================================
How to develop Multi layer Application
=============================================

Below example to create five layers of application

1.Data Access Object Layer
2.Business Component Layer
3.WCF Service Layer
4.Business Data Transaction Object Layer
5.UI Layer


---------------------------------------------------------------
Using Technologies : c#, Enterprise Library, SP's in sql server
---------------------------------------------------------------

Database connection string
--------------------------
1.Server or Data Source
2.Initial Catalog or Database
3.Userid
4.Password
5.ProviderName = "System.Data.SqlClient"

Example :-
connectionString="Data Source=--;Initial Catalog=--;User ID=--;Password=--" providerName="System.Data.SqlClient"


In Web.Config
-------------

< connectionStrings >
< add name="conName" connectionString="Data Source=--;Initial Catalog=--;User ID=--;Password=--" providerName="System.Data.SqlClient"/ >
< /connectionStrings >
< appSettings/ >


1. Create Dao project with class (Data Access Layer)
====================================================
using System;
using System.Text;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System.ComponentModel;
using PjtDac.DACHelper;
using PjtDacBDto.1;

// Get List method

public BindingList< BDto1 > GetList(Int32 UnicId)
{

IDataReader dRead1 = null;
Database db = null;
DbCommand dbcmd1 = null;

BindingList< BDto1 > objBdto1List = new BindingList< BDto1 > ();
db = DatabaseFactory.CreateDatabase("conName");
dbcmd1 = db.GetStoredProcCommand("StoredProcedureName");
dRead1 = db.ExecuteReader(dbcmd1);
while (dRead1.Read())
{

BDto1 obj1BDto = new BDto1();
if (dRead1["UserId"] != DBNull.Value)
obj1BDto.UserId= Convert.ToInt32(dRead1["UserId"]);
if (dRead1["Name"] != DBNull.Value)
obj1BDto.Name = dRead1["Name"].ToString();
objBdto1List.Add(obj1BDto);
}
return objBdto1List

}


// Insert or Update method

public BindingList< BDto1 > InsertMethod(BDto1 obj1BDto)
{

IDataReader dRead1 = null;
Database db = null;
DbCommand dbcmd1 = null;

BindingList< BDto1 > objBdto1List = new BindingList< BDto1 > ();
db = DatabaseFactory.CreateDatabase("conName");
dbcmd1 = db.GetStoredProcCommand("StoredProcedureName");

db.AddInParameter(dbcmd1, "@Id", DbType.Int32, obj1BDto.Id);
db.AddInParameter(dbcmd1, "@Name", DbType.String, obj1BDto.Name);
db.AddOutParameter(dbcmd1, "@isExists", DbType.Int32, Int32.MaxValue);
db.ExecuteNonQuery(dbcmd1);

if (db.GetParameterValue(dbcmd1, "@isExists") != DBNull.Value)
isExists = Convert.ToInt32(db.GetParameterValue(dbcmd1, "@isExists"));
if (isExists == 0)
return true; // SUCCESSFUL INSERTION RETURN TRUE
else
return false; // UNSUCCESSFUL INSERTION RETUN FALSE ( ALREADY EXISTS )
}



// Delete method


public Int32 DeleteMethod(BDto1 obj1BDto)
{
Database db = null;
DbCommand dbcmd1 = null;
int objerror = 0;

db = DatabaseFactory.CreateDatabase("conName");

dbcmd1 = db.GetStoredProcCommand("StoredProcedureName");

db.AddInParameter(dbcmd1, "@Id", DbType.Int32, obj1BDto.Id);
db.AddOutParameter(dbcmd1, "@errorCode", DbType.Int32, 4);
db.ExecuteNonQuery(dbcmd1);
if (db.GetParameterValue(dbcmd1, "@errorCode") != DBNull.Value)
objerror = Convert.ToInt32(db.GetParameterValue(dbcmd1, "@errorCode"));
return objerror;

}




// Idisposiable

public class ClsDao : IDisposable
{
public void Dispose()
{
GC.Collect();
}

}




// Exception Handling
=====================

try
{
---------
---------
}
catch(Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex,"DataAccess Layer Exception Policy")
if (rethrow)
{
throw ex;
}
}

finally
{
Destroy(ref dbcmdSubject);
}




// Method to call in the Finally block
---------------------------------------

public static void Destroy(ref DbCommand dbCmd)
{
if (dbCmd != null)
{
if (dbCmd.Connection.State == ConnectionState.Open)
{
dbCmd.Connection.Close();
}
}

dbCmd = null;
}




StoredProcedudres
==================

// 1. Insert or Update

Create Procedure spInsertUpdate
(
@ id tinyint,
@ Name nvarchar(50)
@isExist int=0 output
)
AS
BEGIN

if exists(select id from tblUser where id=@id Name=@Name)
BEGIN
Set @IsExists = 1
return
END

if NOT EXISTS(select id from tbluser where id=@id OR Name=@Name)
BEGIN
Insert into tbluser (name) values (@Name)
END
ELSE IF NOT EXISTS(select id from tbluser where id< > @id and Name=@Name)
BEGIN
update tbluser set Name=@Name where id=@id
END
ELSE
BEGIN
SET @IsExists =1
return
END
END



// Get list Stored procedure

CREATE PROCEDURE SpGetList
AS
BEGIN
select Id,LTRIM(RTRIM(Name)As Name from tbluser
END


// Delete storedprocedure

create procedure SpDelete
(
@id tinyint,
@errorCode int=0 output
)
as
begin try
delete from tbluser where id in (select [value] from dbo.udf_SplitBy(@id,','))
end try

begin catch
select @errorCode = ERROR_NUMBER()
end catch
return @errorCode

// if error than it returns = 547




2. Create BC project with class (Business Component Layer)
==========================================================
using System;
using System.Text;
using System.Data;
using System.ComponentModel;
using PjtDao;
using PjtBc;
using PjtBDto;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;


public class clsBC : IDisposable
{

// Get list method

public BindingList< BDto1 > GetList(Int32 Unicid)
{
using(Dao1 objDao1=new Dao1())
{
return objDao1.GetList(Unicid);
}
return null;
}


// Insert or Update method
public bool InsertUpdate(BDto1 objBDto)
{
using(Dao1 objDao1=new Dao1())
{
return objDao1.InsertUpdate(objBDto)
}
return false;
}

// Delete method

public Int32 Del1(BDto1 objBDto1)
{
int objreturn = 0;
using (dao1 objdao1 = new dao1())
{
objreturn = objdao1.Del(objBDto1);
}
return objreturn;
}


// Idisposiable
public void Dispose()
{
GC.Collect();
}



}


3. WCF Service Layer
=====================
// Interface

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using PjtBDto1;
using System.ComponentModel;

[ServiceContract]
public interface Iuser
{

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
BindingList< BDto1 > GettList(Int32 unicId);

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
bool InsertUpdate(BDto1 obj1BDto);

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
BindingList< BDto1 > GettList(Int32 unicId);

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
Int32 Del1(BDto1 obj1BDto);

}

//ExceptionFields is an enum containing two members
//“ERROR” and “INCORRECT_OPERATION”.
[DataContract]
public class ExceptionClass
{
[DataMember]
public ExceptionFields errorcode;
[DataMember]
public string message;
[DataMember]
public string details;
}
// Used for holding exception fields
public enum ExceptionFields
{
[EnumMember]
ERROR,
[EnumMember]
INCORRECT_OPERATION
}



// Service class


using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.ComponentModel;
using PjtDao;
using PjtBc;
using PjtBDto;

public class Service1 : IService1
{
public BindingList< BDto1 > GetList(Int32 UnicId)
{
using(BC1 ObjBc1=new BC1)
{
return objBc1.GetList(UnicId);
}
return null;
}


}


// Exception Handling in WCF Service Layer
try

{

}

catch(Exception ex)
{
ExceptionClass error=new ExceptionClass();
error.errorcode = ExceptionFields.ERROR;
error.message = "General Exception"
error.details = ex.StackTrace;
throw new FaultException< ExceptionClass > (error);

}

// Service Exceptions in class of Catch block

ActionNotSupportedException
AddressAccessDeniedException
AddressAlreadyInUseException
ChannelTerminatedException
CommunicaitonException
Exception

// Handling same in all catch block
--------
ExceptionClass error=new ExceptionClass();
error.errorcode = ExceptionFields.ERROR;
error.message = "General Exception"
error.details = ex.StackTrace;
throw new FaultException< ExceptionClass > (error);






4. Create BDto Project with class (Business Data Transaction Layer)
====================================================================


-------------------
How to create BDto
-------------------

// Create BTto to decleare properties.
// also we can write Individual like for Contants,Address etc in different class

using System;

[Serializable]
public class BDto1
{


private String m_firstName = String.Empty;
private String m_middleName = String.Empty;
private String m_lastName = String.Empty;
private String m_fullName = String.Empty;


#region FirstName

public String FirstName
{
get
{
return m_firstName;
}
set
{
m_firstName = value;
}
}
#endregion

#region MiddleName

public String MiddleName
{
get
{
return m_middleName;
}
set
{
m_middleName = value;
}
}
#endregion

#region LastName
public String LastName
{
get
{
return m_lastName;
}
set
{
m_lastName = value;
}
}
#endregion

#region FullName
public String FullName
{
get
{
return m_fullName;
}
set
{
m_fullName = value;
}
}
#endregion



}




5. Create UI Project with class (User interface layer)
======================================================

using System;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Web.UI;
using System.ServiceModel;
using PjtBDto.BDto1;
using PjtService1;
using System.web;



// Get List in Teleric DataGrid binding


public void Bind_DataGrid()
{

dg1.DataSource = null;
dg1.DataBind();

// Calling service to Grid Popup operation
int UnicId = 1;
service1.ServiceClient objSerice1=new service1.ServiceClient();
System.ComponentModel.BindingList< BDto1 > objBL = new System.ComponentModel.BindingList< BDto1 >
objBL = objService1.GetList(UnicId);
objService1.close();

if(objBL != null)
{
dg1.DataService =objBL;
ViewState["v1"] = objBL;
dg1.DataBind();

}

}



// Get List in Teleric radCombo (DropdownList) binding

public void radCOMBO1Popup()
{
int UnicId = 1;
service1.ServiceClient objSerice1=new service1.ServiceClient();
System.ComponentModel.BindingList< BDto1 > objBL = new System.ComponentModel.BindingList< BDto1 >
objBL = objService1.GetList(UnicId);
objService1.Close();
ViewState["V2"] = objBL;
radCombo1.DataSource = objBL;
radCombo1.DataTextField = "Name";
radCombo1.DataValueField = "id";
radCombo1.DataBind();
radCombo1.Item.Insert(0,new RadCOmboBoxItem("-Select-"));
}