Showing posts with label Show all posts
Showing posts with label Show all posts

RangeValidator to validate data in between |

From the set of validation server controlin we will see how to use RangeValidator in this post.

RangeValidator is used to check if values entered are in between specific range or not. In order to use RangeValidator, we need to add server control on web form.

RangeValidator example:

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
        Enter a number between 0 and 5:
        <asp:TextBox ID="txtNumber" runat="server" />
        <asp:RangeValidator ID="RangeValidator1" ControlToValidate="txtNumber" MinimumValue="0"
            MaximumValue="5" Type="Integer" Text="The number should be in between 0 to 5."
            ForeColor="red" runat="server" />
        <asp:Button ID="Button1" Text="Submit" runat="server" />

In order to rangevalidator to be work we need to set few properties: 1. Minimum value
2. Maximum value
3. Control to validate
4. Type of data i.e. Interger, Date...etc.
5. And the Text for error message

Using RequiredFieldValidator to validate controls |

In ASP.NET there exists a set of validation server control which are useful to validate the data on form. In this post we will see how to use RequiredFieldValidator.

RequiredFieldValidator is used to check if field on the form is not empty. In order to use RequiredFiledValidator, we need to add server control on web form. After adding control on page we need to associate the RequiredFieldValidator control to the control that we have to validate. e.g. Textbox. Also we need to set error message to show when validation fails.

RequiredFieldValidator example

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
        Name:<br />
        <asp:TextBox runat="server" ID="Name" />
        <asp:RequiredFieldValidator runat="server" ID="validateName" ControlToValidate="Name"
            ErrorMessage="Enter the name." ForeColor="Red" />
        <br />
        <br />
        <asp:Button runat="server" ID="btnSubmit" Text="Ok" OnClick="Post_Page" CausesValidation="" />

Here you will notice that the validation is happening at client side means without postback, this is because by default validator control does client side validation if browser supports DHTML. And if browser does not supports scripting then it will do server side validation, means page will postback and it will check for "Page.IsValid()" and then will return true or false.

And if we explicitly want to do the server side validation then we need to set EnableClientScript="false"

Get html control value in code behind without runat = server

access html control value in codebehind without runat server
In application we need to access value of html control in code behind without runat="server". For that purpose we can use name property of control. And Request.Form we can get value to code behind.So if we have html text input and you want to pass value of html input to code behind set it name property like <input name="username" />  and access it using Rquest.Form["usename"] you will get value to code behind of control without runat="server".

Code to get html control value to code behind without runat server

<html xmlns="">
<head runat="server">
  <script type="text/javascript">
      function SubmitForm() {
         var theform;
          if (window.navigator.appName.toUpperCase().indexOf("NETSCAPE") > -1) {
              theform = document.forms["form1"];
          else {
              theform = document.forms.form1;
          theform.__EVENTTARGET = "btn";   
          theform.__EVENTARGUMENT = "";
    <form id="form1" runat="server">
        <input type="text" id="username" name="username" />
        <input type="button" id="btn" onclick="SubmitForm()"  value="GO"/>

Code behind to access html control value

using System;

namespace aspnetcontrol
    public partial class Getvaluewithoutrunatservercontrol : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            string value = Request.Form["username"];

ASP.Net Authentication Modes

ASP.Net supports below authentication modes:
1. Windows
2. Forms
3. Passport
4. None

To enable authentication provider or mode we need to use authentication element from config file.
   <!-- mode=[Windows|Forms|Passport|None] -->
   <authentication mode="Windows" />
  This is a default authentication mode in This uses windows credentials for authentication. It relies on IIS to authenticate the user. Aftre authenticating the user it passes security token to Windows authentication provides below ways:

Anonymous: IIS allows everybody to access application, no authentication is done.

Basic: User must have to provide username and password to get access to application. But username and password get sent over network in plain text format so it is bit insecure.

Digest: Same as Basic windows authentication but password is hashed before sending it over the netwrok and also user need to be use IE5 or later and windows accounts should stored in active directory.

Windows Integrated: User still need to provied username and password but it never sent over the network. Application either uses kerberos or challenge response protocol to authenticate the user. Kerberos provides tools for authentication and strong cryptography for secure communication.

2. Forms Authentication mode:  Forms authentication uses own customised HTML form to collect users credentials. Client or user directly sends credentials to application code for authenticatio. If application authenticates user it issues a cookie to ensure user is present on subsequent requests.

<!-- Web.config file -->
   <authentication mode="Forms">
      <forms forms="demoApp" loginUrl="/login.aspx" />
 3. Passport Authentication: Passport authentication mode provides centralized authentication process provided by microsoft passport service. When user site registered with passport, the passport service grants site specific key.
<!-- Web.config file -->
   <authentication mode="Passport" />

ASP.Net Caching, Caching Concept

ASP.NET Caching:

Caching is process of storing frequently used data for reuse. Generally it stores data in memory becuase accessing data from memory is more efficient way rather that generate it again.

ASP.NET provides two types of catching:
1. Output Caching
2. Application Data Caching

Page Output Caching:
 Output caching is done with entire page or with the fragment/part of the page.
 a. Page Output Caching: ASP.Net allows caching entire contents of the page. This is good for caching static pages.

<%@ OutputCache Duration="60" VaryByParam="None" %>

Fragement/Pratial Page Caching:
  This is same as page output caching, but instead it uses to store part or fragment of the page in cache. This is done by caching user controls (.ascx) used in page.

<%@ OutputCache Duration="300" VaryByParam="*" Shared="true" %>

Here shared="true" is used to share same HTML if the user control is used in more than one pages, and to avoid caching same output/HTML of user control multiple time.

Application Data Caching: 

This is used to store data in cache like dataset or any collection objects, or any object that need to be cached:

Item can be added to cache using Cache.Insert(param, param) with expiration parameter. Also Item can be added to cache using Cache.add(param, param) with priority.

Data set can be added to cache like Cache["MyDataSet"] = MyDataSet; and retrived like ds = (DataSet) Cache["MyDataSet"].

ASP.NET Validation Controls

Below are types of 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 Page life Cycle Events:

   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.

   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.
   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

   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.

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

  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
  • 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.

 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.
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:"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.
    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 worker process. This is less perfoamant process than InProc but it does not get affected in worker process get affected.

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

Garbage collection in

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.