Tuesday, 31 December 2013

How to create Login Form in ASP.NET?

Lets assume that we have a Login Form such as:


In the above figure, two Labels, two TextBoxes and one Button is used. First, we need to set the following control's properties:

Controls Properties
Label1 ID User
Text User Name
Label2 ID Pass
Text Password
TextBox1 ID UserName
TextMode SingleLine
TextBox2 ID Password
TextMode Password
Button1 ID Submit
Text Submit

After setting above properties, click on the Submit button and add the following code in the codebehind(.cs or .vb) file:

C#


using System.Data;
using System.Data.SqlClient;

namespace Student
{
  public partial class LoginForm : System.Web.UI.Page
  {
    protected void Submit_Click(object sender, EventArgs e)
    {
      SqlConnection connection = new SqlConnection("server=myDB; uid=sa;
      pwd=password; database=master");
      connection.Open();
      String User = UserName.Text;
      String Pass = Password.Text;
      SqlCommand command = new SqlCommand("select count(*) from Login_Form
      where UserName='"       +   User + "' and Password='" + Pass + "'", connection);
      SqlDataReader dataReader = command.ExecuteReader();
          while (dataReader.Read())
          {
            if (dataReader.GetValue(0).ToString() == "1")
             {
                Response.Redirect("Welcome.aspx");
             }
            else
             {
                Response.Write("<script>alert('Invalid UserName/Password');</script>");
             }
           }
      }
  }
}

VB


Imports System.Data
Imports System.Data.SqlClient

Partial Public Class LoginForm
  Inherits System.Web.UI.Page
 
    Protected Sub Submit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Submit.Click
   
