Thursday, September 11, 2008

Authentication and Authorization in ASP.NET

  • Authentication is the process of verifying user's identity.

  • Authorization is the process of granting privilege to authenticated user.

  • The user is validated using authenticated process and then the authorization process identifies if the user has access to a given resource.

Authentication:-

  • Authentication is the process of obtaining identification credentials such as name and password from a user and validating those credentials against some authority. If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity. Once an identity has been authenticated, the authorization process determines whether that identity has access to a given resource.

  • In ASP.NET, we can authenticate user in code or allow the user to be authenticated by other party such as MS Passport.

  • There are two layer of authentication in ASP.NET

  1. IIS layer :- IIS performs authentication if it is configured to do so. By default, IIS allows anonymous access which means all the users are authenticated. All the requests pass through IIS layer and then to ASP.NET authentication process.If any user requests IIS layer for anonymous access, the user is treated as authenticated and pass to ASP.NET process.

  2. ASP.net authentication process layer :-ASP.NET checks if impersonation is enabled in the web configuaration file i.e. web.config file. If impersonation is enabled, ASP.net acts as though it were the authenticated user otherwise it process with its own configured account.

    • To enable the application to authenticate users, we need to add element in the authorization section of Web.config.

Authentication modes : -

  1. Windows Authentication :-Windows Authentication is the default authentication mechanism for ASP.NET applications .The windows authentication authenticates users based on their windows accounts. In short, it uses windows network security. It uses IIS to perform authentication.Windows authentication is best suited for the application which is meant for a corporate users.

  2. Passport authentication :-The Passport authentication uses Microsoft's passport service to authenticate users. The new user is directed to the Microsoft site where he can register his identity. This facilitates user to access multiple sites using single user name and password. You need to install the Passport SDK to enable the Passport classes in the System.Web.Security namespace.

  3. Form authentication :- The Form authentication collects user's credential and lets the application use own logic to authenticate users. The collected user's credential is validated using the list maintained by the application. The application maintains its own user list either using element in the web.config file or using database. The advantage of using form authentication is that the users don't need to be the member of windows network to have access to the application.Form authentication is preferable for the applications which have diversified users from several places.

we can set authentication mode from web.config file.

<authentication mode="windows">
<authentication mode="passport">
<authentication mode="forms">

Authorization:-

  • Authorization determines whether an identity should be granted access to a specific resource. In ASP.NET, there are two ways to authorize access to a given resource:

  1. File authorization :- File authorization is performed by the 'FileAuthorizationModule'. It checks the access control list (ACL) of the .aspx or .asmx handler file to determine whether a user should have access to the file. ACL permissions are verified for the user's Windows identity (if Windows authentication is enabled) or for the Windows identity of the ASP.NET process. For more information, see ASP.NET Impersonation.

  2. URL authorization :-URL authorization is performed by the 'UrlAuthorizationModule', which maps users and roles to URLs in ASP.NET applications. This module can be used to selectively allow or deny access to arbitrary parts of an application (typically directories) for specific users or roles.
    With URL authorization, we explicitly allow or deny access to a particular directory by user name or role. To do so, we create an authorization section in the configuration file for that directory. To enable URL authorization, we specify a list of users or roles in the allow or deny elements of the authorization section of a configuration file. The permissions established for a directory also apply to its subdirectories, unless configuration files in a subdirectory override them.

    - The syntax is as below

    <authorization>
    < [ allow deny ] [ users ] [ roles ] [ verbs ] />
    </authorization>

- For e.g below authorization section shows how to allow access to the abc identity and deny access to all other users

<authorization>
<allow users="abc">
<deny users="*">
</authorization>

- Here ' * ' refers to all identities and ' ? ' refers to anonymous identity

The allow or deny element is required. we must specify either the users or the roles attribute. Both can be included, but both are not required. The verbs attribute is optional.

