ASP.NET Validation Controls

Below are types of asp.net validation controls:
1. Required FieldValidator
    Ensures user does not left control without data.
Reference:  How to: Validate Required Entries for ASP.NET Server Controls.

2. RangeValidator
   Check if entered values are in between given upper and lower boundries.
Reference:   How to: Validate Against a Range of Values for ASP.NET Server Controls.

3. RegularExpressionValidator
   Checks that entered data matches to the given pattern of Regular Expression.
Reference:  How to: Validate Against Patterns for ASP.NET Server Controls.

4. CompareValidator
    Compares the values entered by user with other control or constant value or
Reference: How to: Validate Against a Specific Value for ASP.NET Server Controls and How to: Validate Against a Data Type for ASP.NET Server Controls.

5. Custom Validator
   Check the entered values agains the logic you write yourself for validation.
Reference: How to: Validate with a Custom Function for ASP.NET Server Controls and How to: Validate Against Values in a Database for ASP.NET Server Controls.

ASP.Net Page life Cycle Events

Below are ASP.net Page life Cycle Events:

1.PreInit
   We can use PreInit event to check IsPostBack property, if it is a new request or is it a postback. Also Master pages, Themes and profile values get set dynamically here. No control data ans control properties values from viewsate is loaded here.

2.Init
   This event get raised after all controls get initialized. Use this event to read and initialize controls properties.

3.Init Complete
  Raised by Page object and used to complete all initialization.
  
4.PreLoad
   Use this event to do some process on the controls or page before loads event occures. This load viewstate data for page and itls all contrlos

5.Load
   Page and it's all controls and controls child controlls totally get loaded during this event. Use this event to set the properties of the controls.

6.Control Events
    Use this event to handle specific controls event like button click event.

7.Load Ccomplete
   Use this event to do the tasks inorder to complete the page loading.

8. PreRender
   This event occure for every control on page and use this event to apply final changes to controls.

9.Save State complete
   This event performs the tasks that required to save view state.

10.Render
   Page object call Render method of all the controls that writes the markup for each control.

11.Unload
  This event occures for page and its all controls. Use this event to do final work on page like closinf opened files, closing database connection..etc

ASP.Net Page Life Cycle

How page life cycle works in asp.net?
  • Page request:
            This is a stage before page life cycle starts. This step happens when user sends request for page. ASP.Net decides whether to parse and compile the requested page or just catched verions of page need to be send in response.
  • Start:
           In this step page request and response properties get set. Also page determines whether it is a page post back ot it is a new request and based on that sets IsPostBack() property value and also sets UICulture.
  • Page Initialization:
         In this step all the controls on page a available and each controls unique Id's get set. Also themes get set. But data is not loaded for the controls and control property values are not restored from viewstate.
  • Page load:
        In this step if request is a postback request then dat get loaded fro controls from viewstate and control state.
  • Validation:
        In this step Validate method of all valiation controls get called and it sets IsValid property of each individual validator control and of the page.
  • Postback event handling:
          If reuest is a postback, event handlers get called.
  • Rendering:
           In this step, page calls render method for each control and writes output to page response proerty. Before Rendering viewsate get saved for page and all it's controls.
  • Unload:
           This step happens when page and it's controls are fully loaded and sent to the client and ready to be discarded. Page properties like Response and Request are unloaded at this phase.

ASP.NET State management

    Whenever page is posted to the server, a new instance of the Web page class is created each time. This means that all information associated with the page and the controls on the page get lost with each round trip.
    To overcome this situation, ASP.NET provides various options to preserve the data. These are known as state management techniques:

Client-Side or Client-based State Management options:
·         View state
·         Control state
·         Hidden fields
·         Cookies
·         Query strings
View state, control state, hidden fields, cookies, and query strings all involve storing data on the client.
Server-side or Server-based State Management options:
·         Application state
·         Session state
·         Profile Properties
             application state, session state, and profile properties all store data in memory on the server.

While dealing with client-based options for state management it stores information either in the page or on the client computer.  Information is not maintained on the server between round trips.

View State

While page processing, the current state of the page and it’s all controls get hashed into a string and then saved in the form of hidden field on the page. If specified value in MaxPageStateFieldLength property get exceeds than the data to be stored then it get stored in multiple hidden fields.  When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.
The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.
Control State:
In order to persist or preserve the control data we can use control state option. For example,  we have a tab control that needs to be preserve selected tab in between post backs to server we can use control sate option..
We can use ViewState here, but it may possible that at page level ViewState is turned off.
The ControlState property allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property.

Hidden Fields:
  Hiddenfields are also used to store values on page. Hidden file does not render on page. Hiddenfield stores data in it's Value property. To make hiddenfield values available during page precoessing we need to submit the page using HTTP POST method or command. Hiddenfield values are not available using HTTP GET command.

Cookies:
 Cookie is nothing but the small amount of that is stored on client's browser using text file on client's file system on in memory.
Ex.
Define and set value in cookie:
Response.Cookie["MyValue"].Value = "Test Value";
Get Cookie value

lblCookieText = Request.Cookies["MyValue"].Value;