     Dim connection As SqlConnection = New SqlConnection("server=myDB; uid=sa;
     pwd=password;database=master")
        connection.Open()
        Dim User As String = UserName.Text
        Dim Pass As String = Password.Text
        Dim command As SqlCommand = New SqlCommand("select count(*)from
        Login_Form where UserName='" + User + "' and Password='" + Pass + "'",
        connection)
        Dim dataReader As SqlDataReader = command.ExecuteReader()
        While (dataReader.Read())

            If (dataReader.GetValue(0).ToString() = "1") Then

                Response.Redirect("Welcome.aspx")

            Else

                Response.Write("<script>alert('Invalid UserName/Password');</script>")

            End If

        End While

    End Sub
End Class

If User Name and Password both matches with the User Name and Password that are stored in the database, then 'Welcome.aspx' page would be opened. If User Name and Password both or any one of them does not match, then it would show an error message.

Sunday, 29 December 2013

ActiveX Data Object.NET (ADO.NET)

ADO.NET  is a data access component introduced in the Microsoft.Net framework. ADO.NET  includes .NET Framework data providers for connecting to a database, executing commands and retrieving results. ADO.NET uses Extensible Markup Language (XML) for transmitting data between different application layers.

ADO.NET Architecture
  • Presentation Tier works with the interface part of the application that is presented to the client.

  • Business Tier works with the business logic part of the application where all the calculation and logic resides.

  • Data Tier works with the database part of the application.

The Object Model of ADO.NET
  • DataSets

  • .NET Data Providers
DataSet:

DataSet is an object that store retrieved data from the database. The data in the DataSet is stored in the form of a DataTable object. The DataSet can contain one or more tables. The DataTable object in the DataSet  represents a table retrievd from the database. The data in the DataTable is represented by the DataRow object. The DataSet can hold data from a database as well as non database data source. The DataSet does not interact with any database, it is just a container for the data.

Syntax to add table to the DataSet:- 

<DataSet name>.Tables.Add(<DataTable Object name>);

Syntax to add Columns to the DataTable:- 

<DataTable Object name>.Columns.Add(<Column name>,typeof(DataType));

Syntax to add Rows to the DataTable:- 

<DataTable Object name>.Rows.Add();

.Net Data Providers:

The .NET Data Provider contains objects that provide access to data from various data sources. The data can be manipulated through these data providers.

The .NET Data Providers is a collection of components such as:
  • Connection
  • Command
  • DataReader
  • DataAdapter 
There are four types of .NET Data Providers available-
  •  .Net Data Provider for SQL Server
  •  .Net Data Provider for OLEDB
  •  .Net Data Provider for ODBC
  •  .Net Data Provider for Oracle
Connection Object: 

The Connection Object is used to establish a connection between the application and the database.

Connection Object for SQL.NET Data Provider:

Namespaces needed:
  • <%@ Import Namespace="System.Data" %>
  • <%@ Import Namespace="System.Data.SqlClient" %>
Connection String:

SqlConnection connection=new SqlConnection("server=myDB; uid=sa; pwd=password; database=master");

where,
connection is the name of the connection object.
myDB is the name of the SQL Server that stores the database 'master'.
uid is the identity that is used to access the database.
pwd is the password that is required to access the database.

Connection Object for OLEDB.NET Data Provider:

Namespaces needed:
  • <%@ Import Namespace="System.Data" %>
  • <%@ Import Namespace="System.Data.OleDb" %>
Connection String:

OleDbConnection oleconnection=new OleDbConnection("provider=SQLDB; Data Source=myDB; User Id=sa; pwd=password; Initial Catalog=master");

where,
oleconnection is the name of the connection object.
SQLDB is the OLE DB Provider for SQL Server.
myDB is the name of the SQL Server.
Initial Catalog is used to specify the database. 
User Id is the identity that is used to access the database.
pwd is the password that is required to access the database.

Command Object:

The Command Object is used to retrieve, update, insert and delete data in a database.

Retrieving Data:
  • SQL.NET Data Provider
SqlDataAdapter dataadapter=newSqlDataAdapter("select * from student",connection);
        
SqlDataAdapter is the Command Object, dataadapter is the name of the command object and connection is the connection object.
  • OLEDB.NET Data Provider
OleDbDataAdapter dataadapter=new OleDbDataAdapter("select * from student",oleconnection);

OleDbDataAdapter is the Command Object, dataadapter is the name of the command object and oleconnection is the connection object.

Example of DataSet using DataAdapter:

using System.Data;
using System.Data.SqlClient;


namespace Student
{
  public partial class Profile : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      SqlConnection connection = new SqlConnection("server=myDB; uid=sa; pwd=password;
      database=master");
      connection.Open();
       SqlCommand command = new SqlCommand("select * from student", connection);
       SqlDataAdapter da = new SqlDataAdapter();
       da.SelectCommand = command;
       DataSet ds = new DataSet();
       da.Fill(ds, "student");
       studentGrid.DataSource = ds.Tables["student"].DefaultView;
       studentGrid.DataBind();
       connection.Close();

Inserting Data:
  • SQL.NET Data Provider
SqlCommand command=new SqlCommand("insert into student values(1,'Mike','30-12-1990')",connection);
  • OLEDB.NET Data Provider
OleDbCommand olecommand=new OleDbCommand("insert into student values(1,'Mike','30-12-1990')",oleconnection);

Updating Data:
  • SQL.NET Data Provider
SqlCommand command=new SqlCommand("update student set Roll_No=10 where Student_Name='Mike'",connection);
  • OLEDB.NET Data Provider
OleDbCommand olecommand=new OleDbCommand("update student set Roll_No=10 where Student_Name='Mike'",oleconnection);

Deleting Data:
  • SQL.NET Data Provider
SqlCommand command=new SqlCommand("delete from student where Roll_No=10",connection);
  • OLEDB.NET Data Provider
OleDbCommand olecommand=new OleDbCommand("delete from student where Roll_No=10",oleconnection);

DataReader

DataReader is used to view the records one after the other. DataReader is the read-only view of the query result.

DataView

DataView is used to filter the records. It presents customized view of data from a DataTable.

Example:


using System.Data;
using System.Data.SqlClient;


namespace Student
{
   public partial class Profile : System.Web.UI.Page
   {
     protected void Page_Load(object sender, EventArgs e)
     {
       SqlConnection connection = new SqlConnection("server=myDB; uid=sa; pwd=password;
       database=master");
       connection.Open();
       SqlCommand command = new SqlCommand("select Roll_No,Student_Name,DOB from 
       Student", connection);
       DataTable dt = new DataTable();
          
       dt.Columns.Add("Roll No");
       dt.Columns.Add("Student Name");
       dt.Columns.Add("Date of Birth");
       DataRow dr = dt.NewRow();

       SqlDataReader dataReader = command.ExecuteReader();

          while (dataReader.Read())
            {
                dr["Roll No"] = dataReader.GetValue(0).ToString();
                dr["Student Name"]=dataReader.GetValue(1).ToString();
                dr["Date of Birth"] = dataReader.GetValue(2).ToString();
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                studentGrid.DataSource = dataReader;
                studentGrid.DataBind();
            }
               dataReader.Close();
               connection.Close();
        }
    }
}

Wednesday, 25 December 2013

The Session Object

Hypertext Transfer Protocol (HTTP) is a stateless protocol. In stateless transactions the Web Server does not keep track of these transactions. Every transaction is considered as an independent transaction.

Sessions were designed to overcome this limitation. Sessions are used to store  the information of the user logged in to the Website. The information that is stored is used to identify the user sending a request to the Web Server. For each new user, the Server object checks the user Session ID. The user is considered as 'active' and is permitted to continue with the application if the user has a valid Session ID. If the Server object unable to find Session ID, the Server object creates a Session Object for the user.

Session object is used to store information about a user. When a user logs in to the Website, the Web Server creates a Session ID for that user. The Web server sends the Session ID to the user's computer. This Session ID is stored in the user's computer as Cookies. The information is retained when the user browses from one page to another within the same application.

Advantages of Session Object:
  • The information is retained for the duration of the user session and cannot be shared or accessed by other users of the application.
  • The server destroys the Session object after the session expires or is terminated.
Example:

This example demonstrates how Session variable is used from one page to another.

WriteSessionVariable.aspx.cs

protected void Submit_Click(object sender, EventArgs e)
{
Session["FirstName"] = FName.Text;
Session["LastName"] = LName.Text;
Response.Redirect("ReadSessionVariable.aspx");
}

FName and LName is a TextBox ID.
FirstName and LastName is a Session Variable Name.

Output:
ReadSessionVariable.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
First_Name.Text = "First Name: " + Session["FirstName"];
Last_Name.Text = "Last Name: " + Session["LastName"];
}

First_Name and Last_Name is a Label ID.

Output:

Tuesday, 24 December 2013

The Application Object

The Application object is a built-in ASP.NET object that represents an instance of the ASP.NET application. It includes all the methods and collections related to the application.When the first user calls an ASP.NET file, the application is started and an Application object is created. Once the Application object is created, it can share information throughout the application. The object remains until the application is shut down. The Application object stores and maintain values through variables. Variables can have two level of scope:
  • Page Level Variables: Page Level variables are used while the page is being processed. After the page is processed, the variables are destroyed and the associated resources are released.

    Code Snippet:

    String user_name="Mak";

    Response.write("Hello "+user_name);

  • Object Level Variables: Object Level variables and their values can be accessed across pages. There are two types of Object Level variables:
  • Application Level variables are used to share common information across multiple users.
  • Session Level variables are used to pass information from one page to another for a particular user.
Example:

Global.asax

protected void Application_Start(object sender, EventArgs e)
{
Application["count"] = 0;
}

protected void Session_Start(object sender, EventArgs e)
{
Response.Write("Session Started"+"<br />");
Application["count"] = Convert.ToInt32(Application["count"]) + 1;
}

protected void Application_BeginRequest(object sender, EventArgs e)
{
Response.Write("Application Request Begins" + "<br />");
}

protected void Application_EndRequest(object sender, EventArgs e)
{
Response.Write("Application Request ends");
}

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}

protected void Application_Error(object sender, EventArgs e)
{
}

protected void Session_End(object sender, EventArgs e)
{
Response.Write("Session Ended");
}

protected void Application_End(object sender, EventArgs e)
{
}

ApplicationObj.aspx

<script language="C#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Visitor Number:" + Application["count"] + <br>);
}
</script>

When the user starts the application, the Application_Start event is fired.

Output:

Application Request Begins
Session Started
Visitor Number:1
Application Request ends

If user refresh the page, the counter is not incremented as shown below.

Application Request Begins
Visitor Number:1
Application Request ends

If .aspx page is loaded in a new browser window, the counter is incremented by one as shown below.

Application Request Begins
Session Started
Visitor Number:2
Application Request ends

An application variable retains the value assigned to it until the application is shut down.

The Global.asax file

ASP.NET application use a special file called Global.asax to maintain information about events and objects that are global to the application. This file is stored in the root directory of the application. An application can have only one Global.asax file. The server processes the Global.asax file when:
  • The user starts or stops application.The Application_Start event is fired when application is started. The Application_End event is triggered when the user ends the application. 
  • A session starts or stops. The Session_Start event is triggered when an individual session is started for a user who accesses the application. The Session_End event is fired when the user ends the session.
Global.asax
Application Events
  • Application_Start
  • Application_BeginRequest
  • Application_EndRequest
  • Application_End
Session Events
  • Session_Start
  • Session_End

The following table describes some of the events stored in Global.asax file:

Event Description
Application_Start Fires when the first ASP.NET page in the current application is called.
Application_BeginRequest Fires every time when a page is loaded or refreshed.
Application_EndRequest Fires when a page request ends
Application_End Fires when the last session of the application ends.
Session_Start Fires every time a new session starts.
Session_End Fires when session ends.

Sample Global.asax File:

protected void Application_Start(object sender, EventArgs e)
{
}

protected void Session_Start(object sender, EventArgs e)
{
Response.Write("Session Started");
}

protected void Application_BeginRequest(object sender, EventArgs e)
{
Response.Write("Application Request Begins");
}

protected void Application_EndRequest(object sender, EventArgs e)
{
Response.Write("Application Request ends");
}

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}

protected void Application_Error(object sender, EventArgs e)
{
}

protected void Session_End(object sender, EventArgs e)
{
Response.Write("Session Ended");
}

protected void Application_End(object sender, EventArgs e)
{
}

Output:

Application Request Begins
Session Started
Application Request ends

If the page is refereshed, the output would be:

Application Request Begins
Application Request ends

(Note: We cannot include any HTML tags or Response.Write() method in Application_Start() because session has not yet started and Response object has not been created.)

Thursday, 19 December 2013

Use of RangeValidator in ASP.NET

The RangeValidator control is used to check if the value of a control lies within a range.

Example:
Suppose that you want your user must be in between 18 to 60 years, then you can use RangeValidator to validate user's age during the registration by setting the following RangeValidator's properties:

ID Age_Validator
ControlToValidate Age
ErrorMessage Your age must be in the range of 18-60 years
Maximum 60
Minimum 18

MinimumValue and MaximimValue are used to set the lower and the upper limit of the range respectively. 

Code Snippet:
<asp:rangevalidator controltovalidate="Age" errormessage="Your age must be in the range of 18-60 years" id="Age_Validator" maximumvalue="60" minimumvalue="18" runat="server"></asp:rangevalidator>

Wednesday, 18 December 2013

Use of CompareValidator in ASP.NET

When the values of two controls have to be compared or the value of a control has to be compared to a specified constant value, the CompareValidator control is used.
Example1:
Suppose that you want your user to be atleast 18 years old to join your website, then you have to check the age entered by the user to see whether he/she is 18 years old or not. This could be done very easily by using CompareValidator control. You just need to set the following CompareValidator properties:

ID Age_Validator
ControlToValidate Age
ErrorMessage Age should be 18 or more
Operator GreaterThanEqual
Type Integer
ValueToCompare 18

Demo:
Name
Age
Example2:
If you do not want your user to be more than 60 years old, then CompareValidator properties would be:

ID Age_Validator
ControlToValidate Age
ErrorMessage Age cannot be greater than 60
Operator LessThanEqual
Type Integer
ValueToCompare 60

Demo:
Name
Age
CompareValidator is also used to compare two passwords.CompareValidator properties to compare passwords are:

ID Password_Validator
ControlToCompare Password
ControlToValidate Confirm_Password
ErrorMessage The two passwords do not match
Operator Equal
Type String

Demo:
Password
Confirm Password

Monday, 16 December 2013

RegularExpressionValidator characters that compares values entered with a specified pattern.

RegularExpressionValidator characters and their meanings:

Sign Meaning
^ Specifies that checking starts from here
$ Specifies that checking ends here
[] Checks that the value entered match with any of the characters that are in the square brackets
\w Allows any value to be entered
\d{} "\d" specifies that the value entered is a digit and {} specifies the number of occurences of the specified data type
+ Specifies that one or more elements to be added to the expression being checked

Wednesday, 11 December 2013

How to validate Email Address in ASP.NET?

To validate Email ID in ASP.NET, set the following RegularExpressionValidator properties:

ID Email_Validator
ControlToValidate Email_ID
ErrorMessage Please enter the valid Email Address.
ValidationExpression ^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$

Code Snippet:
<asp:RegularExpressionValidator ID="Email_Validator" runat="server" ControlToValidate="Email_ID" ErrorMessage="Please enter the valid Email Address" ValidationExpression="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"></asp:RegularExpressionValidator>

(Note: Email_ID is a TextBox ID in which email id would be entered by user).

Tuesday, 10 December 2013

How to set RequiredFieldValidator on DropDownList in ASP.NET?


Lets assume that we have a DropDownList named 'Gender' in our Registration Form and it is a required field so that user must select it. First we have to set the following DropDownList properties:

ID Gender
Items (Collection)...
  • Click on the Collection button then ListItem Collection Editor would be open as shown below:
  • Click on the Add button and set the ListItem properties as follows:
 
