Showing posts with label created. Show all posts
Showing posts with label created. Show all posts

Monday, March 26, 2012

session variable getting lost

Okay, don't bash me to hard for my design on this app, it's my first web app
and it's in production.
My basic design is using Datatables created via the designer with a business
logic class in between the datatable and ObjectDataSources.
In one page I had a Gridview with select enabled. When an row in the grid is
selected, I retrieve the SelectedValue, store the value in a Session
variable and redirect the response to another web page, which, has an
ObjectDataSource on it and a DetailsView. The ObjectDataSource on this page
retrieves the value of the Session variable set from the first page. The
problem is that the Session variable is randomly losing its value.
So, the ObjectDataSource's Business object's SelectMethod accepts a value to
select records by. How do I know that the value is getting lost?
Because no rows are returned as:
dr = dtAdapter.Rows(0)

throws an exception IndexOutOfRange.

My question is, is there some reason that my session variable evaporates
randomly?

Thanks in advance

SAL"SAL" <SAL@.nospam.nospamwrote in message
news:u5$G%23JMIIHA.4712@.TK2MSFTNGP04.phx.gbl...

Quote:

Originally Posted by

My question is, is there some reason that my session variable evaporates
randomly?


No. Session variables will be lost when the Session times out, or when they
are overwritten / removed - does either of these situations apply here...?

--
Mark Rae
ASP.NET MVP
http://www.markrae.net
Mark, thanks for the reply.
I do not see either of these things applying here. This happened twice this
morning for no apparent reason and then it didn't happen. I have not changed
the time out so it should still be 20 minutes and I am not overwriting them
as far as I can see. I can not reproduce it on my machine.

S

"Mark Rae [MVP]" <mark@.markNOSPAMrae.netwrote in message
news:%237xKnRMIIHA.5056@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

"SAL" <SAL@.nospam.nospamwrote in message
news:u5$G%23JMIIHA.4712@.TK2MSFTNGP04.phx.gbl...
>

Quote:

Originally Posted by

>My question is, is there some reason that my session variable evaporates
>randomly?


>
No. Session variables will be lost when the Session times out, or when
they are overwritten / removed - does either of these situations apply
here...?
>
>
--
Mark Rae
ASP.NET MVP
http://www.markrae.net


Hi SAL,

Based on my understanding, you're redirecting to the second page right
after setting the session variable, right? If this is the case, there's no
reason the session variable will be lost due to session timeout. Could you
please double check if the session variable is really lost or it's because
the query that uses the variable to retrieve records from database returns
empty result?

By the way, there's another way to pass variables between pages using
Context.Items and Server.Transfer:

#Famil Jones : Pass Variables Between ASP.NET Pages
http://www.dotnetjunkies.com/WebLog...4/08/11020.aspx
Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
Hmmm, thank you for the replies all.
Would it be possible for Walter or someone else to comment on the load that
using the Server.Transfer pattern would place on the server? So, is there an
increased load on the server using this model as compared to using Session
variables?

Thanks
SAL

"SAL" <SAL@.nospam.nospamwrote in message
news:u$66KsMIIHA.3356@.TK2MSFTNGP02.phx.gbl...

Quote:

Originally Posted by

Mark, thanks for the reply.
I do not see either of these things applying here. This happened twice
this morning for no apparent reason and then it didn't happen. I have not
changed the time out so it should still be 20 minutes and I am not
overwriting them as far as I can see. I can not reproduce it on my
machine.
>
S
>
"Mark Rae [MVP]" <mark@.markNOSPAMrae.netwrote in message
news:%237xKnRMIIHA.5056@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

>"SAL" <SAL@.nospam.nospamwrote in message
>news:u5$G%23JMIIHA.4712@.TK2MSFTNGP04.phx.gbl...
>>

Quote:

Originally Posted by

>>My question is, is there some reason that my session variable evaporates
>>randomly?


