Restricting user access in asp.net - asp.net

I am working on asp.net application. I want only logged in users to access the Game page. When the users log in, the id and pass are authenticated from the SQL then they are logged in. and I want the logged in users to have an access to Games.aspx.
Here is the login code,
public partial class Login : System.Web.UI.Page
{
//"Data Source=MUNIZA\\SQLEXPRESS;Initial Catalog=LD_Server;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
lbInfo.Enabled = false;
}
public bool IsAuthenticated
{
get { return Convert.ToBoolean(Session["sIsAuthenticated"] ?? false); }
set { Session["sIsAuthenticated"] = value; }
}
protected void Button1_Click(object sender, EventArgs e)
{
string strcon = "Data Source=MUNIZA\\SQLEXPRESS;Initial Catalog=LD_Server;Integrated Security=True";
SqlConnection con = new SqlConnection(strcon);
SqlCommand com = new SqlCommand("spStudentProfile", con);
com.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("RegNo", TextBox2.Text);
SqlParameter p2 = new SqlParameter("Password", TextBox1.Text);
com.Parameters.Add(p1);
com.Parameters.Add(p2);
con.Open();
SqlDataReader rd = com.ExecuteReader();
if (rd.HasRows)
{
IsAuthenticated = true;
rd.Read();
Response.Redirect("~/Games.aspx");
}
else
{
IsAuthenticated = false;
lbInfo.Enabled = true;
lbInfo.Text = "Invalid username or password.";
}
}
It is the login code on every page,
<%
string url = "~/Login.aspx", text = "Log in";
if (Convert.ToBoolean(Session["sIsAuthenticated"] ?? false))
{ url = "~/Home.aspx"; text = "Log out"; }
%>
<%: text %>
</div>

Related

Session Sign in - Session string is null

This is not working at all. I have done it many times but I don't know what's going wrong. the textbox always shows "not found" whereas it should be showing username.
Note: Textbox is just an example.
Login Page:
protected void login_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Session.Abandon();
Session.Clear();
string username = email.Text.ToLower().Trim();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
con.Open();
string sql = "SELECT USERNAME, PASSWORD FROM MANAGER WHERE USERNAME = #USERNAME AND PASSWORD=#PASSWORD";
SqlCommand command = new SqlCommand(sql, con);
command.Parameters.AddWithValue("#USERNAME", username);
command.Parameters.AddWithValue("#PASSWORD", password.Text.Trim());
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
command.ExecuteNonQuery();
command.Dispose();
con.Close();
if (dt.Rows.Count > 0)
{
Session["manager"] = username;
Response.Redirect("ManagerHomePage.aspx");
Session.RemoveAll();
}
else
{
Label1.Text = "Invalid Email or Password!";
}
}
ManagerHomePage.aspx :
protected void Page_Load(object sender, EventArgs e)
{
if(Session["manager"]!=null)
{
TextBox1.Text = Session["manager"].ToString();
}
else
{
TextBox1.Text = "not found";
}
}
Do not use ExecuteNonQuery for Select command. ExecuteNonQuery is used for Insert, Update, Delete command. Try using ExecuteReader
Bellow is the code
protected void login_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Session.Abandon();
Session.Clear();
string username = email.Text.ToLower().Trim();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
con.Open();
string sql = "SELECT USERNAME, PASSWORD FROM MANAGER WHERE USERNAME = #USERNAME AND PASSWORD=#PASSWORD";
SqlCommand command = new SqlCommand(sql, con);
command.Parameters.AddWithValue("#USERNAME", username);
command.Parameters.AddWithValue("#PASSWORD", password.Text.Trim());
SqlDataReader rdr=command.ExecuteReader();
if(rdr.HasRows())
{
Session["manager"] = username;
Response.Redirect("ManagerHomePage.aspx");
}
else
{
Label1.Text = "Invalid Email or Password!";
}
}

How to connect to SQL Server using ADO.Net

