<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Please, log in</title>
</head>
<body>
<div id="pageContent">
<form id="Form1" runat="server">
<table>
<tr>
<td><b>User ID</b></td>
<td><asp:textbox runat="server" text="" id="userName" /></td></tr>
<tr>
<td><b>Password</b></td>
<td><asp:textbox runat="server" text="" id="passWord" textmode="password" /></td></tr>
</table>
<asp:button ID="Button1" runat="server" text="Log In..." onclick="LogonUser" />
<br />
<asp:label runat="server" id="errorMsg" Font-Names="Verdana" Font-Size="Small" Font-Bold="True" ForeColor="Red"/>
</form>
</div>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SetFocus("userName");
}
protected void LogonUser(object sender, EventArgs e)
{
string user = userName.Text;
string pswd = passWord.Text;
bool bAuthenticated = AuthenticateUser(user, pswd);
if (bAuthenticated)
FormsAuthentication.RedirectFromLoginPage(user, false);
else
errorMsg.Text = "Sorry, yours seems not to be a valid account.";
}
private bool AuthenticateUser(string username, string pswd)
{
string connString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
string cmdText = "SELECT COUNT(*) FROM employees WHERE firstname=@user AND lastname=@pswd";
int found = 0;
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(cmdText, conn);
cmd.Parameters.Add("@user", SqlDbType.NVarChar, 10).Value = username;
cmd.Parameters.Add("@pswd", SqlDbType.NVarChar, 20).Value = pswd;
conn.Open();
found = (int)cmd.ExecuteScalar();
conn.Close();
}
return (found > 0);
}
}