Query String:
 Using Querystring application passes information or data by appending it to URL using question mark "?" like:

http://www.mywebsite.com?Name="Test Name"&phone="1234";

QueryString provides easy but 'limited' way to pass data from one page to other. To make querystring available during page processing, page must be submitted using HTTP GET command.

Application State:
   Application state provides way be store data which can be acessible globally in application. Application state uses System.Web.ApplicationState class.
Example:
    Defining and storing application state:
    Application["Name"] = "My Web";

// Accessing application variable value
string name;
if (Application["Name"] != null)
      name = Application["Name"].ToString();

Session State:
 Session state is way to store data in session variable for the current single browser session. If different users uses application , each users session state will be different.
Session State stroed in below three ways/ Session State Modes:

1. InProc: Means storing session in memory of the web server. It is the defualt session storage. InProc mode is high performant as it get read from same process. But it get affected by Worker process as both are in same process.

2. Stateserver: Storage location is server memeory with a seperate process, and not with the same process with asp.net worker process. This is less perfoamant process than InProc but it does not get affected in asp.net worker process get affected.

3.SQL Server:  Stores the data in SQL server database.

Garbage collection in asp.net

How Garbage Collector(GC) works?

How Garbage Collector (GC) works?
Microsoft .NET CLR environment provides automatic memory management using Garbage Collection (GC). Garbage Collection (GC) basically a process that frees or releases the object from the memory which is no longer is in use by program. When we create new object Common Language Runtime (CLR) allocates the memory to new object on managed heap. Till the time memory has free space runtime allocates it to a new object but when memory gets full Garbage Collection comes into the picture. Garbage Collection GC basically performs memory clean up in order to make space available for other newly created object.

Benefits of Garbage Collections are that it allows us to develop application without implementing logic to free memory. Also it allocates objects on memory very efficiently. It reclaims the objects those are no longer in use and frees the memory for new objects to be allocated. Also provides safe memory operations by making sure that one object cannot use other object

When Garbage collection(GC) Occurs or run?

Garbage collection happens for below conditions.
  • If system has low memory
  • If the memory allocated to object exceeds.
  •  if GC.Collect get called.
How Garbage Collector(GC) keep track of object's life?
The heap is organized in generations so that it can keep track of short time spaned object and long time spaned objects i.e. (short-lived and long lived objects). Garbage collection occures for short time spaned object who occupies small part of heap. There are three types of generations on the heap:

  • Gen 0
              It contains short spaned objects.GC collection mostly happen in Gen0. Newly allocated object are  implicitly comes under Gen0 if object is not a large object. Example: Temp variables or local variables to the process.
  • Gen 1
             It is buffer between short spaned object memory and long spaned object memory. if Gen0  space is not enough for newly allocated object then data moved to Gen1.
  • Gen 2
           It contains objects with long span and going to be used for long period. Example: global variables those are going to be used through out the applicaion life.


How to clear unmanaged resources?
Unmanaged resources are the resources that does not taking care by CLR. Means those are not cleared from memory using Garbage Colletion(GC). File system object, database connection objects, windows handlers...etc are the examples of unmanaged resources.
We can use both implicit and explicit way to free such unmanages resources. Implicit way is to implement Finalize Method on an object. GC (Garbage Collector) calls this method when object is no longer referenced.

Explicit way is to implement  IDisposable Interface and it's  Dispose method.

jQuery Events Part - II : Mouse Events - Continue....

jQuery mouse evemts

.hover()
hover mouse event triggers to the element when user take mouse over the perticular element.

Example of hover mouse event:

<div> id="hoverDiv">Change Color </div>
$(document).ready(function() 
{  
$("hoverDiv").hover( 
function () { 
$(this).css("backgroundcolor", 'blue'); 
} 
);
});



.mousedown()
mousedown() mouse event triggers when user clicks on the the perticular element.

Example of mousedown event:

    <div> id="hoverDiv">Change Color</div>
    $(document).ready(function() 
    {  
    $("hoverDiv").mousedown( 
    function () {
    alert('Mouse Down event fired for div')
    } 
    );
    });
    


.mouseenter()
mouseenter() mouse event triggers when user enter to the area of perticular element. This is different from .hover in the way the event bubbling happens. If we have element inside element and mouse enters to inside element the mouseenter event will not fire for ouside element. But in case of .mouseover() mouse event it will fire for both inner and outter element. For more info: http://api.jquery.com/mouseenter/

Example that shows mouse enter event

    <div> class="out enter">
        <p>move your mouse</p>
        <p>0</p>
    </div>
    var i = 0;
    $("div.enter").mouseenter(function(){
    $("p:first",this).text("mouse enter");
    $("p:last",this).text(++i);
    }); 
    


.mouseleave()
mouseleave() mouse event triggers when user leaves the area of perticular element. This is different from .hover in the way the event bubbling happens. If we have element inside element and mouse leaves from inside element the mouseleave event will not fire for ouside element. But in case of .mouseout() mouse event it will fire for both inner and outter element. For more info: http://api.jquery.com/mouseenter/