>>
>No. Session variables will be lost when the Session times out, or when
>they are overwritten / removed - does either of these situations apply
>here...?
>>
>>
>--
>Mark Rae
>ASP.NET MVP
>http://www.markrae.net


>
>


Hi SAL,

Regarding difference between Response.Redirect and Server.Transfer, I think
following page is useful for your reference. Each approach has its own pros
and cons.

#Response.Redirect vs Server.Transfer
http://haacked.com/archive/2004/10/...rvertransfer.as
px

Back to the original issue about losing session after Redirect, I think
George's suggestion is quite helpful.

Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
Thank you for your reply and the article link.
I am currently investigating George's suggestion as well

S

""Walter Wang [MSFT]"" <wawang@.online.microsoft.comwrote in message
news:RatUSdeIIHA.4268@.TK2MSFTNGHUB02.phx.gbl...

Quote:

Originally Posted by

Hi SAL,
>
Regarding difference between Response.Redirect and Server.Transfer, I
think
following page is useful for your reference. Each approach has its own
pros
and cons.
>
#Response.Redirect vs Server.Transfer
http://haacked.com/archive/2004/10/...rvertransfer.as
px
>
Back to the original issue about losing session after Redirect, I think
George's suggestion is quite helpful.
>
>
Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support
>
==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================
>
This posting is provided "AS IS" with no warranties, and confers no
rights.
>


"SAL" <SAL@.nospam.nospamwrote in
news:uFUwqXiIIHA.6108@.TK2MSFTNGP03.phx.gbl:

Quote:

Originally Posted by

Thank you for your reply and the article link.
I am currently investigating George's suggestion as well


Please post back here if (and when) you find the culprit.

I have stopped using sesion variables altogether becuase of
similar issues on a client's server, but am very interested
in what you figure out.

Now my client may well be changing the web.config file
which will cause the application to restart, all the more
reason to not use session varialbes (in my case).

Instead I pass info encrypted in the query string, which
works just fine, the only session variable I use is to
relay error messages to tan error page - if that gets
lost, oh well.

kpg
Hi SAL,

This looks like a normal shutdown, try to use following method to log the
cause and the time it occurs:

#Logging ASP.NET Application Shutdown Events - ScottGu's Blog
http://weblogs.asp.net/scottgu/arch.../14/433194.aspx
Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
Hi SAL,

How's the issue now?

Not directly related, but I think following information might be useful:

#Thomas Marquardt's Blog : ASP.NET File Change Notifications, exactly which
files and directories are monitored?
http://blogs.msdn.com/tmarq/archive...hange-notificat
ions-exactly-which-files-and-directories-are-monitored.aspx

Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
Okay, I did that. Now I'm getting this in the event log:

The description for Event ID ( 0 ) in Source ( .NET Runtime ) cannot be
found. The local computer may not have the necessary registry information or
message DLL files to display messages from a remote computer. You may be
able to use the /AUXSOURCE= flag to retrieve this description; see Help and
Support for details. The following information is part of the event:

_shutDownMessage=HostingEnvironment caused shutdown

_shutDownStack= at System.Environment.GetStackTrace(Exception e, Boolean
needFileInfo)
at System.Environment.get_StackTrace()
at System.Web.HttpRuntime.ShutdownAppDomain()
at System.Web.Hosting.HostingEnvironment.ShutdownThis AppDomainOnce()
at
System.Web.Hosting.HostingEnvironment.InitiateShut downWorkItemCallback(Object
state)
at System.Threading.

Which I really don't understand. Help?

S

""Walter Wang [MSFT]"" <wawang@.online.microsoft.comwrote in message
news:OI6Y7QoIIHA.4200@.TK2MSFTNGHUB02.phx.gbl...

Quote:

Originally Posted by