- Attributes:-
1. users :-It will check the user accounts for this element.
2. roles :-It will check that the current request that is allowed or denied access to the resource.
3.verbs :-Defines the HTTP verbs to which the action applies, such as GET, HEAD, and POST.
- The following example grants access to Mary and members of the Admins role, while denying access to John ( unless John is a member of the Admins role ) and to all anonymous users.

<authorization>
<allow users = "Mary">
<allow roles = "Admins">
<deny users = "John">
<deny users = "?">
</authorization>

-Both users and roles can refer to multiple entities by using a comma-separated list such as in the following:
<allow users = "John, Mary, redmond\bar">

- Notice that the domain account [ redmond\bar ] must include both the domain and user name.
-The following example lets everyone do a GET, but only Mary can use POST:

<authorization>
<allow verb = "GET" users = "*">
<allow verb = "POST" users = "Mary">
<deny verb = "POST" users = "*">
</authorization>

Rules are applied using the following heuristics:

  • Rules defined in application-level configuration files take precedence over inherited rules. The system determines which rule takes precedence by constructing a merged list of all rules for a URL, with the most recent rules ( those nearest in the hierarchy ) at the head of the list.
  • Given a set of merged rules for an application, ASP.NET starts at the head of the list and checks rules until the first match is found.
    • If a match is found and the match is an <allow> element, the module grants access to the request.
    • If a match is found and the match is a <deny> element, the request is returned with a 401 HTTP status code.
    • If no rules match, the request is allowed unless otherwise denied.

Notice in the last situation, the request is allowed access even if no rules were matched. This happens so because the default configuration for ASP.NET defines an <allow users = "*"> element, which authorizes all users. By default, this rule is applied last.

To prevent this behavior, define a <deny users = "*"> element at the application level.

Like all other configuration settings, the access permissions established for a directory also apply to all of its subdirectories, unless explicitly overriden in a child configuration file.

Configuring authorization using the <location> element

Instead of defining access permissions in separate directory configuration files, you can also define one or more location elements in a root configuration file to specify the particular files or directories to which authorization settings defined in that location element should apply.

The following code example demonstrates how to allow an anonymous user to gain access to the Default.aspx page.

 <configuration>
<location path = "Logon.aspx">
<system.web>
<authorization>
<allow users = "?">
</authorization>
</system.web>
</location>
</configuration>

Wednesday, September 10, 2008

Caching In Asp.Net

Caching is used to speed up processing of an application.Caching is the process of taking information that is time-instensive to collect and storing it in a location that requires less time to access.
  • One could, fairly easily, build their own caching system using Application variables.We can use application-level variables as a cache to store database results. Since application variables are accessible from any page they are quite a logical choice for a caching system.
  • The main benefits of caching are performance-related: operations like accessing database information can be one of the most expensive operations of an ASP page's life cycle. If the database information is fairly static, this database-information can be cached.
  • When information is cached, it stays cached either indefinitely, until some relative time, or until some absolute time. Most commonly, information is cached for a relative time frame. That is, our database information may be fairly static, updated just a few times a week. Therefore, we might want to invalidate the cache every other day, meaning every other day the cached content is rebuilt from the database.
ASP.NET supports three types of caching for Web-based applications:
  1. Output Caching (Page Level Caching)
  2. Page Fragment Caching (often called Partial-Page Output Caching)
  3. Programmatic or Data Caching
