// Login.ascx -- Login User Control
<BACK
//Redirect page after login succeed
public String RedirectPage ="/Default.aspx";
public int chk;
bool Authenticate(String user, String pass) {
bool authenticated = false;
try {
Stringdsn="server=localhost;uid=sa;pwd=;database=portal";
String sSQL = "SELECT Name,password FROM users where Name='" + user.Trim() + "'";
SQLConnection Conn = new SQLConnection(dsn);
SQLCommand Cmd = new SQLCommand(sSQL,Conn);
SQLDataReader myRead=null; //instancing a datareader
Conn.Open(); //opening the connection
Cmd.Execute(out myRead);
if (myRead!=null){ //checking for records
if (myRead.Read()) {
if (myRead.GetString(0)==user){ //checking username in db with given username
if(myRead.GetString(1)==pass){ //checking password in db with given password
authenticated =true;
} else {
chk=1; // settingflag as 1 if password failed
}
} else {
chk=2; //setting flaga as 2 in username failed
}
}
}
} catch(Exception e) {
Response.Write("Auth Exception: " + e.ToString()); }
return authenticated;
}
private void SubmitBtn_Click(Object sender, EventArgs e) {
if (Authenticate(UserName.Text, Password.Value)) {
Response.Redirect(Redirecturl); //redirecting to valid page after login Succed } else{
if (chk==1){
Message.Text= "PassWordInvalid";
Message.Visible = true;
} else{
Message.Text= "UserNameinvalid";
Message.Visible = true;
}
}
}
|
This code above shows you how to validate a input data with the data avaliable in database. The user control will be having two asp text box (Web Control) for username and password and a asp lable to display error message and a asp submit button.
DataReader:
DataReader is
a read-only, forward-only stream returned from the database. Only one record at
a time is ever in memory. It is similay to ADO forwardonly cursor and read only
lock type.Datareader also provides a series of Get methods that allow accessing
the field values as its native time. Examples of this are: GetDataTime,GetString,
GetDouble, GetGuid, GetInt32, GetStream.
Password:<asp:Textbox
id=password size=14 runat= server /> <asp:Button
id=click value= signon onclick=SubmitBtn_Click runat=server> <asp:lable
id=message visibality=false runat=server /> |
Registering
UserControl:
Declare
an @ Register directive
that includes:
For example, the
following code registers a control defined in the file login.ascx,
which has been given the tag prefix UserControl and the tag name Login.
<!--
Login.aspx--> <!-- Registering the user control--> <%@ Register TagPrefix="UserControl" TagName="Login" Src="login.ascx" %> <html>
<body>
<form runat="server">
<UserControl:Login id="MyLogin" runat="server"/>
</form>
</body>
</html>
|