"How to detect Session Timeout And Redirect To Login Page In ASP.NET " - 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

Related

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

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

Grid View only updates when page refresh

In my application i have a grid view and a save task button. when i click save task my button , the Grid View doesn't refresh but when i click the refresh button of browser the grid refreshes and automatically add another task in the database. All i want is to refresh the grid when save task button is click and not add task when browser refresh button is clicked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
static string startdate;
DataTable dt;
static string enddate;
static string EstDate;
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
protected void Page_Load(object sender, EventArgs e)
{//Page dosn't go back//
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetNoStore();
if (IsPostBack)
{
if (Session["auth"] != "ok" )
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
//Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
else
{
GridView1.DataSource = dt;
GridView1.DataBind();
if (Session["auth"] != "ok")
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
// Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
//decode url data in query string
labelID.Text = HttpUtility.UrlDecode(Request.QueryString["Id"]);
labelDur.Text = HttpUtility.UrlDecode(Request.QueryString["Duration"]);
labelStatus.Text = HttpUtility.UrlDecode(Request.QueryString["Status"]);
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
if (!IsPostBack)
{
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
}
protected void saveTask_Click(object sender, EventArgs e)
{
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
try
{
String query = "insert into Tasks (T_Description, T_Status,S_ID,StartDate,EstEndDate) values('" + TaskDesBox.Text + "', 'incomplete','" + labelID.Text + "' ,'" + startdate + "','" + EstDate + "');";
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
GridView1.DataBind();
}
else
{
TaskStatus.Text = "Task not Saved";
}
}
catch (Exception ex)
{
Response.Write("reeor" + ex);
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void TaskDesBox_TextChanged(object sender, EventArgs e)
{
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
startdate = Calendar1.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
SDate.Text = startdate;
Calendar1.Visible = false;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Calendar2.Visible = true;
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
EstDate = Calendar2.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
EstDateBox.Text = EstDate;
Calendar2.Visible = false;
}
}
What you are doing on a post back is:
First show the results due to code in your Page_Load
Then perform event handlers, so if you pushed the Save button, the saveTask_Click will be performed, which adds a record to the database. You don't update your grid view datasource, but just call DataBind() afterwards which still binds the original DataSource.
Imo you shouldn't update your grid view on Page_Load. You should only show it initially on the GET (!IsPostBack).
And at the end of saveTask_Click you have to update your grid view again.
So move the code you need to show the grid view to a method you can call on other occasions:
protected void ShowGridView() {
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
Then call it in your Page_Load on !IsPostBack
if (!IsPostBack)
{
ShowGridView();
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
Then after adding the row in saveTask_Click you can call ShowGridView() to see the new result.
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
//GridView1.DataBind();
ShowGridView();
}
else
{
TaskStatus.Text = "Task not Saved";
}

Restricting user access in 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>

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;
[...]

How to provide different user pages with same login page for different users?

what i am tryin to do is
i have common login page with 4 users each has different roles
and i have a Singel master pages where i have different contorls.....how to provide authentication to the own page with the contorls assigned to them..regarding on thier role they should be directed to the given page....
user 1 manager he needs only some controls on the page so when he logins the master page should contain only the controls assgned to him
applys the same for all users
can any one help me......planing ,i dont know where to start....
Try This in Button Click
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DebitCareBankApp;Data Source=SSDEV7-HP\\SQLEXPRESS");
string cmdStr = "select LoginType from Login where UserName='" + TxtUserName.Text + "' AND Password = '" + TxtPassword.Text + "'";
SqlCommand cmd = new SqlCommand(cmdStr, con);
con.Open();
Object TypeUser = cmd.ExecuteScalar();
con.Close();
if (TypeUser != null)
{
LblError.Visible = false;
LblError.Text = "";
if (TypeUser.ToString() == "Manager")
{
Response.Redirect("~//Administration/Manager/WorkManagement.aspx");
}
else if (TypeUser.ToString() == "HR")
{
Response.Redirect("~//Administration/Hr/CalculateAndGeneratePayslips.aspx");
}
else if (TypeUser.ToString() == "Employee")
{
Response.Redirect("~//Administration/CallingAgent/TodaysWork.aspx");
}
}
else
{
LblError.Visible = true;
LblError.Text = "Invalid Credentials Entered, Try again";
}
There is simple way for this approach below are the steps you can follow
Keep one default Master Page // ("MasterPage.master")
Add as many master pages according to requirement // "manager.master/Admin.master"
Add the Pages to the default Master page
Add class file in app_code where u can map dynamic masterpage
Add this class in App_Code
public class DynamicPage : System.Web.UI.Page
{
protected override void OnPreInit(EventArgs e)
{
string masterfile = getMasterPageFromDatabase();
if (!masterfile.Equals(string.Empty))
{
base.MasterPageFile = masterfile;
}
base.OnPreInit(e);
}
private string getMasterPageFromDatabase()
{
// check the conditions "manager.master/Admin.master"
return "Admin.master";
}
}
when coming to .cs file for default.aspx.cs it would be "System.Web.UI.Page" replace that with DynamicPage
public partial class _Default : **System.Web.UI.Page**
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
finally it comes like
public partial class _Default : **DynamicPage**
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
rest will happen automatically mapped
hope this helps !!!

Resources