Hi SAL,
>
This looks like a normal shutdown, try to use following method to log the
cause and the time it occurs:
>
#Logging ASP.NET Application Shutdown Events - ScottGu's Blog
http://weblogs.asp.net/scottgu/arch.../14/433194.aspx
>
>
Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support
>
==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================
>
This posting is provided "AS IS" with no warranties, and confers no
rights.
>


Hi Walter. It's just as bad as ever and what I don't get is that, I'm not
changing anything when this stuff occurs that I'm aware of. All I'm doing is
redirecting to another page, changing DetailsView states to edit, cancelling
the edit, clicking another menu item and doing the same thing all over again
and it will restart which causes the ID of the item the viewer is using to
be lost in the session variable. And, since the ObjectDataSource is getting
records based on this ID, the app fails with a web page that isn't showing
any data.

S

""Walter Wang [MSFT]"" <wawang@.online.microsoft.comwrote in message
news:FRH$rDnJIHA.4200@.TK2MSFTNGHUB02.phx.gbl...

Quote:

Originally Posted by

Hi SAL,
>
How's the issue now?
>
Not directly related, but I think following information might be useful:
>
#Thomas Marquardt's Blog : ASP.NET File Change Notifications, exactly
which
files and directories are monitored?
http://blogs.msdn.com/tmarq/archive...hange-notificat
ions-exactly-which-files-and-directories-are-monitored.aspx
>
>
Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support
>
==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================
>
This posting is provided "AS IS" with no warranties, and confers no
rights.
>


kpg,
what I figured out was the app was getting recycled due to a limit I had set
on virtual memory. There are times when the virtual memory usage jumps up
dramatically and then it pops right back down. The app does not appear to be
leaking memory at this time. So, I unchecked that option in the App pool's
configuration.
I used information garnered from this link to aid me in my quest, although I
haven't completely implemented Peter's Exception Engine.
http://www.eggheadcafe.com/articles/20030816.asp
I placed this code in my Application_Error routine in my Global.asax file:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
' check to see if the ASPNETApplication log exists
Dim b As Boolean
Try
b =
Convert.ToBoolean(ConfigurationManager.AppSettings ("logAppErrors"))
Catch ex As Exception

End Try
If Not b Then Exit Sub

If Not System.Diagnostics.EventLog. _
SourceExists("AnnexationTrackerApplication") Then
System.Diagnostics.EventLog. _
CreateEventSource("AnnexationTrackerApplication",
"Application")
End If
System.Diagnostics.EventLog. _
WriteEntry("AnnexationTrackerApplication",
Server.GetLastError().GetBaseException().Message)

End Sub

The message appeared in the system event log not the application event log.

HTH
S

"kpg*" <no@.spam.comwrote in message
news:Xns99E27E9E22F89ipostthereforeiam@.207.46.248. 16...

Quote:

Originally Posted by

"SAL" <SAL@.nospam.nospamwrote in
news:uFUwqXiIIHA.6108@.TK2MSFTNGP03.phx.gbl:
>

Quote:

Originally Posted by

>Thank you for your reply and the article link.
>I am currently investigating George's suggestion as well


>
Please post back here if (and when) you find the culprit.
>
I have stopped using sesion variables altogether becuase of
similar issues on a client's server, but am very interested
in what you figure out.
>
Now my client may well be changing the web.config file
which will cause the application to restart, all the more
reason to not use session varialbes (in my case).
>
Instead I pass info encrypted in the query string, which
works just fine, the only session variable I use is to
relay error messages to tan error page - if that gets
lost, oh well.
>
kpg

session variable lost across different folders

Hi

A session variable that I have created can only be shared by the pages within the same directory where the page containing the session variable is sitting. Once I redirect the page to another page outside the folder (a different folder), the session variable is lost (empty). I understood that a session variable is meant to be used across all files in an application. Am I missing something here? Or I didn't setup properly?

Please help.

ThanksIs is useable throughout and application. IE if you have an application directory called /myapp then all folders under that directory will accept the session variable. (I think). There are a number of ways to get around this. If you tell me were the 2 differnt folders are located,(relative to eachother). and what kind of value you are trying to pass I'll be able to help you.

One last thing: what kinda of script are you trying to write? login page, shopping cart, etc...

Ryder
Thanks Ryder!

I have an application folder called 'QSAConnect' and under this folder there are several sub-folders. The page with the session variable called Session("StudentID") is saved in a sub-folder called 'AbsRecordEntry', and I want to redirect this page to another page, called absreport.aspx, which requires this Session("StudentID") as a passing parameter for all the functions. The target page(absreport.aspx) is located in a sub-directory called 'AbsReport'. Here is the code:


Sub btnViewReport_Click(sender As Object, e As EventArgs)
Dim strStudentID as string
strStudentID=lbxStudentLastName.Items(lbxStudentLastName.SelectedIndex).Value
Session("StudentID") = strStudentID
response.redirect(".../AbsReport/absreport.aspx")

End Sub


This produced an empty session variable when the absreport.aspx loaded. But if I place the file absreport.aspx under AbsRecordEntry folder and change code to:

response.redirect("absreport.aspx")

there is no problem.

I hope you can understand my explanation.

Thanks again

Haiyi
hmmm, I created a similar situation on my testing server a few minutes ago and it worked fine. But what I did notice is that i wrote my response.redirect line a bit differntly and I think that may be it.

see, here is how you wrote yours: response.redirect(".../AbsReport/absreport.aspx")
and this is how I wrote mine: response.redirect("../AbsReport/absreport.aspx")

notice I only have 2 periods not 3. So my next step was to try my code with 3 periods. It generated an error, so i beleive that may be it. The only onther thing I could think of off the top of my head was that maybe the folder AbsRecordEntry or AbsReport is also an application directory. because this would cause a problem perhaps.

Let me know if this works.

Ryder

Saturday, March 24, 2012

Session variable problem

I have a Session object set on Session_Start...
I figured out that the object is never created...
Cannot understand why..

Also I noticed that the debugger will not stop at
breakpoints that are inside the Session_Start method or in
the class of the object that is created within the
Session_Start method...

Is this a bug or a setting problem?
any ideas?I think you might be misunderstanding the message.
The message is probably referring to the Session object
being nothing, not the content.

Session will never bomb out on an object being nothing in
the context you show. Session will be nothing in any
classes you create. Instead,
use "Current.Session.item..." and you should be able to
get your object just fine.

It helps to put a reference to:
System.Web.HttpContext
in your "Imports" in the project properties under the
properties page, Common Properties folder. Otherwise you
need to reference System.Web.HttpContext.Current.Session

Email if you need more...
>--Original Message--
>Ok...
>in Global.asax I have:
>protected void Session_Start(Object sender, EventArgs e)
>{
>cms.errorHandler error = new cms.errorHandler();
>Session["error"] = error;
>}
>and then in my code I have:
>errorHandler error = (errorHandler)Session["error"];
>I get:
>Object Reference not set to an instance of an object
>(NullReferenceException).
>I even get the Exception if I do:
>Session["test"] = "Test";
>Yes I debug the application
>.
I dont understand where to put the reference of
System.Web.HttpContext to. Is there such thing? On my
project properties page there no such thing as "Imports"
under Common Properties. I couldnt find anything like that.
Even in the code if I do "using System.Web." there is not
HttpContext...

Am I missing something here?