  • Click 'OK' and set the RequiredFieldValidator properties as follows:
ID Gender_Validator
ControlToValidate Gender
ErrorMessage Please select Gender
InitialValue 0

Now if user does not select either 'Male' or 'Female' then RequiredFieldValidator would generate an error message.

Code Snippet:
<asp:RequiredFieldValidator ID="Gender_Validator" runat="server" ControlToValidate="Gender" ErrorMessage="Please Select Gender" InitialValue="0"></asp:RequiredFieldValidator>

Demo:
Gender
Download Source Code

Saturday, 7 December 2013

How to enter Date in a given format in a TextBox in ASP.NET?

In ASP.NET, date can be validated easily by using RegularExpressionValidator. Suppose that you want your user to enter the date in (DD-MM-YYYY) format in a TextBox named Date_of_Birth. To do so, you just need to set the following RegularExpressionValidator properties:

ID Date_Validator
ControlToValidate Date_of_Birth
ErrorMessage Please fill the date in correct format
ValidationExpression ^(\d{2})\-(\d{2})\-(\d{4})$

If you want your user to enter the date in (DD/MM/YYYY) format, then ValidationExpression property will be as follows:

ValidationExpression ^(\d{2})\/(\d{2})\/(\d{4})$

If you want your user to enter the date in (D-M-YY) format, then ValidationExpression property will be as follows:

ValidationExpression ^(\d{1,2})\-(\d{1,2})\-(\d{2})$

(Note: You can change Error Messages, Control Names and Formats according to your project requirements.)

Friday, 6 December 2013

How to enter only characters in a TextBox in asp.net?

Suppose we have a TextBox named First_Name and we want to validate it in such a manner so that user can enter only characters in a TextBox.

We can use RegularExpressionValidator to validate First_Name. We just need to set the following  RegularExpressionValidator properties:

ID FirstName_Validator
ControlToValidate First_Name
ErrorMessage First Name is a character field.
ValidationExpression ^([A-Za-z])+$

Now if user enter any value in a First_Name TextBox other than characters, it will show an error message.

(Note- You can write your own Error Message and Control Names.) 

How to enter only numbers in a TextBox in asp.net?

Suppose we have a TextBox named Mobile_No and we need to validate it so that user cannot enter wrong values in a TextBox.

We can use RegularExpressionValidator to validate Mobile_No. We just need to set the following  RegularExpressionValidator properties:

ID Mobile_Validator
ControlToValidate Mobile_No
ErrorMessage You can enter only numbers in Mobile Number
ValidationExpression ^([0-9])+$


Now if user enter any value other than numbers, it will show an error message.

(Note- You can write your own Error Message and Control Names.)