Output Caching
  • Output Caching caches the HTML output of dynamic requests to ASP.NET Web pages.
  • Each time an incoming ASP.NET page request comes in, this engine checks to see if the page being requested has a cached output entry. If it does, this cached HTML is sent as a response; otherwise, the page is dynamically rendered, it's output is stored in the Output Cache engine.
  • Output Caching is particularly useful when we have very static HTML pages.
  • Output caching can be easily implemented using the @OuputCache page directive.
  • The syntax looks like this:
    • <%@OutputCache Duration="50" VaryByParam="none" %>
    • Duration:This parameter specifies how long, in seconds, the HTML output of the Web page should be held in the cache. When the duration expires, the cache becomes invalid and, with the next visit, the cached content is flushed, the ASP.NET Web page's HTML dynamically generated, and the cache repopulated with this HTML.
    • VaryByParam:This parameter is used to indicate whether any GET (QueryString) or POST (via a form submit with method="POST") parameters should be used in varying what gets cached. In other words, multiple versions of a page can be cached if the output used to generate the page is different for different values passed in via either a GET or POST.
      • The VaryByParam is a useful setting that can be used to cache different "views" of a dynamic page whose content is generated by GET or POST values. For example, you may have an ASP.NET Web page that reads in a Part number from the QueryString and displays information about a particular widget whose part number matches the QueryString Part number. Imagine for a moment that Output Caching ignored the QueryString parameters altogether (which you can do by setting VaryByParam="none"). If the first user visited the page with QueryString /ProductInfo.aspx?PartNo=4, she would see information out widget #4. The HTML for this page would be cached. The next user now visits and wished to see information on widget #8, a la /ProductInfo.aspx?PartNo=8. If VaryByParam is set to VaryByParam="none", the Output Caching engine will assume that the requests to the two pages are synonymous, and return the cached HTML for widget #4 to the person wishing to see widget #8! To solve for this problem, you can specify that the Output Caching engine should vary its caches based on the PartNo parameter by either specifying it explicitly, like VaryByParam="PartNo", or by saying to vary on all GET/POST parameters, like: VaryByParam="*".
Partial-Page Output Caching
  • More often than not, it is impractical to cache entire pages. For example, we may have some content on our page that is fairly static, such as a listing of current inventory, but you may have other information, such as the current stock price of any company, that we wish to not be cached at all. Since Output Caching caches the HTML of the entire ASP.NET Web page, clearly Output Caching cannot be used for these scenarios: enter Partial-Page Output Caching.
  • Partial-Page Output Caching, or page fragment caching, allows specific regions of pages to be cached. ASP.NET provides a way to take advantage of this powerful technique, requiring that the part(s) of the page you wish to have cached appear in a User Control. One way to specify that the contents of a User Control should be cached is to supply an OutputCache directive at the top of the User Control. That's it! The content inside the User Control will now be cached for the specified period, while the ASP.NET Web page that contains the User Control will continue to serve dynamic content.
  • For this we should not place an OutputCache directive in the ASP.NET Web page that contains the User Control - just put it inside of the User Control.
Data Caching
  • Sometimes, more control over what gets cached is desired. ASP.NET provides this power and flexibility by providing a cache engine. Programmatic or data caching takes advantage of the .NET Runtime cache engine to store any data or object between responses. That is, you can store objects into a cache.
  • This data cache is kept in memory and "lives" as long as the host application does. In other words, when the ASP.NET application using data caching is restarted, the cache is destroyed and recreated. Data Caching is almost as easy to use as Output Caching or Fragment caching.
  • The syntax looks like this:
    • - Cache["ABC"] = str; // C#
      - Cache("ABC") = str ' VB.NET
    • We Can retrive values by
    • - str = Cache["ABC"]; // C#
      - str = Cache("ABC") ' VB.NET
    • Note that after we retrieve a cache value in the above manner we should first verify that the cache value is not null prior to doing something with the data. Since Data Caching uses an in-memory cache, there are times when cache elements may need to be evicted. That is, if there is not enough memory and we attempt to insert something new into the cache, something else will be get!
    • The Data Cache engine does all of this scavenging for your behind the scenes, of course. However, don't forget that you should always check to ensure that the cache value is there before using it. This is fairly simply to do - just check to ensure that the value isn't null/Nothing. If it is, then you need to dynamically retrieve the object and restore it into the cache.

Thursday, August 21, 2008

Collections Overview in asp.net 2.0

Collections in .Net is having same use as Arrays,but there are certain limitations of the arrays like
  • The size of an array is always fixed and must be defined at the time of instantiation of an array.
  • An array can only contain objects of the same data type, which we need to define at the time of its instantiation.