Example that shows mouse leave event

    <div> class="out leave">
        <p>move your mouse</p>
        <p>0</p>
    </div>

    var i = 0;
    $("div.leave").mouseleave(function(){
    $("p:first",this).text("mouse leave");
    $("p:last",this).text(++i);
    }); 
    

jQuery Events Part - II : Mouse Events

jQuery mouse events

In this post we will look how jQuery mouse events works. jQuery library provides mouse events like click, double click, mouseup, mousedown, toggle..etc. Using this jQuery events one can easily perform the required operations or actions. We will look jQuery events samples in this post.

.click()
click event get triggered to an element when mouse button is pressed and released on that element. Any HTML element can trigger this event.

Sample code for jQuery click event:


<a id="mouseclick" href="mouseclickdemo.aspx">Click here</a>

$(document).ready(function() 
{  
$("#mouseclick").click(function(){
alert("This is jQuery Mouse Click event.")
});
});

In above jQuery code for click event will triggered and alter with “This is jQuery Mouse click event” will get displayed.

.dblclick()
dblclick event get triggered to an element when mouse button is pressed and released twice on that element. Any HTML element can trigger this event.

Below sample code shows how jQuery double click (dblclick) event works:

<div id="mousedblclick"> Click here</div>
$(document).ready(function() 
{  
$("#mousedblclick".dblclick(function(){
alert("This is jQuery mouse dblClick event.")
});
});

Above code shows that after double clicking on div tag it will trigger jQuery dblclick event and will show alert message “This is mouse dblclick event.”

.mousedown()
mousedown event get triggered to an element when mouse button is moved over the element and mouse button is pressed . Any HTML element can trigger this event.

Below sample code shows how jQuery mouse down event works:

    <span id="mousedown">Click here</span>

    $(document).ready(function() 
    {  
    $("#mousedown").mousedown(function(){
    alert("jQuery mousedown event.")
    });
    });

In above sample of jQuery, when mouse down event triggers then it will show alert message “jQuery mousedown event.”


.mouseup()
mouseup event get triggered to an element when mouse button is pressed and then released. Any HTML element can trigger this event.

Below is sample jQuery code for mouseup event:

<div id="mouseup"> Click here</ div>
$(document).ready(function() 
{  
$("#mouseup").mouseup(function(){
alert("jQuery mouseup event.")
});
});
When mouse button is released then jQuery mouse event will get triggered and it will show alert message “jQuery mouseup event.”


.toggle()
toggle event used to do the alternate actions for perticular operation. Which is used in association with click.

code shows how jQuery toggle event works :

<div id="toogleDiv"> Change Color </div>

$(document).ready(function() 
{  
$("toogleDiv").toggle( 
function() { 
$(this).css("backgroundcolor", 'blue'); 
}, 
function () { 
$(this).css("backgroundcolor",'green');
});
});
jQuery toggle event used to change the state of object from one state to other. for example we can show or hide div element using toggle event. Toggle event works in association with click event. In above code sample when we click on div element it will change color from blue to green and if it already green then changes it to blue.

jQuery Events Part - I : Document loading Events and Keyboard Events

jQuery events

jQuery basically have following type of events:


.ready()

Indicates that DOM is fully loaded that mean all controls and it's hierarchy is fully loaded .This is the best place to do all event handling and jacascript/jQuery code manipulations.

Below example shows how to use .ready() in jQuery:


$(document).ready(function()
{  
  // Handler for .ready() called.
});


.load()
.load event executes code when page is rendered or a perticular element is rendered. Use this event when code is relies on loaded assests like images.

Below example show .load() in jQuery, and this triggers event when page is fully loaded with all control:


$(window).load(function()
{ 
 // Add code here
); 

You may call .load for perticular element when it loads.


<img src="something.png" id="imageDemo"/>



$("#imageDemo").load()(function(){
  // Add code here.
});


.unload()
Use this event when user navigates away from the page or window.
Below example shows how .unload() works in jQuery:

$(window).unload(function(){
alert('I am unloading.');
});


.keydown()

Event on element get triggered when user presses any key on keyboard. If you want keydown event get fired when user start typing in some text box.

Below example shows how .keydown() works in jQuery:
For textbox you can write it like


<input id="keyDownDemo" type="text" value="Hello"/>


$("#keyDownDemo").keydown(function(){ 
alert(Hello jQuery KeyDown Happened.');
});

jQuery basics

Basics of jQuery

In this post we will see very basic of jQuery.How to start with jQuery?jQuery, is a Javascript library with cross-browser support and open source which simplify the client side scripting in web/html.
It supports

  • DOM,
  • CSS manipulation,
  • Ajax,
  • animations and effect
  • extendible plugins.


Get Started using jQuery:
jQuery needs to add library in html or web page which is a .js file that contains Ajax funcions, effects, DOM, events ...etc. You can download jQuery library from http://docs.jquery.com/Downloading_jQuery

After downloading jQuery library add it to page like below:
Sample to start with jQuery:

<!DOCTYPE html >
< html>
<head>
<title>jQuery Demo</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<form id="Form1" method="post" runat="server">
</form>
</body>
</html>