How to stop opening a login page in (asp.net webforms) when user is already logged in the same browser in different tab - asp.net

I have logged in as a user and it works fine , but when i try to open the login in a different tab in same browser it still goes to the login.aspx without the actual member page
Please help !
Aboutus.aspx
protected void Page_Load(object sender, EventArgs e)
{
if(Session["Username"] == null)
{
Response.Redirect("Login.aspx");
}
else
{
string Username = Session["Username"].ToString();
Label1.Text = Username;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session.Abandon();
Response.Redirect("Login.aspx");
}
}
Login.aspx
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select COUNT(*)FROM [dbo].[Reg] WHERE Username='" + Login1.UserName + "' and Password=#pass");
cmd.Connection = con;
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
////create an array of bytes we will use to store the encrypted password
Byte[] hashedBytes;
////Create a UTF8Encoding object we will use to convert our password string to a byte array
UTF8Encoding encoder = new UTF8Encoding();
////encrypt the password and store it in the hashedBytes byte array
hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(Login1.Password));
cmd.Parameters.AddWithValue("#pass", hashedBytes);
var username = Login1.UserName;
int OBJ = Convert.ToInt32(cmd.ExecuteScalar());
if (OBJ > 0)
{
if (username == "admin")
{
Session["Username"] = Login1.UserName;
Response.Redirect("AdminPanel.aspx");
}
else
{
Session["Username"] = Login1.UserName;
Response.Redirect("About.aspx");
}
}
else
{
Label1.Text = "Invalid username or password";
this.Label1.ForeColor = Color.Red;
}
}
}
}

In Page_Load of Login.aspx do this:
if(Session["Username"] != null)
{
string username = Convert.ToString(Session["Username"]);
if (username == "admin")
{
Response.Redirect("AdminPanel.aspx");
}
else
{
Response.Redirect("About.aspx");
}
}

Your page laod method on Loginpage must be like this
protected void Page_Load(object sender, EventArgs e)
{
if(Session["Username"] == null)
{
}
else
{
Response.Redirect("index.aspx",false);
}
}
I hope this helps

Related

Cookie always return null in asp.net

net web pages,in the first one, I wrote like below:
protected void lbXML_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("RequestedXML");
cookie["xmlContent"] = hide_XML.Value;
Response.Cookies.Add(cookie);
cookie.Expires = DateTime.Now.AddMinutes(20);
Response.Write("<script>window.open('XML_Editor.aspx', '_blank', 'toolbar=no, location=no, resizable=yes, width=800px, height=500px', true);</script>");
}
In XML_Editor.aspx, I wrote code like this:
protected void Page_Load(object sender, EventArgs e)
{
Page lastPage = (Page)Context.Handler;
if (!IsPostBack)
{
HttpCookie cookie = Request.Cookies["RequestedXML"];
if (cookie != null)
{
TextBox1.Text = cookie["xmlContent"];
}
}
}
the problem is that the cookie always return null to me in Page_Load in XML_Editor.aspx, why is that?
Your problem can be you code, try it:
HttpCookie cookie = new HttpCookie("RequestedXML");
cookie.Value =hide_XML.Value;
cookie.Expires = DateTime.Now.AddMinutes(20);
Response.Cookies.Add(cookie);
Response.Write("<script>window.open('XML_Editor.aspx', '_blank', 'toolbar=no, location=no, resizable=yes, width=800px, height=500px', true);</script>");
XML_Editor.aspx
Page lastPage = (Page)Context.Handler;
if (!IsPostBack)
{
var cookie = Request.Cookies["RequestedXML"];
if (cookie != null)
{
Response.Write(cookie.Value);
}
}

Session is not being created...why?

On login page i have created the session like this.
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
if (Session["UserId"] != null)
{
Response.Redirect("~/client/ClientHome.aspx");
}
if (Request.QueryString["error"] != null)
{
loginuser.FailureText= "Please Login to visit the Page";
}
}
protected void loginuser_LoggedIn(object sender, EventArgs e)
{
if (Roles.IsUserInRole(loginuser.UserName, "admin"))
{
string username = loginuser.UserName;
DataSet ds = new DBUsers().GetUserId(username);
Guid userid = Guid.Parse(ds.Tables[0].Rows[0][0].ToString());
Session["UserId"] = userid;
Response.Redirect("Admin/Home.aspx");
}
else if (Roles.IsUserInRole(loginuser.UserName, "client"))
{
bool isPersistent = false;
string username = loginuser.UserName;
DataSet ds = new DBUsers().GetUserId(username);
Guid userid = Guid.Parse(ds.Tables[0].Rows[0][0].ToString());
Session["UserId"] = userid;
string userData = "ApplicationSpecific data for this user.";
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
// Redirect back to original URL.
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
}
}
here value of session is not null , it contains userid
but when the home page loads it says that the value of session is null
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
if (Session["UserId"] == null)
{
Response.Redirect("../Login.aspx?error=1");
}
}
why it enters inside if statement, why sesion value is null.