So,In .net the concept of collections is very usefull to overcome from this limitaions.

The Namespace for Collections is

using System.Collections

.net 2.0 provides collections which are as described below.

  • ArrayList

ArrayList Provides the collection similar to Arrays,but it grows dynamically as the number of Elements change.

Example

static void Main()

{

ArrayList list = new ArrayList();

list.Add(11);

list.Add(22);

list.Add(33);

foreach(int num in list)

{

Console.WriteLine(num);

}

}

Output

11

22

33

  • Stack

A collection that works on the Last In First Out (LIFO) principle,

i.e., the last item inserted is the first item removed from the collection.

Push - To add element and

Pop – To Remove element

Example

class Test

{

static void Main()

{

Stack stack = new Stack();

stack.Push(2);

stack.Push(4);

stack.Push(6);

while(stack.Count != 0)

{

Console.WriteLine(stack.Pop());

}

}

}

Output

6

4

2

  • Queue

A collection that works on the First In First Out (FIFO) principle,

i.e.,the first item inserted is the first item removed from the collection.

Enqueue - To add element

Dequeue – To Remove element

Example:

static void Main()

{

Queue queue = new Queue();

queue.Enqueue(2);

queue.Enqueue(4);

queue.Enqueue(6);

while(queue.Count != 0)

{

Console.WriteLine(queue.Dequeue());

}

}

Output

2

4

6

  • Dictionaries

Dictionaries are a kind of collection that store items in a key-value pair fashion.

  • HashTable

Provides a collection of key-value pairs that are organizedbased on the hash code of the key.

Example:

static void Main()

{

Hashtable ht = new Hashtable(20);

ht.Add("key", "Hello");

ht.Add("key1", "Hello1");

ht.Add("key2", "Hello2");

Console.WriteLine("Printing Keys...");

foreach(string key in ht.Keys)

{

Console.WriteLine(key);

}

Console.WriteLine("\nPrinting Values...");

foreach(string Value in ht.Values)

{

Console.WriteLine(Value);

}

Console.WriteLine("Size of Hashtable is {0}", ht.Count);

Console.WriteLine(ht.ContainsKey("key"));

Console.WriteLine(ht.ContainsValue("Hello"));

Console.WriteLine("\nRemoving element with key = key1");

ht.Remove("key1");

Console.WriteLine("Size of Hashtable is {0}", ht.Count);

}

Output
Printing Keys...

key

key1

key2

Printing Values...

Hello

Hello1

Hello2

Size of Hashtable is 3

True

True

Removing element with key = key1

Size of Hashtable is 2

  • SortedList

Provides a collection of key-value pairs where the items are sorted according to the key.

The items are accessible by both the keys and the index.

Example:

static void Main()

