Tuesday, January 26, 2010

c# code for user login

web Config For sql server
<add key=”test” value=”data source=servername;uid=””;pwd=””;initial catalog=”””; Connect Timeout=900;pooling=’true’; Max Pool Size=900;”/>
.aspx page
conn = new SqlConnection(ConfigurationManager.AppSettings["test"]);
strQuery = “select * from tbl_admin where username=@userName and password=@password and status=’Active’”;
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add(“@userName”, SqlDbType.VarChar).Value = txtusername.Text;
cmd.Parameters.Add(“@password”, SqlDbType.VarChar).Value = password;
conn.Open();
try
{
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Read())
{
FormsAuthentication.RedirectFromLoginPage(txtusername.Text, false);
FormsAuthentication.RedirectFromLoginPage(txtpassword.Text, false);
FormsAuthentication.RedirectFromLoginPage(dr["status"].ToString(), false);
Session["userid"] = dr["userid"];
Session["username"] = dr["username"];
if (Session["status"].ToString() == “Active”)
{
Response.Redirect(“cphome.aspx”);
}
else
{
Session.Abandon();
FormsAuthentication.SignOut();
Response.Redirect(“../index.aspx”);
}
}
lblmsg.Visible = true;
lblmsg.Text = “Invalid UserName or Passoword.”;
}
finally
{
conn.Close();
}
Web Config Authotication:
<authentication mode=”Forms”>
<forms name=”ExAuth” path=”/” loginUrl=”admin/login.aspx” protection=”All” timeout=”30″ defaultUrl=”Default.aspx”>
</forms>
</authentication>