ASP.NET, Code on click of a next button

The following is my code, I am doing project on online examination in that I have a module of question to display in this when I click on next button it should go to the next question but it is not going.
public partial class Student : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
int i=1;
Session["Number"] = i;
protected void Page_Load(object sender, EventArgs e)
{
Session["Number"] = i++;
Label1.Text = Session["Number"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Questions where QuestionNo = '"+Label1.Text+"'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Label2.Text = dr["Question"].ToString();
Label3.Text = dr["Ans1"].ToString();
Label4.Text = dr["Ans2"].ToString();
Label5.Text = dr["Ans3"].ToString();
Label6.Text = dr["Ans4"].ToString();
}
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("Select * from Answers where QuestionNo = '" + Label1.Text + "'", con);
SqlDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
Label8.Text = dr1["Answer"].ToString();
}
con.Close();
}
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked)
{
Label7.Text = Label3.Text;
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
Label7.Text = Label4.Text;
}
}
protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton3.Checked)
{
Label7.Text = Label5.Text;
}
}
protected void RadioButton4_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton4.Checked)
{
Label7.Text = Label6.Text;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Label7.Text == Label8.Text)
{
Label9.Text = "Your Answer is correct";
}
else
Label9.Text = "Your Answer is incorrect";
}
protected void Button2_Click(object sender, EventArgs e)
{
i++;
Session["Number"] = i;
Response.Redirect("Student.aspx");
}
}
So many bad things in this code.
You should always give names to your variables properly.
Don't concatenate SQL queries because security reasons like SQL Injection
You should use Session["Number"] to select the question number rather than Label1.Text.
Use session when it was only necessary.
First thing that you are doing wrong is how you are trying to store value of i in your Session. You are overwriting it every time you get into the method and thus resulting in same question number on each button click.
Second, you should parametrized your queries.
On each button click you should retrieve the value of i from your session and then increment it and again store it in the session. like:
int i = 0;
if (Session["Number"] == null)
{
Session["Number"] = i;
}
else
{
i = Convert.ToInt32(Session["Number"]);
}
//Later To increment Session
Session["Number"] = ++i; //First increments, then assigns the value
You should also use ++i instead of i++ since that will store the value of i before increment.

radio button not working in asp.net

I am beginner.radio button not working properly. I dn't know what is a problem
protected void RadioButton1_CheckedChanged1(object sender, EventArgs e)
{
if (RadioButton1.Checked == true)
{
Label1.Text = "Upload our video file";
RadioButton2.Checked = false;
}
else
{
Label1.Text = "Upload our image file";
RadioButton1.Checked = false;
}
}
public void upload()
{
SqlCommand cmd = new SqlCommand("insert into video_info(Name,path,user_name,email,comment)values(#Name,#path,#user_name,#email,#comment)", con);
cmd.Parameters.AddWithValue("#Name", txt_file.Text);
cmd.Parameters.AddWithValue("#path", "video/" + fileuplod.FileName);
cmd.Parameters.AddWithValue("#user_name", use_name.Text);
cmd.Parameters.AddWithValue("#email", email.Text);
cmd.Parameters.AddWithValue("#comment", comment.Text);
fileuplod.SaveAs(Server.MapPath("~/video/" + fileuplod.FileName));
cmd.ExecuteNonQuery();
}
protected void submit_Click(object sender, EventArgs e)
{
upload();
}
}
What I want to do.I have two radio button.Image and video.Suppose user select image.then all the detail will save on image table or if user click on video.All the detail goes to image_database.
May be my logic is wrong.
put auto postback to true in radiobutton property
Try this
public void upload(string query)
{
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Name", txt_file.Text);
cmd.Parameters.AddWithValue("#path", "video/" + fileuplod.FileName);
cmd.Parameters.AddWithValue("#user_name", use_name.Text);
cmd.Parameters.AddWithValue("#email", email.Text);
cmd.Parameters.AddWithValue("#comment", comment.Text);
fileuplod.SaveAs(Server.MapPath("~/video/" + fileuplod.FileName));
cmd.ExecuteNonQuery();
}
protected void submit_Click(object sender, EventArgs e)
{
string query;
if (RadioButton1.Checked == true)
{
query="insert into video_info(Name,path,user_name,email,comment)values(#Name,#path,#user_name,#email,#comment)";
Label1.Text = "Upload our video file";
RadioButton2.Checked = false;
}
else
{
query="insert into Image_info(Name,path,user_name,email,comment)values(#Name,#path,#user_name,#email,#comment)";
Label1.Text = "Upload our image file";
RadioButton1.Checked = false;
}
if(query!="")
{
upload(query);
}
}

"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

Resources