{

SortedList sl = new SortedList();

sl.Add(18, "Java");

sl.Add(5, "C#");

sl.Add(11, "VB.Net");

sl.Add(1, "C++.Net");

Console.WriteLine("The items in the sorted order are...");

Console.WriteLine("\t Key \t\t Value");

Console.WriteLine("\t === \t\t =====");

for(int i=0; i

{

Console.WriteLine("\t {0} \t\t {1}", sl.GetKey(i),sl.GetByIndex(i));

}

}

Output
Key Value
==

1 C++.Net

5 C#

11 VB.Net

18 Java

Wednesday, August 20, 2008

ASP.Net 2.0 Page Life Cycle Events



  1. The page first retrieves the posted data from the QueryString or Form collection of the Request Object.

  2. The page then checks whether the posted Data collection (the NameValueCollection Form or QueryString) contains an item with the key __CALLBACKID. If it does, it sets its IsCallback Boolean property to true to signal that the page has been posted back to the server through theASP.NET client callback mechanism.

  3. PreInit: The page takes the following actions in the PreInit phase of its life cycle:
    A. Calls its OnPreInit method to raise the PreInit event.
    B. Initializes the theme by using the contents of the App_Themes directory to dynamicallyimplement a class of type PageTheme, compiles the class, creates an instance of thecompiled class, and assigns the instance to its PageTheme property.
    C. Applies the master page.

  4. Init: The page takes the following actions in the Init phase of its life cycle:
    A. Recursively initializes the controls in its Controls collection. This initializationincludes setting the properties of these controls such as Page, ID, NamingContainer,and so on.
    B. Recursively applies these controls’ skins.
    C. Calls its own OnInit method to raise its own Init event and then recursively calls thechild control’s OnInit methods to raise their Init events.
    D. Calls its own TrackViewState to start its own view state tracking and then recursivelycalls the child controls’ TrackViewState methods to start their view state tracking.

  5. InitComplete: The page calls its OnInitComplete method to raise the InitComplete event.This event signals the end of the initialization phase. By this time all controls in the Controlscollection of the page are initialized.

  6. Load Control State (postback only): The page recursively calls the LoadControlState method of those controls in its Controls collection that have called the RegisterRequiresControlState method of the page class to express interest in using their control states.

  7. Load View State (postback only): The page first calls its own LoadViewState method and then recursively calls the LoadViewState method of the controls in its Controls collection to allowthem to load their saved view states.

  8. Load Post Data (postback only - first try): The page calls the LoadPostData method of the controls that implement the IPostBackDataHandler interface and passes the posted data into it.The LoadPostData method of each control must access the posted data and update the respective property of the control accordingly. For example, the LoadPostData method of the TextBoxcontrol assigns the new value of the text box to the Text property of the TextBox control.

  9. PreLoad: The page calls its OnPreLoad method to raise the PreLoad event. This event signalsthe beginning of the load phase of the page life cycle.

  10. Load: The page first calls its own OnLoad method to raise its own Load event and then recursively calls the OnLoad methods of the controls in its Controls collection to raise their Load events. Page developers may register callbacks for the Load event, where they may programmaticallyadd child controls to the Controls collection of the page.

  11. Load Post Data (postback only second try): The page calls the LoadPostData method of those controls that were programmatically added to its Controls collection in the Load phase if theyimplement the IPostBackDataHandler interface.

  12. Raise Post Data Changed Event (postback only): The page calls the RaisePostData ChangedEvent method of those controls whose LoadPostData method returned true. The RaisePostDataChangedEvent method raises post data changed event. For example, the TextBox control raises this event when the new value of the text box is different from the old value.

  13. Raise Postback Event (postback only): The page calls the RaisePostBackEvent method of the control whose associated HTML element submitted the form. For example, the Button control’s associated HTML element posts the page back to the server. The RaisePostBackEvent methodof a control must map the postback event to one or more server-side events. For example, the RaisePostBackEvent method of the Button control maps the postback event to the Command and Click server-side events.

  14. Load Complete: The page calls its OnLoadComplete method to raise the LoadComplete event to signal the completion of all loading activities including loading post data and raising postdata changed event to allow interested controls to update themselves accordingly.

  15. Raise Callback Event (postback and callback only): The page calls the RaiseCallbackEvent method of the control that uses the ASP.NET client callback mechanism to allow a client-side method (such as a JavaScript function) to call a server-side method without having to post theentire page back to the server. The RaiseCallbackEvent method must call the respective server-side methods. If the page is posted back through the client callback mechanism, the pagewill not go through the rest of its life cycle phases.

  16. PreRender: The page takes the following actions in this phase of its life cycle:
    A. Calls its EnsureChildControls method to ensure its child controls are created before the page enters its rendering phase.
    B. Calls its own OnPreRender method to raise its own PreRender event.
    C. Recursively calls the OnPreRender methods of the controls in its Controls collection to raise their PreRender events.

  17. PreRender Complete: The page calls its OnPreRenderComplete method to raise thePreRenderComplete event to signal the completion of all prerendering activities.

  18. Save Control State: The page recursively calls the SaveControlState method of those controls in its Controls collection that have called the RegisterRequiresControlState method ofthe page class to express interest in saving their control states.

  19. Save View State: The page first calls its own SaveViewState method and then calls the SaveViewState method of the controls in its Controls collection to allow them to save their view states.

  20. Save State Complete: The page calls its OnSaveStateComplete method to raise theSaveStateComplete event to signal the completion of all save state activities.

  21. Rendering: The page takes the following actions in this phase of its life cycle:
    A. Creates an instance of the HtmlTextWriter class that encapsulates the output stream of the response.
    B. Calls its RenderControl method and passes the HtmlTextWriter instance into it.The RenderControl method recursively calls the RenderControl methods of the child controls to allow each child control to render its HTML markup text. The HTML markup texts ofchild controls form the final HTML markup text that is sent to the client browser.

Monday, August 4, 2008

Use of sp_help System Stored Procedure

In this blog i am going to explain the use of sp_help system stored procedure.It can be very useful for database developer.

sp_help
It gives information about various database objects i.e. any objects comes under sysobjects table,a user defined data type or a data type supplied by SQL server. It is executable for all public roles.It gives information of the current database only.
Syntax
sp_help [[@objname =] name]
Arguments
[@objname =] name
Is the name of any object, in sysobjects or any user-defined data type in the systypes table. name is nvarchar(776), with a default of NULL. Database names are not acceptable. The argument is optional.
Result Sets
1)Without giving any object name as parameters:It gives summary information of objects of all types that exist in the current database.
Exec sp_Help
Result : It gives columns of Name for Object Name,Owner for object owner and type for object





















