Sample Login Page in ASP.NET


Many websites allows the users to see the content or use the benefits of the sites ater manually logged in by supplying the user id and password details. That means authenticated youser only can view the website.

Every website may have the roles difined and based on the roles they user may allow to login to the site.Today we will look how to create a sample website and develop the Login page.
Below are the steps to create a website using ASP.NET.

How to create a new ASP.NET Web site


1. First Start Microsoft Visual Studio 2010.
2. Go to the File menu, click on New Web Site.
3. Now the New Web Site dialog box is displayed.
4. Under Templates, click C# and then select ASP.NET Web Site.
5. In the Web Location box, select the location where you want to save the website
6. Now right click on website clcik new Item and select the WebForm, name the webfarm as UserLogin.aspx.
Now my intention is to create a webpage which should enter the Login Id and Paswword and click on the submit button, needs to validate the user and naviagate to sites home page based on the authentication. The login form should be look like as below.
MyLogin;

UserLogin.aspx page



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UserLogin.aspx.cs" Inherits="UserLogin" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1">
<title>HIHL Administration - Login</title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
<link href="Styles.css" rel="stylesheet" type="text/css" />

<script language="javascript" type="text/javascript">
document.onmousedown = click
var times = 0
var times2 = 1
function click() {
var times = 0
var times2 = 1
if ((event.button == 2) || (event.button == 3)) {
if (times >= 1) {
bye()
}
alert("You donot have permission to copy these Images or text");
times++
}
}
function bye() {
alert("");
bye()
}

</script>
<script language="javascript" type="text/javascript">
function validateKey(evt) {
if (evt.keyCode == '17') {
alert("You may not cut and paste text here.")
return false
}
return true
}
</script>
</head>

<body style="margin-left:0; margin-top:0; margin-right:0" onkeydown="return validateKey(event)">
<table>
<tr>
<td class="tableHeaderLine" style="HEIGHT: 5px; width: 272px;" colspan="2">

<asp:label id="lblDisplay" runat="server" CssClass="lableError" Visible="False" Width="385px"></asp:label>
</td></tr>
</table>
<table style="WIDTH: 280px; position: static;background-color:#F0F0F0 " id="TABLE1" >

<tr valign="top">
<td align="center" colspan="2" style="height: 22px;background-color:#008B8B" >
<asp:Label ID="Label1" runat="server" Font-Bold="True" ForeColor="Blue" Width="99px">Login</asp:Label></td>
</tr>
<tr>
<td align="right" colspan="3"></td>
</tr>
<tr valign="top">
<td class="CompulsoryFieldCell" align="right">
<label id="lblUsid1" class="lablestyle" >User ID</label><span style="color:red">*</span>
</td>
<td align="left" style="width: 205px">
<asp:textbox id="txtuserid" tabIndex="1" runat="server" MaxLength="30" Width="140px" ></asp:textbox>
<asp:requiredfieldvalidator id="rfvUserid" runat="server" ControlToValidate="txtuserid" ErrorMessage="*User ID field cannot be left blank" Font-Names="Verdana" Font-Size="XX-Small" Display="None">*</asp:requiredfieldvalidator>
<asp:regularexpressionvalidator id="regUserID" runat="server" ValidationExpression="[A-Za-z]+(\w+)*(\d+)*([/_ ][\w\d]+)*" ControlToValidate="txtuserid" ErrorMessage="Please enter valid user ID" Font-Names="Verdana" Font-Size="XX-Small" Display="None">*</asp:regularexpressionvalidator>
</td>
</tr>
<tr valign="top">
<td class="CompulsoryFieldCell" align="right" colspan="1" rowspan="1" style="padding-right:5px; height: 26px;">
<label id="lblPassword" class="lablestyle">Password</label><span style="color:red">*</span>
</td>
<td align="left" style="width: 205px; height: 26px;"><asp:textbox id="txtPassword" tabIndex="1" runat="server" MaxLength="30" TextMode="Password" Width="140px" ></asp:textbox>
<asp:requiredfieldvalidator id="rfvPassword" runat="server" ControlToValidate="txtPassword" ErrorMessage="*Password field cannot be left blank" Font-Names="Verdana" Font-Size="XX-Small" Display="None">*</asp:requiredfieldvalidator>

</td>
</tr>
<tr>
<td colspan="2" ><asp:ValidationSummary ID="VI" runat="server" ShowSummary="false" ShowMessageBox="true" />
<asp:Button id="btnSubmit" tabIndex="3" runat="server" CssClass="HIHL-Button" Width="57px" Height="25px" Text="Login" OnClick="btnSubmit_Click"></asp:Button></td>
</tr>
<tr>
<td class="tableHeaderLine" style="HEIGHT: 5px" colspan="2" align="center">


