Thursday, March 22, 2012

session variables

Hi i have created a log in page which verifies a users login details, these details will include their access rights and user id which then allows them based on their access rights to view certain pages, this page is then meant to take the user to the home page where the uses details will be displayed in the footer of the page, my problem is i am unsure of how to store the session variables in the login page. below is my cs file, thank you.

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using System.Configuration;

namespace xxx

{

publicpartialclassindex : System.Web.UI.Page

{

protectedvoid cvAuthentication_ServerValidate(Object Source, System.Web.UI.WebControls.ServerValidateEventArgs args)

{

SqlConnection SqlConn =null;

SqlCommand SqlCmd =null;

String strConnection =null;

String strSQL =null;

try

{

args.IsValid =false;

strConnection =ConfigurationManager.AppSettings["strConnectionString"];

SqlConn =newSqlConnection(strConnection);

SqlConn.Open();

strSQL ="SELECT * FROM tblUser WHERE Username ='" + txt_Username.Text +"' and User_Password='" + txt_Password.Text +"'";

SqlCmd =newSqlCommand(strSQL, SqlConn);

SqlCmd.Parameters.Add(newSqlParameter("Username", txt_Username.Text));

SqlCmd.Parameters.Add(newSqlParameter("User_Password", txt_Password.Text));

if (SqlCmd.ExecuteScalar() !=null)

{

args.IsValid =true;

}

}

finally

{

if (SqlConn !=null)

{

SqlConn.Close();

}

}

}

protectedvoid btnLogin_ServerClick(Object sender, System.EventArgs e)

{

if (Page.IsValid)

{

Session["UserAccess"] = ("Access_Right_ID");

Session["UserFullName"] = ("User_Forename") +" "("User_Surname");

Session["UserID"] = ("User_ID");Session["Username"] = ("Username");

Session.Timeout = 60;

Response.Redirect("home.aspx");

}

}

}

}

Here is the code which the user will go to;

</div>

</td>

</tr>

<tr>

<tdcolspan="2"class="container_footing">

<divid="footing">

Currently logged in as<ahref="javascript:logout();"><%=Session["UserFullName"]%></a>

</div>

</td>

</tr>

</table>

This is the page which the homepage refences.

publicclasshome_front_page : System.Web.UI.Page

{

//protected System.Web.UI.WebControls.DataGrid dgAMPs;

protected skmDataGrid.PrettyDataGrid dgAMPs;

privateDataSet dsetRecordsFound =newDataSet();

protected System.Web.UI.WebControls.DataGrid dgCustomers;

privateDataView dvSelectedRecord =newDataView();

protected skmDataGrid.PrettyDataGrid dgSurveys;

protectedDataSet dsetStatistics ;privatevoid Page_Load(object sender, System.EventArgs e)

{

// Put user code to initialize the page here

if(Session["UserAccess"]==null)

{

Response.Redirect("index.aspx?log_out=0",true);

}

ViewState["UserAccess"] = Session["UserAccess"].ToString();

if(!IsPostBack)

{

clsxxx objxxx =newclsxxx();

dsetStatistics =clsxxx.GetDataSetByIDfield("dhoc_FrontPage_Statistics","User_ID",Convert.ToInt32(Session["UserID"]));

Session["dsetStatistics"] = dsetStatistics;

if(ViewState["UserAccess"].ToString()=="2")

{

objxxx.BindGrid(dsetStatistics.Tables[0],"Survey_ID",this.dgSurveys);

this.dgAMPs.Visible =false;

this.dgSurveys.Visible =true;

}

if(ViewState["UserAccess"].ToString()=="3" || ViewState["UserAccess"].ToString()=="4" )

{

objxxx.BindGrid(dsetStatistics.Tables[0],"Survey_ID",this.dgAMPs);

this.dgSurveys.Visible =false;

this.dgAMPs.Visible =true;

}

this.dgAMPs.RowSelectionEnabled =true;

}


Sorry Peter, I'm not to sure what you are asking. Can you explain a little more?


Hi Jperry4, thanks for responding, basically what i am trying to do is set some session variables in my login page which will then be passed through to other pages such as the home page. The code i have pasted above shows that in the home page it is trying to retrieve session variables from the login page(index.cs), thank you

Ok, I think I see what you are asking now. (Sorry it's Monday ;-))

First off your parameters should be like this...

strSQL ="SELECT * FROM tblUser WHERE Username = @.UserName and User_Password= @.Passsword";
SqlCmd =newSqlCommand(strSQL, SqlConn);
SqlCmd.Parameters.Add(newSqlParameter("@.Username", txt_Username.Text));
SqlCmd.Parameters.Add(newSqlParameter("@.User_Password", txt_Password.Text));

Then retrieve the data using a DataReader..
DataReader dbReader = SqlCmd.ExecuteReader();

Then if it has rows store your values in session...

if(dbReader.HasRows)
{
Session["UserAccess"] = dbReader["UserAccessFromDB"].ToString();
//etc...
}

You could do all of this in the Login button click event and redirect after the Session data has been loaded.

It that what you are looking for?


Once again John thanks for answering it is truly appreciated, I have placed the code you suggested into mine, i get this error now can you have a look and see if i have done it properly, thank you

strSQL ="SELECT * FROM tblUser WHERE Username = @.Username and User_Password= @.User_Password";

SqlCmd =newSqlCommand(strSQL, SqlConn);

SqlCmd.Parameters.Add(newSqlParameter("@.Username", txt_Username.Text));SqlCmd.Parameters.Add(newSqlParameter("@.User_Password", txt_Password.Text));

DataReader dbReader = SqlCmd.ExecuteReader();

if (SqlCmd.ExecuteScalar() !=null)

{

args.IsValid =true;

}

}

finally

{

if (SqlConn !=null)

{

SqlConn.Close();

}

}

}

protectedvoid btnLogin_ServerClick(Object sender, System.EventArgs e)

{

if (dbReader.HasRows)

{

Session["UserAccess"] = dbReader["Access_Right_ID"].ToString();

Session["UserID"] = dbReader["UserID"].ToString();

Session["Username"] = dbReader["Username"].ToString();

Session.Timeout = 60;

Response.Redirect("home.aspx");

//etc...

}


Sorry John this is the error i am getting "CS0246: The type or namespace name 'DataReader' could not be found (are you missing a using directive or an assembly reference?), thank you.

SqlDataReader is what you have to use. For the problem you are facing validate the user credentials and if that is a valid one create the session variables and then redirect to the home page...


Hi thanks for answering, i used SqlDataReader but it now gives me this error "CS0103: The name 'dbReader' does not exist in the current context", and can you give me a bit more info about what you are suggesting im a bit of a newbie when it comes to c#, thanks


This is how my code looks right now and the error it gives is "CS0103: The name 'dbReader' does not exist in the current context"

publicpartialclassindex : System.Web.UI.Page

{

protectedvoid cvAuthentication_ServerValidate(Object Source, System.Web.UI.WebControls.ServerValidateEventArgs args)

{

SqlConnection SqlConn =null;

SqlCommand SqlCmd =null;

String strConnection =null;

String strSQL =null;

try

{

args.IsValid =false;

strConnection =ConfigurationManager.AppSettings["strConnectionString"];

SqlConn =newSqlConnection(strConnection);

SqlConn.Open();

strSQL ="SELECT * FROM tblUser WHERE Username = @.Username and User_Password= @.User_Password";

SqlCmd =newSqlCommand(strSQL, SqlConn);

SqlCmd.Parameters.Add(newSqlParameter("@.Username", txt_Username.Text));SqlCmd.Parameters.Add(newSqlParameter("@.User_Password", txt_Password.Text));

SqlDataReader dbReader = SqlCmd.ExecuteReader();

if (SqlCmd.ExecuteScalar() !=null)

{

args.IsValid =true;

}

}

finally

{

if (SqlConn !=null)

{

SqlConn.Close();

}

}

}

protectedvoid btnLogin_ServerClick(Object sender, System.EventArgs e)

{

if (dbReader.Hasrows)

{

Session["UserAccess"] = dbReader["Access_Right_ID"].ToString();

Session["UserID"] = dbReader["UserID"].ToString();

Session["Username"] = dbReader["Username"].ToString();Session["UserFullName"] = dbReader["Username"].ToString() +" " + dbReader["User_Surname"].ToString();

Session.Timeout = 60;

Response.Redirect("home.aspx");

//etc...

}


ok Peter...here it is..

You have created the sqldatareader object(dbReader) in the function "cvAuthentication_ServerValidate" and that is why dbReader object is not accessible from the function "btnLogin_ServerClick". ie..The objects declared inside a function has a scope local to that function and is not available outside. You can make it accessible by declaring it as a class level variable(inside the class but out side the function)

publicpartialclassindex : System.Web.UI.Page

{

SqlDataReader dbReader;

protectedvoid cvAuthentication_ServerValidate(Object Source, System.Web.UI.WebControls.ServerValidateEventArgs args)

.....same code as you have written but change the line

SqlDataReader dbReader = SqlCmd.ExecuteReader();

to

dbReader = SqlCmd.ExecuteReader();

i suggest you write all these ( code inside the cvAuthentication_ServerValidate) in the btnLogin_ServerClick. the sqlreader requires a open connection so make sure you are not closing it before the use of dbreader is completely over.


Hi Joe thanks for answering, if i transfer all the code from the cvAuthentication to the btnLogin will i still be able to achieve validation?


I guess you have textboxes to enter the userid and password and a login button....in that case in the validation function you can check if the user has entered his username or has left it blank sort of validations....once you are sure that the user has entered some thing proper in the fields you can check what he has eneter in the inputs fields match with the ones present in the database...in if it matches you create the session variables and redirect to the home page...


Thanks for all your help Joe, I have now placed it under the login button, it seems to be working but is now giving me a different error so i think I am making progress with it, this is the error "Invalid attempt to read when no data is present. "

and here is my code;

publicpartialclassindex : System.Web.UI.Page

{

protectedvoid btnLogin_ServerClick(Object sender, System.EventArgs e)

{

SqlConnection SqlConn =null;

SqlCommand SqlCmd =null;

String strConnection =null;

String strSQL =null;

strConnection =ConfigurationManager.AppSettings["strConnectionString"];SqlConn =newSqlConnection(strConnection);

SqlConn.Open();

strSQL ="SELECT * FROM tblUser WHERE Username = @.Username and User_Password= @.User_Password";

SqlCmd =newSqlCommand(strSQL, SqlConn);

SqlCmd.Parameters.Add(newSqlParameter("@.Username", txt_Username.Text));SqlCmd.Parameters.Add(newSqlParameter("@.User_Password", txt_Password.Text));

SqlDataReader dbReader = SqlCmd.ExecuteReader();

if (dbReader.HasRows)

{

Session["UserAccess"] = dbReader["Access_Right_ID"].ToString();

Session["UserID"] = dbReader["UserID"].ToString();

Session["Username"] = dbReader["Username"].ToString();

Session["UserFullName"] = dbReader["Username"].ToString() +" " + dbReader["User_Surname"].ToString();

Session.Timeout = 60;

Response.Redirect("home.aspx");

//etc...

}

else

{

lblMessage.Text ="Please check your Username and password and try again";

}

}

}

}


Now the code looks better...

SqlDataReader reads data row by row from the data base...so before you try to access the data in a datareader you have to do a read operation...in your case dbreader.read() before checking if it has data or not. But even the read operation returns a boolean value indicating there is data to be read or not. So you can make it work by just changingif (dbReader.HasRows) to if(dbReader.Read())...that should work fine..

0 comments:

Post a Comment