Column name


Data type


Description


Name


nvarchar(128)


Object name


Owner


nvarchar(128)


Object owner


Object_type


nvarchar(31)


Object type




2)Give table name as an object name:
Exec sp_help tablename
Result: It gives datasets containing various information like table name.Owner,Created date time,object type, Column names,Column length,Column Data type,Nullable or not,Collations,Identity,Keys ,Constraint name,Constraint type,Constraint keys,Foreign key related information etc.





























Column name


Data type


Description


Name


nvarchar(128)


Table name


Owner


nvarchar(128)


Table owner


Type


nvarchar(31)


Table type


Created_datetime


datetime


Date table created

Depending on the database object specified, sp_help returns additional result sets.
If object name is a system table, user table, or view, sp_help returns these result sets (except the result set describing where the data file is located on a file group is not returned for a view).




















































Column name


Data type


Description


Column_name


nvarchar(128)


Column name.


Type


nvarchar(128)


Column data type.


Computed


varchar(35)


Indicates whether the values in the column are computed: (Yes or No).


Length


int


Column length in bytes.


Prec


char(5)


Column precision.


Scale


char(5)


Column scale.


Nullable


varchar(35)


Indicates whether NULL values are allowed in the column: Yes or No.


TrimTrailingBlanks


varchar(35)


Trim the trailing blanks (yes or no).


FixedLenNullInSource


varchar(35)


For backward compatibility only.





























Column name


Data type


Description


Identity


nvarchar(128)


Column name whose data type is declared as identity.


Seed


numeric


Starting value for the identity column.


Increment


numeric


Increment to use for values in this column.


Not For Replication


int


IDENTITY property is not enforced when a replication login, such as sqlrepl, inserts data into the table:

1 = True

0 = False















Column name


Data type


Description


RowGuidCol


sysname


Name of the global unique identifier column















Column name


Data type


Description


Data_located_on_filegroup


nvarchar(128)


The file group in which the data is located (Primary, Secondary, or Transaction Log)

























Column name


Data type


Description


index_name


sysname


Index name


Index_description


varchar(210)


Description of the index


index_keys


nvarchar(2078)


Column name(s) on which the index is built






































Column name


Data type


Description


constraint_type


nvarchar(146)


Type of constraint.


constraint_name


nvarchar(128)


Name of the constraint.


status_enabled


varchar(8)