</td>
</tr>
<tr>
<td colspan="2" style="height: 5px" align="center">

<asp:LinkButton id="lnkRemember" runat="server" Visible="true" Text="" CausesValidation="False" Font-Size="Small" ForeColor="green" Font-Bold="true" OnClick="lnkRemember_Click1" Width="99px">
<asp:image ID="forgotimage" runat="server" ImageUrl="Image/forgotpassword.png" AlternateText="Forgot Password" />
</asp:LinkButton>
</td>
</tr>
</table>

</body>
</html>


Below is the .cs code to authenticate the user in button click event after submiting the userid and password.

UserLogin.aspx.cs page



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Xml;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

public partial class UserLogin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtuserid.Focus();
lblDisplay.Visible = false;

Session["m_ipaddress"] = ACLData.owutil.GetIPAddress();
string ip = ACLData.owutil.GetIPAddress();

}

protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
if (txtuserid.Text.Trim() == "")
{
lblDisplay.Visible = true;
lblDisplay.Text = "User Id cannot be left blank";
}
try
{
string userName = txtuserid.Text.Trim(); //Get the username from the control
string password = txtPassword.Text.Trim(); //get the Password from the control
bool flag = AuthenticateUser(userName, password);
if (flag == true)
{
Server.Transfer("ACLHome.aspx", true);
}
else
{
lblDisplay.Visible = true;
lblDisplay.Text = "Unauthorized user to login, contact Administrator";

}


}
catch (Exception ex)
{
ACLData.clsErrorHandlerALL _oErrorHandler = new ACLData.clsErrorHandlerALL();
_oErrorHandler.ErrorsEntry(ex.GetBaseException().ToString(), ex.Source, 1, "clsACLLogin", "LogOff()", ACLData.clsErrorHandlerALL.Logtype.file);

}
}
}
private bool AuthenticateUser(string userName, string password)
{
bool userflag = false;
string connString = "server=NAVEEN-257FA970;Trusted_Connection=yes;database=HIHL;";
string strSQL = "select * from dbo.HIHLUser where user_name ='" + userName + "' AND user_password ='" + password + "'";
DataSet userDataSet = new DataSet();
SqlConnection connection;
SqlDataAdapter dataAdapter;
SqlCommand command;
try
{
connection = new SqlConnection(connString);
connection.Open();
dataAdapter = new SqlDataAdapter(strSQL, connection);
dataAdapter.Fill(userDataSet);
connection.Close();
}
catch (Exception ex)
{
userDataSet = null;
}

if (userDataSet != null)
{
if (userDataSet.Tables[0].Rows.Count > 0)
userflag = true;
}
return userflag;
}

protected void lnkRemember_Click1(object sender, EventArgs e)
{
Server.Transfer("ForgotPassword.aspx");
}

}


If you observe the above Image, we have a option Forgot Password, when you click on the forgot password that will redirect to a Forgotpassword page that would be look like as below.
MyLogin
Below is the ASPX code to design the ForgotPassword.aspx page to get the password details to cilent mail.

ForgotPassword.aspx page



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ForgotPassword.aspx.cs" Inherits="ForgotPassword" Title="Forgot Password"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Forgot Password</title>
<link href="Styles.css" rel="stylesheet" type="text/css" />
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript">

function confirmReset()
{
var doc = document.forms[0];
var msg = "Are you sure you want to Reset the Values?";
if (confirm(msg))
doc.submit();
else
{ return false; }
}

</script>
<script language="javascript" type="text/javascript">
document.onmousedown=click
var times=0
var times2=1
function click()
{
var times=0
var times2=1
if ((event.button==2) || (event.button==3))
{
if (times>=1)
{
bye()
}
alert("You do not have permission to copy these Images or text");
times++ } }
function bye() {
alert("");
bye() }

</script>
<script language="javascript" type="text/javascript">
function onKeyDown() {
// current pressed key
var pressedKey = String.fromCharCode(event.keyCode).toLowerCase();

if (event.ctrlKey && (pressedKey == "c" ||
pressedKey == "v")) {
// disable key press porcessing
event.returnValue = false;
}

} // onKeyDown

</script>
</head>
<body style="margin-left:0; margin-top:0; margin-right:0" onkeydown="onKeyDown()">
<form id="form1" runat="server">
<table id="ta" runat="server" style="width: 964px" >
<tr>
<td valign="top" colspan="4" style="background-image:url(image/bg.jpg);height:13px"></td>