This is the first time I'm designing a web site. I'm having problem on connecting to my database. None of buttons work on pages. The most important one is Register button. I fill the form correctly but when I press Register button it doesn't register the new user into database. It even doesn't show any error message which I've considered. For example, it doesn't show that You've registered before or Your registration wasn't successful. No error message and no new record in my database. I've removed the captcha code because I thought that may cause problem.Here's my code:
using System;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
public partial class SignUp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strname = Cache["TF"] as string;
if (strname != null)
{
(Master.FindControl("Lozv") as Label).Text = strname;
(Master.FindControl("LinkButton1") as LinkButton).Visible = true;
}
else
{
(Master.FindControl("Lozv") as Label).Text = "Guest";
(Master.FindControl("LinkButton1") as LinkButton).Visible = false;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
string username = txtboxUser.Text;
SqlConnection sqlc = new SqlConnection("Data Source=.; Database=LDatabase; Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT dbo.CheckUserName(#UN)");
cmd.Parameters.AddWithValue("#UN", txtboxUser.Text);
sqlc.Open();
Boolean User = Convert.ToBoolean(cmd.ExecuteScalar());
sqlc.Close();
if (User == false) ////////////// if user name is not in DB//////////////
{
SqlConnection sqlca = new SqlConnection();
sqlca.ConnectionString = "data source=. ; database=LDatabase ; integrated security=true";
SqlCommand cmda = new SqlCommand();
cmda.Connection = sqlca;
cmda.CommandText = "INSERT INTO User_Pass values(#UserName,#Pass,#Name,#LastName,#Email,#Date,#Sex,'0')";
cmda.Parameters.AddWithValue("#UserName", txtboxUser.Text);
cmda.Parameters.AddWithValue("#Pass", txtboxPass.Text);
cmda.Parameters.AddWithValue("#Name", txtboxName.Text);
cmda.Parameters.AddWithValue("#LastName", txtboxSurname.Text);
cmda.Parameters.AddWithValue("#Email", txtboxEmail.Text);
cmda.Parameters.AddWithValue("#Date", DateTime.Now);
cmda.Parameters.AddWithValue("#Sex", rbtnGender.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#manager", "No");
sqlca.Open();
int n= cmda.ExecuteNonQuery();
if (n <= 0)
LMsg.Text = "Your registration wasn't successful";
else
{
txtboxName.Text = "";
txtboxSurname.Text = "";
txtboxUser.Text = "";
txtboxPass.Text = "";
txtboxRePass.Text = "";
txtboxEmail.Text = "";
rbtnGender.SelectedIndex = -1;
LMsg.Text = "You registered successfully.";
}
sqlca.Close();
}
else //////////////if user name is in db//////////////
{
LMsg.Text = "This username has already registered.";
}
}
}
Does Captcha have anything to do with this type of problem? Any help would be appreciated.
Put your button like this in the aspx-markup:
<asp:Button ID="btnRegister" runat="server" Click="Button1_Click1" Height="26px" Text="register" Width="88px"/>
It should trigger the method.
Edit: Or bind the event in the Page_Load method (remove the Click-attribute from the button first - from my previous example above).
protected void Page_Load(object sender, EventArgs e)
{
btnRegister.Click += new EventHandler(Button1_Click1);
string strname = Cache["TF"] as string;
[...]

[System.NullReferenceException: Object reference not set to an instance of an object.]

I am trying to select a user from my default_information.aspx.cs page and display that user information on my registration.aspx page where I already created a registration form.
I am getting System.NullReferenceException:Object reference not set to an instance of an object error. Please help me. I've given the main part of it. I debugged it. I found every data is selected from my DB in string strusername,strpassword. But code breaks on usernametxt.Text = strusername; when i try to show username or password on that text field.
default_information contains
protected void gridviewprofile_SelectedIndexChanged(object sender, EventArgs e)
{
registration objdef = new registration();
string username = gridviewprofile.Rows[gridviewprofile.SelectedIndex].Cells[1].Text;
objdef.displayuser(username);
}
protected void update_Click(object sender, EventArgs e)
{
Response.Redirect("registration.aspx");
}
registration.aspx contains
protected void register_Click(object sender, EventArgs e)
{
user objuser = new user();
objuser.username = usernametxt.Text;
objuser.password = passwordtxt.Text;
objuser.email = emailtxt.Text;
objuser.Save();
}
public void displayuser(string username)
{ user obj = new user();
DataSet objDataset = obj.profile(username);
string strusername = objDataset.Tables[0].Rows[0][0].ToString();
string strpassword = objDataset.Tables[0].Rows[0][1].ToString();
string stremail = objDataset.Tables[0].Rows[0][2].ToString();
usernametxt.Text = strusername;
passwordtxt.Text = strpassword;
emailtxt.Text = stremail;
}
user class contains
public class user
{
public void Save()
{
clssqlserver obj = new clssqlserver();
obj.insertuser_info(Username,Password,Email);
}
public DataSet profile(string username)
{
clssqlserver obj = new clssqlserver();
return obj.getalluser_info(username);
}
}
clssqlserver contains
public DataSet getalluser_info(string username)
{
string connectionstring = "Data Source=localhost\\mssql;Initial Catalog=blooddb;Integrated Security=True";
SqlConnection objconnection = new SqlConnection(connectionstring);
objconnection.Open();
string command = "Select * from login_donor where username='" + username + "' ";
SqlCommand objcommand = new SqlCommand(command, objconnection);
DataSet objdataset = new DataSet();
SqlDataAdapter objadapter = new SqlDataAdapter(objcommand);
objadapter.Fill(objdataset);
objconnection.Close();
return objdataset;
}
public bool insertuser_info(string username,string password,string email)
{ string connectionstring = "Data Source=localhost\\mssql;Initial Catalog=blooddb;Integrated Security=True";
SqlConnection objconnection = new SqlConnection(connectionstring);
objconnection.Open();
string strInsertCommand = "insert into login_donor values('"+ username +"','"+ password + "','"+email+"')";
SqlCommand objcommand = new SqlCommand(strInsertCommand, objconnection);
objcommand.ExecuteNonQuery();
objconnection.Close();
return true;
}
It looks like you are using the asp.net create user wizard control.Because your controls are buried inside another container, you have to be rewarded after some little excavation..Lets start digging......
Using the wizard which is already accessible locate your text box
TextBox usernametxt= (TextBox)CreateUserWizard.FindControl("usernametxt");
usernametxt.Text = strusername;
Hope this will help.
You should check this line
string strusername = objDataset.Tables[0].Rows[0][0].ToString();
you are trying to access directly objDataset.Tables[0], what if there is no user with the supplied username to this method getalluser_info(string username), will the dataset fill the table.
you should first check whether there is any table in the dataset or not.
hope this helps
well i ve found the solution...i was passing Data Between Webforms in worng way..here is the link which helps me: http://dotnetslackers.com/community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspx
here is the solution
default_information.aspx contains
protected void gridviewprofile_SelectedIndexChanged(object sender, EventArgs e)
{ string username = gridviewprofile.Rows[gridviewprofile.SelectedIndex].Cells[1].Text;
Response.Redirect("registration.aspx?id="+username);
}
registration.aspx contains:
protected void Page_Load(object sender, EventArgs e)
{
string queryStringID = Request.QueryString["id"];
displayuser(queryStringID);
}
public void displayuser(string username)
{ user obj = new user();
DataSet objDataset = obj.profile(username);
string strusername = objDataset.Tables[0].Rows[0][0].ToString();
string strpassword = objDataset.Tables[0].Rows[0][1].ToString();
string stremail = objDataset.Tables[0].Rows[0][2].ToString();
usernametxt.Text = strusername;
passwordtxt.Text = strpassword;
emailtxt.Text = stremail;
}

"How to detect Session Timeout And Redirect To Login Page In ASP.NET "

i have a login page in asp.net..if successfully logged in ,it shows login time in next page.. then how to write a common function to detect session timeout and redirect into login.aspx page ?so that i can call it into all other pages
public partial class Login : System.Web.UI.Page
{
MainClass obj = new MainClass();
protected void bt_login_Click(object sender, EventArgs e)
{
string s_name;
SqlCommand cmd = new SqlCommand("select staff_id,staff_name from staff_details where staff_id='" + tb_loginid.Text + "' ", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
if (tb_password.Text == "ABCD" )
{
dr.Read();
string id = dr[0].ToString();
s_name = dr[1].ToString();
Session["staffname"] = s_name;
Session["staffid"] = tb_loginid;
String last_interaction_time = DateTime.Now.ToShortTimeString();
Session["lasttime"] = last_interaction_time;
Response.Redirect("Successfully_loggedin.aspx");
}
}
else
{ ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('Incorrect LoginID or Password!')", true);
lb_invalid.Visible = true;
tb_password.Text = "";
}
}
}
and logged_in page is
public partial class Successfully_logined : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string name=(string)Session["staffname"];
lb_welcome.Text = "Welcome " + name+"!";
string last_login_time= (string)Session["lasttime"];
lb_logintime.Text =last_login_time;
}
}
and web.config is
<sessionState mode="InProc" cookieless="false" timeout="1">
For that you have check condition..You check on Pageload also....
if (Session["Username"] != null)
{
// Code here
}
else
{
Response.Redirect("login.aspx");
}
For more details... Click here ... Session_timeout

Asp.net code-behind login errors?

I am getting an error when it is determining whether the username is false or not. I am using asp.net in code-behind. It is highlighted below. If someone can tell me what the error is that would be amazing!
protected void Login_Authenticate(object sender, AuthenticateEventArgs e)
{
Boolean blnresult;
blnresult = false;
**blnresult = Authentication(Login.UserName);**
if (blnresult == true)
{
e.Authenticated = true;
Session["Check"] = true;
}
else
e.Authenticated = false;
}
private bool Authentication(TextBox textBox)
{
throw new NotImplementedException();
}
protected static Boolean Authentication(string Username, string Password)
{
string sqlstring;
sqlstring = "SELECT userID FROM import_log.dbo.user_verification WHERE userID =" + Username + "";
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source = ietm-fwb-sql1; Initial Catalog = import_log; Persist Security Info = True; User ID = sa; Password = fwbadmin");
System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand(sqlstring, con);
System.Data.SqlClient.SqlDataReader reader;
con.Open();
reader = comm.ExecuteReader();
if (reader.Read())
return true;
else
return false;
}
}
}

Resources