Indicates whether the constraint is enabled: Enabled, Disabled or N/A. (Only applicable to CHECK and FOREIGN KEY constraints.


status_for_replication


varchar(19)


Indicates whether the constraint is for replication. (Only applicable to CHECK and FOREIGN KEY constraints.)


constraint_keys


nvarchar(2078)


Names of the columns that make up the constraint or, in the case for defaults and rules, the text that defines the default or rule.


















Column name


Data type


Description


Table is referenced by


nvarchar(516)


Identifies other database objects that reference the table.


If object name is a system stored procedure or an extended stored procedure, sp_help returns this result set.
Exec sp_help spname
Result :It gives datasets containing sp name sp type ,sp owner,sp's Created datetime,Parameter names,Parameter types,Parameter length,Collations etc.













































Column name


Data type


Description


Parameter_name


nvarchar(128)


Stored procedure parameter name


Type


nvarchar(128)


Data type of the stored procedure parameter


Length


smallint


Maximum physical storage length (in bytes)


Prec


int


Precision (total number of digits)


Scale


int


Number of digits to the right of the decimal point


Param_order


smallint


Order of the parameter










Saturday, August 2, 2008

Calculate Age from given Birthdate

As there was a requirement in my project to calculate age(Age in Year,Age in Month,Age in days) of an entity from his/her birthdate to the present date.

I have created one function in javascript which will calculate age(Age in Year,Age in Month,Age in days) from given birthdate.

The function is as given below.


1function CalculateAgeFromBirthdate(birthdate)
2
{
3

4 var birthdate;
5 birthdate = new
Date(birthdate);
6

7 var bYear = birthdate.getFullYear();//Year of birth

8 var bMonth = birthdate.getMonth() + 1; //Month of Birth

9 var bDay = birthdate.getDate(); //Day of Birth

10

11 var date = new Date(); // get current date

12 var cYear = date.getFullYear(); //Get current year

13 var cMonth = date.getMonth() + 1;//Get current month

14 var cDay = date.getDate();//Get Current Date
15

16 var g31Day=new Array(1,3,5,7,8,10,12);//Array of the months of 31 days

17 var g30Day=new Array(2,4,6,9,11); //Array of the months of 30 days

18 var gMonth=12
;
19 var
gDay;
20

21 var getCurentMont=cMonth//get current month

22 var getCurrentYear=cYear//get current year
23

24 for(var i=0;i < g31Day.length;i++
)
25
{
26

27

28 if (g31Day[i]==
getCurentMont)
29
{
30 gDay=31
;
31 break
;
32 }

33

34 }

35 for(var i=0;i < g30Day.length; i++
)
36 {

37

38 if(g30Day[i] ==
getCurentMont)
39
{
40 if(getCuurentMont=2
)
41
{
42 //For leap year

43 if(getCurrentYear % 4 == 0 (getCurrentYear % 100 != 0 && getCurrentYear % 4 == 0
))
44
{
45 gDay=29
;
46 break
;
47 }

48 else

49
{
50 gDay=28
;
51 break
;
52 }

53

54 }

55 else

56
{
57 gDay=30
;
58 break
;
59 }

60 }

61 }

62

63 var
years;
64 var
Day;
65 var
Month;
66

67 years = (cYear) -
parseInt(bYear);
68

69 Day = parseInt(cDay)-
parseInt(bDay);
70

71 Month = (cMonth)-
parseInt(bMonth);
72

73

74 if( Month < 0
)
75

76
{
77

78 gMonth=parseInt(gMonth)+
parseInt(Month) ;
79

80 Month=
gMonth;
81 years--
;
82 flag=true
;
83

84 }

85 if( Day < 0
)
86

87
{
88

89 gDay=parseInt(gDay)+
parseInt(Day) ;
90

91 Day=
gDay;
92

93 }

94

95 alert("I am of "+years+" years, "+Month+" month and "+Day +" days"
);
96

97 }


By passing Birthdate as Parameter it will calculate the age.