</tr>
<tr valign="top">

<td valign="top" align="left" style="font-size:medium; width: 20%; ">
<asp:Image ID="img1" runat="server" ImageUrl="Image/HMRI_logo.jpg" ImageAlign="Top" ToolTip="HMRI For All" /></td>

<td valign="middle" style="font-size:medium; width:61%; background-image:url(image/medical_report.gif)"><div align="center"><font color="#008080" size="5.5">Hospital
Management System</font></div></td>
<td valign="bottom" align="left" style="font-size:medium; width: 5%;"></td>
<td style="width:20%;">

<asp:Image ID="Image1" runat="server" ImageUrl="Image/Rajiv_logo.jpg" ToolTip="Rajeev Arogya Sree"/>
</td>

</tr>


<tr style="height:2" >
<td class="HIHL-TableHeaderLine1" colspan="4" style="background-image:url(image/downbg.gif);width: 50%; height:3px"></td>
</tr>
</table>
<br />



<strong><span style="font-size: 9pt" class="headfont">Forgot Password</span></strong>

<table id="t5" align="center">
<tr>
<td align="right" class="HIHL-TableHeaderLine" style="width: 406px"></td>
</tr>
</table>
<table id="Table1" runat="server" align="center" style="width: 360px" >

<tr style="width: 540px; height: 23px;"><td style="width: 628px"><asp:Label id="display" runat="server" Text="" Visible="false" CssClass="lableSuccess"></asp:Label><asp:Label id="Label1" runat="server" Text="" Visible="false" CssClass="lableError"></asp:Label></td>
</tr>
</table>
<table id="t1" runat="server" align="center">


<tr>
<td style="width: 102px; height: 23px;"><label id="LblUserID" class="lablestyle">Enter UserID</label><span style="color:red">*</span></td>
<td style="width: 184px; height: 23px;"><asp:textbox id="txtuserid" tabIndex="1" runat="server" MaxLength="30" Width="140px" Height="18px" BorderStyle="Groove"></asp:textbox>
<asp:RequiredFieldValidator id="rfvNewPwd" runat="server" Font-Size="8pt" Font-Names="Tahoma" ControlToValidate="txtuserid" ErrorMessage="UserID Cannot be Blank" Display="None" >*</asp:RequiredFieldValidator>
<asp:regularexpressionvalidator id="regUserID" runat="server" ValidationExpression="[A-Za-z]+(\w+)*(\d+)*([/_ ][\w\d]+)*" ControlToValidate="txtuserid" ErrorMessage="Please enter valid user ID" Font-Names="Verdana" Font-Size="XX-Small" Display="None">*</asp:regularexpressionvalidator>
<asp:ValidationSummary ID="ValidationSummary1" ShowMessageBox="true" ShowSummary="false" runat="server" Font-Names="Verdana"
Font-Size="X-Small" HeaderText="You must enter valid data in the UserID field" />
</td>
</tr>
<tr>
<td style="width: 102px; height: 37px;">
</td>
<td style="width: 184px; height: 37px;">

<asp:Button id="btnSubmit" tabIndex="3" runat="server" CssClass="HIHL-Button" Width="57px" Height="29px" Text="Submit" OnClick="btnSubmit_Click" ></asp:Button> <asp:Button ID="Button1" runat="server" CssClass="HIHL-Button" Height="29px"
TabIndex="3" Text="Reset" Width="57px" CausesValidation="False" OnClick="Button1_Click" /></td>
</tr>
<tr>
<td style="width: 102px; height: 32px;">
</td>
<td style="width: 184px; height: 32px;" class="lablestyle">
Click Here To:<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" OnClick="LinkButton1_Click" ForeColor="#0000ff">Login</asp:LinkButton></td>
</tr>

</table>
<table id="Table2" align="center">
<tr>
<td align="center" class="HIHL-TableHeaderLine" colspan="4" style="width: 406px"></td>
</tr>
</table>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<table>
<tr><td class="HIHL-TableHeaderLine1" colspan="4" style="background-image:url(image/downbg.gif);width: 50%; height:3px"></td></tr>
<tr>