>--Original Message--
>I think you might be misunderstanding the message.
>The message is probably referring to the Session object
>being nothing, not the content.
>Session will never bomb out on an object being nothing in
>the context you show. Session will be nothing in any
>classes you create. Instead,
>use "Current.Session.item..." and you should be able to
>get your object just fine.
>It helps to put a reference to:
>System.Web.HttpContext
>in your "Imports" in the project properties under the
>properties page, Common Properties folder. Otherwise you
>need to reference System.Web.HttpContext.Current.Session
>Email if you need more...
>>--Original Message--
>>Ok...
>>
>>in Global.asax I have:
>>
>>protected void Session_Start(Object sender, EventArgs e)
>>{
>>cms.errorHandler error = new cms.errorHandler();
>>Session["error"] = error;
>>}
>>
>>and then in my code I have:
>>
>>errorHandler error = (errorHandler)Session["error"];
>>
>>I get:
>>Object Reference not set to an instance of an object
>>(NullReferenceException).
>>
>>I even get the Exception if I do:
>>
>>Session["test"] = "Test";
>>
>>Yes I debug the application
>>.
>>
>.

Session variable, need help!

Hi All!

In my login page, I created a session variable to hold the username(studentId). It's not working! It's very frustrating!! Anybody figure out what my problem is?!

My Code:

Login page Code:

Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack then

dim user as string = UserName.Text
Session("StudentID") = user

End If
End Sub

Sub LoginBtn_Click(Sender As Object, E As EventArgs)

If Page.IsValid Then
Dim userDS As New System.Data.DataSet

userDS = password(UserName.Text, UserPass.Text)

If userDS.Tables(0).Rows.Count = 1 Then

FormsAuthentication.RedirectFromLoginPage(UserName.Text, true)
Else
Msg.Text = "***Invalid Credentials: Please try again***"
End If
End If

End Sub


Next Page Code:

Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack then


Dim id = CType(Session("StudentID"), string)
Label1.Text = id.ToString()


End If
End Sub

make sure that you have session enabled.

Hi!

Don't know how to do that! Can you explain to me how I can do it?

Collette


I think the problem is that you are setting the session variable in thepage load method, and at that time UserName.Text is probablyblank! Try creating the session variable in the click event ofthe login button and see if that solves the problem.

Hi!

I tried this:

Sub LoginBtn_Click(Sender As Object, E As EventArgs)

If Page.IsValid Then
Dim userDS As New System.Data.DataSet

userDS = password(UserName.Text, UserPass.Text)

Session("UserName") = user

If userDS.Tables(0).Rows.Count = 1 Then

FormsAuthentication.RedirectFromLoginPage(UserName.Text, true)
Else
Msg.Text = "***Invalid Credentials: Please try again***"
End If
End If

End Sub

Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack then

dim user as string
user = UserName.Text

End If
End Sub

But Im getting the following error:

Object reference not set to an instance of an object.

Please help!!!



Panic Over!!

Sussed it out, appreciate the help I got, Thanx guys!Wink [;)]


Your variable "User" is not a global variable in your page. It islocal to the Page_Load method and hence not usable in any other method.
Try the following ... note the change in the underlined text.

Sub LoginBtn_Click(Sender As Object, E As EventArgs)

If Page.IsValid Then
Dim userDS As New System.Data.DataSet

userDS = password(UserName.Text, UserPass.Text)

Session("UserName") = UserName.Text

If userDS.Tables(0).Rows.Count = 1 Then

FormsAuthentication.RedirectFromLoginPage(UserName.Text, true)
Else
Msg.Text = "***Invalid Credentials: Please try again***"
End If
End If

End Sub


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..

Session Variables

I am developing a web application using frames(main and menu). User logs in, sessions are created and when the user logs out the sessions are set to null. Logout button is in the menu frame. This work fine for the main frame but the menu frame still think that the sessions are not created because it's giving me a null value. Can anyone tell me what I am doing wrong here? I don't want to use cookies. Thanks for any helpCan anyone tell me what I am doing wrong here?

You are using frames, don't use them ;)

You are always going to be fighting with this because the browser sees the 2 frame windows as separate windows being openned. So if you set a session in one, it doesn't associate it with the other. You might be able to set the session in your core page that has the source for creating the frames, but there are no guarantees.

So I stick with my suggestion of dumping the frameset and using tables since you don't want to be bothered with cookies (which are as secure and usable as sessions mind you)