<td align="center" colspan="4" style="width: 983px">
<asp:Label id="lblCopyright" runat="server" Font-Size="XX-Small" Font-Names="Verdana" Font-Bold="True" ForeColor="Black" Width="651px" >Copyright © 2007 . All rights reserved. </asp:Label></td>
</tr>
<tr valign="bottom">
<td align="center" colspan="4" style="width: 983px" >
<asp:Label id="lblBestView" Font-Bold="True" Font-Names="Verdana" Font-Size="XX-Small" runat="server"
ForeColor="Black" Height="10px"> Best viewed in 1152x864 resolution.Recommended browser IE5+ </asp:Label> </td>
</tr>
</table>

</form>
</body>
</html>


You can seen the below code which is useful to send the password mail to client after providing the userid in the text box.

ForgotPassword.aspx.cs page



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Xml;
using System.IO;
using System.Collections.Generic;
using System.Text;
using DAC;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
public partial class ForgotPassword : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Button1.Attributes.Add("onClick", "return confirmReset();");
display.Visible = false;
Label1.Visible = false;
txtuserid.Focus();
}
string EmailId;
//clsEmailSend objEmailSend = new clsEmailSend();
int i=0;
protected void btnSubmit_Click(object sender, EventArgs e)
{

int count = 0;
DataSet ds = new DataSet();
string user_id = txtuserid.Text;
ds = ACLBusiness.BusinessFactory.GetForgotPasswordObject().GetValidUser(user_id);
if(ds.Tables[0].Rows.Count>0)
{
count = Convert.ToInt32(ds.Tables[0].Rows[0].ItemArray[1]);
}


if (count!=0)
{
int usid = Convert.ToInt32(ds.Tables[0].Rows[0].ItemArray[1]);
Authentication al = new Authentication(ConfigurationManager.AppSettings["LoginUrl"]);

string result = al.ForgotPassword(usid);
DataSet ds1 = new DataSet();
ds1.ReadXml(new XmlTextReader(new StringReader(result)));
if (Convert.ToInt32(ds1.Tables[0].Rows[0].ItemArray[1]) == 1)
{

string updatedPassword = ds1.Tables[0].Rows[0].ItemArray[0].ToString();
Label1.Visible = false;
display.Visible = true;

//sneding SMTP MAIL

//string strFrom = ConfigurationManager.AppSettings["ToMailId"].ToString();
string smtpServer = ConfigurationManager.AppSettings["SmtpServer"].ToString();
EmailId = ds.Tables[0].Rows[0].ItemArray[2].ToString();

int smtpserverport = Convert.ToInt32(ConfigurationManager.AppSettings["smtpserverport"]);

System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage();
mailMsg.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["FromId"], "hello", System.Text.Encoding.UTF8);
mailMsg.To.Add(EmailId);
mailMsg.Subject = @"USERMANAGEMENT PASSWORD";
mailMsg.Body = "The Result Of USERMANAGEMENT PASSWORD IS" + updatedPassword;
mailMsg.BodyEncoding = System.Text.Encoding.UTF8;
mailMsg.IsBodyHtml = true;
mailMsg.Priority = System.Net.Mail.MailPriority.High;

System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential("hihlsmtp", "kskns28");

System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.Port = smtpserverport;
client.Host = smtpServer;
client.EnableSsl = false;
client.UseDefaultCredentials = false;
client.Credentials = mailAuthentication;
;
object userState = mailMsg;
client.Send(mailMsg);

display.Text = "Your password has been mailed to your mail id.";
txtuserid.Text = "";
}
}
else
{
display.Visible = false;
Label1.Visible = true;
Label1.Text = "Invalid User";
txtuserid.Text = "";
}

}
protected void Button1_Click(object sender, EventArgs e)
{
txtuserid.Text = "";
display.Visible = false;
Label1.Visible = false;
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Server.Transfer("UserLogin.aspx");
}

}


We often encounter the situation to restrict the right click and Ctrl-C,Ctrl-V on the webpage. We can address this situation by using the java script. Nelow is the java script to restrict the right click.

Java Script to restrict the user from right click on the page:



<script language="javascript" type="text/javascript">
document.onmousedown=click
var times=0
var times2=1
function click()
{
var times=0
var times2=1
if ((event.button==2) || (event.button==3))
{
if (times>=1)
{
bye()
}
alert("You do not have permission to copy these Images or text");
times++
}
}
function bye() {
alert("");
bye() }

</script>
<script language="javascript" type="text/javascript">
function onKeyDown() {
// current pressed key
var pressedKey = String.fromCharCode(event.keyCode).toLowerCase();

if (event.ctrlKey && (pressedKey == "c" ||
pressedKey == "v")) {
// disable key press porcessing
event.returnValue = false;
}

} // onKeyDown

</script>


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: