Showing posts with label class. Show all posts
Showing posts with label class. Show all posts

Monday, March 26, 2012

Session Variable in Class

Hi all,

I am trying to create a seesion variable in a class. When I try to compile it I get the following error.

CS0103: The name 'Session'does not exist in the class or namespace 'DatabaseConnection.DbConnect'

In the class file I try to create the session variable as follows

Session["CompanyName"]="Name";

Anyone have any ideas of my problem?HttpContext.Current.Session
When you use "Session" in a WebForm, you are accessing a property (Page.Session), which returns an HttpSessionState object, which you then index using ["CompanyName"]. If your class is not derived from Page (or several other classes which have a Session property), then your class doesn't have a Session property for you to use. Fortunately you can use the static method HttpContext.Current to get the current HttpContext object, which then gives you access to session state through its Session property.

AutoFed
Thanks for this.

How do I convert a session object to a boolean type or an integer?
You can use, Convert.ToInt32 and Convert.ToBoolean methods. These are the static methods of "Convert" class, which take object type as the parameter. So, you can pass your session variable to these methods to convert to the required type
It depends on what object you assigned to the session variable. If you assigned an integer to the session variable, e.g. Session["MyInt"] = 16, then you just need to cast it back to an int when you read it out, int myInt = (int)Session["myInt"]. If you assigned a string to the sesson variable, e.g. Session["MyInt"] = "16", and you want to convert that to an int, you can use Int32.Parse. You should only use the Convert functions if you don't know what the type of the object is, since there is some extra overhead in determining what the type is before converting it.

AutoFed

Saturday, March 24, 2012

session variable only accessable through page behind class instance?

Are session variables available to any class instance within a project namespace or only for use for the form codebehind class?

I have tried to set a session variable on a code behind class and then retrieve its value in a class instance used by the codebehind class and I get errors. Maybe I'm just not meant to access that way and only codebehind classes (classes that inherit System.Web.UI.Page) can use them?As far as I know session variables are only available in aspx pages.

That does not prevent you from passing value of your session variables to any of your business tier objects.
It's more a question of context.
Within the context of the ASP.NET process, any class can get to the session using HttpContext.Current.Session.
Thanks very much for the help!

Session variable problem

Hi,

Im having trouble with the code below, I think it is because this code is executed in a class and not on an actual form, I am getting the error "Name 'Session' is not declared.

Is there away to fix this error? Is there an problems with setting the user session variable in a class and not on a form?

Private Function PasswordMatch(ByVal UserName, ByVal PassEntered)
Try
Dim intResult As Integer = 0
Dim intUser As Integer
SqlCmdLogon.CommandText = "sp_CheckPassword"
SqlCmdLogon.Parameters("@dotnet.itags.org.Username").Value = UserName
SqlCmdLogon.Parameters("@dotnet.itags.org.Password").Value = PassEntered
SqlCnnShippers.Open()
SqlCmdLogon.ExecuteNonQuery()
intResult = SqlCmdLogon.Parameters("@dotnet.itags.org.Rows").Value
intUser = SqlCmdLogon.Parameters("@dotnet.itags.org.UserID").Value
If intResult = -1 Then

session("UserID") = SqlCmdLogon.Parameters("@dotnet.itags.org.UserID").Value

Return True
Else
Return False
End IfApparently it is not possible, so passed it to a public readonly property instead then called that on the form to set the session variable instead.

Should be Ok.

I'll mark resolved but if anyone sees aproblem ps let me know.
Can i know how we check there is what stored inside the session?
Session("Name") ="Fish"
label1.text = Session("Name")
'Label should display "Fish"
Apparently it is not possible, so passed it to a public readonly property instead then called that on the form to set the session variable instead.

Should be Ok.

I'll mark resolved but if anyone sees aproblem ps let me know.
That's how it was supposed to be done. You can't let your HTTPContexts be mixed into your class logic.

Session variables

Hi,
Basically I see two options:
1- Use application variables, with a Hashtable and the userID is the key.
2- Use a class with a static Hashtable or similar struct. it will be global
to the application therefore will not expire with the section.
Please note that both solutions assume that you are doing this for
registered users, if you allow anonymous users and treat each session as a
different user you have to do something else.
Cheers,
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"Bonj" <anonymous@dotnet.itags.org.discussions.microsoft.com> wrote in message
news:B3D56FFC-CC10-495D-9C62-450DED7D33B2@dotnet.itags.org.microsoft.com...
> I see Session variables time out after 20 minutes (or whatever number of
minutes you define).
> I want to have some variables that won't time out, but they only occupy
very small amounts of data, say 10-20 bytes per user, so I think it won't
too much of a performance impact to store it in the web server's memory.
Would having hash tables as global variables using the SessionID as key work
OK? Global variables and SessionIDs don't time out do they?"Bonj" <anonymous@.discussions.microsoft.com> wrote in message news:B3D56FFC-CC10-495D-9C62-
450DED7D33B2@.microsoft.com...
> I see Session variables time out after 20 minutes (or whatever number of m
inutes you define).
> I want to have some variables that won't time out, but they only occupy very small
amounts of data, say 10-20 bytes per user, so I
think it won't too much of a performance impact to store it in the web serve
r's memory. Would having hash tables as global variables
using the SessionID as key work OK? Global variables and SessionIDs don't ti
me out do they?
It's not the session *variables* that time out, it's the *session* that will
be removed (along with all stored values) after the user has done
nothing (=no new page request) for 20 minutes.
How long do you want to keep this data? Could you store it in
a database?
Hans Kesting
All Session variables expires after 20 (or x minutes you choose) whatever
type they have, also the corresponding SessionID of the expired Session. Use
Application variables to store common variables.
Horatiu Ripa
"Bonj" <anonymous@.discussions.microsoft.com> wrote in message
news:B3D56FFC-CC10-495D-9C62-450DED7D33B2@.microsoft.com...
> I see Session variables time out after 20 minutes (or whatever number of
minutes you define).
> I want to have some variables that won't time out, but they only occupy
very small amounts of data, say 10-20 bytes per user, so I think it won't
too much of a performance impact to store it in the web server's memory.
Would having hash tables as global variables using the SessionID as key work
OK? Global variables and SessionIDs don't time out do they?
You could also look at storing this data in an encrypted cookie. Then you
can set the timeout to whatever you wish with no server overhead.
-mike
MVP
"Bonj" <anonymous@.discussions.microsoft.com> wrote in message
news:B3D56FFC-CC10-495D-9C62-450DED7D33B2@.microsoft.com...
>I see Session variables time out after 20 minutes (or whatever number of
>minutes you define).
> I want to have some variables that won't time out, but they only occupy
> very small amounts of data, say 10-20 bytes per user, so I think it won't
> too much of a performance impact to store it in the web server's memory.
> Would having hash tables as global variables using the SessionID as key
> work OK? Global variables and SessionIDs don't time out do they?

Thursday, March 22, 2012

Session Variables

Working with ASP.NET 1.1 - C#

I have been attempting to locate all of reading and writing of session
variables into a class in its own file. The file contains:
using System;
using System.Collections;
using System.Web;
using System.Web.SessionState;
using System.Xml;
using System.Text;
using Microsoft.Win32;
namespace SessionVariablesClasses
{
public class SessionVariablesClass
{
I am getting the following error message:
c:\inetpub\wwwroot\OB_EEG_WhatIf\SessionVariables. cs(84): The name 'Session'
does not exist in the class or namespace
'SessionVariablesClasses.SessionVariablesClass'

on the following line of code:
try
{
_bnUserHasBeenValidated = Session["UserHasBeenValidated"].ToString();
}
catch
{
_bnUserHasBeenValidated = false;
}You can find the Session Object in System.Web namespace

You could get at the session like:
System.Web.HttpContext.Current.Session["MyVar"] = "Blah";

HTH,
Tony

"Robert E. Flaherty" <Bobf@.TimeVision.Com> wrote in message
news:eTGd%23gjSGHA.4608@.tk2msftngp13.phx.gbl...
> Working with ASP.NET 1.1 - C#
> I have been attempting to locate all of reading and writing of session
> variables into a class in its own file. The file contains:
> using System;
> using System.Collections;
> using System.Web;
> using System.Web.SessionState;
> using System.Xml;
> using System.Text;
> using Microsoft.Win32;
> namespace SessionVariablesClasses
> {
> public class SessionVariablesClass
> {
> I am getting the following error message:
> c:\inetpub\wwwroot\OB_EEG_WhatIf\SessionVariables. cs(84): The name
> 'Session' does not exist in the class or namespace
> 'SessionVariablesClasses.SessionVariablesClass'
> on the following line of code:
> try
> {
> _bnUserHasBeenValidated = Session["UserHasBeenValidated"].ToString();
> }
> catch
> {
> _bnUserHasBeenValidated = false;
> }
When you reference Session within a Page, you are resolving a property of
the page object. When referencing Session within a class other than a page,
you will need to qualify it as follows:

HttpContext.Current.Session["MySessionVariableName"] = "abc";

Also, you really shouldn't be using a try / catch to check for a valid
Session variable. Exceptions are expensive. Instead, try testing your
session variable for null:

if(Session["UserHasBeenValidated"] != null)
{
_bnUserHasBeenValidated = true;
}
else
{
_bnUserHasBeenValidated = false;
}

Hope this helps you out.

--
Andrew Robinson
http://blog.binaryocean.com

"Robert E. Flaherty" <Bobf@.TimeVision.Com> wrote in message
news:eTGd%23gjSGHA.4608@.tk2msftngp13.phx.gbl...
> Working with ASP.NET 1.1 - C#
> I have been attempting to locate all of reading and writing of session
> variables into a class in its own file. The file contains:
> using System;
> using System.Collections;
> using System.Web;
> using System.Web.SessionState;
> using System.Xml;
> using System.Text;
> using Microsoft.Win32;
> namespace SessionVariablesClasses
> {
> public class SessionVariablesClass
> {
> I am getting the following error message:
> c:\inetpub\wwwroot\OB_EEG_WhatIf\SessionVariables. cs(84): The name
> 'Session' does not exist in the class or namespace
> 'SessionVariablesClasses.SessionVariablesClass'
> on the following line of code:
> try
> {
> _bnUserHasBeenValidated = Session["UserHasBeenValidated"].ToString();
> }
> catch
> {
> _bnUserHasBeenValidated = false;
> }
I have a well encapsulated Session object wrapper at my blog:

http://spaces.msn.com/sholliday/ 10/24/2005 entry

it would be a trivial exercise to add a .ClearAll() method to it, since
I have all the objects in a collection member variable.

Robert E. Flaherty wrote:
> Working with ASP.NET 1.1 - C#
> I have been attempting to locate all of reading and writing of session
> variables into a class in its own file. The file contains:
> using System;
> using System.Collections;
> using System.Web;
> using System.Web.SessionState;
> using System.Xml;
> using System.Text;
> using Microsoft.Win32;
> namespace SessionVariablesClasses
> {
> public class SessionVariablesClass
> {
> I am getting the following error message:
> c:\inetpub\wwwroot\OB_EEG_WhatIf\SessionVariables. cs(84): The name 'Session'
> does not exist in the class or namespace
> 'SessionVariablesClasses.SessionVariablesClass'
> on the following line of code:
> try
> {
> _bnUserHasBeenValidated = Session["UserHasBeenValidated"].ToString();
> }
> catch
> {
> _bnUserHasBeenValidated = false;
> }
> Also, you really shouldn't be using a try / catch to check for a valid
> Session variable. Exceptions are expensive.

depends. see http://www.yoda.arachsys.com/csharp/exceptions.html

> Instead, try testing your session
> variable for null:
> if(Session["UserHasBeenValidated"] != null)
> {
> _bnUserHasBeenValidated = true;
> }
> else
> {
> _bnUserHasBeenValidated = false;
> }

but yes, this would be better.

Hans Kesting

Session Variables

Working with ASP.NET 1.1 - C#
I have been attempting to locate all of reading and writing of session
variables into a class in its own file. The file contains:
using System;
using System.Collections;
using System.Web;
using System.Web.SessionState;
using System.Xml;
using System.Text;
using Microsoft.Win32;
namespace SessionVariablesClasses
{
public class SessionVariablesClass
{
I am getting the following error message:
c:\inetpub\wwwroot\OB_EEG_WhatIf\Session
Variables.cs(84): The name 'Session'
does not exist in the class or namespace
'SessionVariablesClasses.SessionVariablesClass'
on the following line of code:
try
{
_bnUserHasBeenValidated = Session["UserHasBeenValidated"].ToString();
}
catch
{
_bnUserHasBeenValidated = false;
}You can find the Session Object in System.Web namespace
You could get at the session like:
System.Web.HttpContext.Current.Session["MyVar"] = "Blah";
HTH,
Tony
"Robert E. Flaherty" <Bobf@.TimeVision.Com> wrote in message
news:eTGd%23gjSGHA.4608@.tk2msftngp13.phx.gbl...
> Working with ASP.NET 1.1 - C#
> I have been attempting to locate all of reading and writing of session
> variables into a class in its own file. The file contains:
> using System;
> using System.Collections;
> using System.Web;
> using System.Web.SessionState;
> using System.Xml;
> using System.Text;
> using Microsoft.Win32;
> namespace SessionVariablesClasses
> {
> public class SessionVariablesClass
> {
> I am getting the following error message:
> c:\inetpub\wwwroot\OB_EEG_WhatIf\Session
Variables.cs(84): The name
> 'Session' does not exist in the class or namespace
> 'SessionVariablesClasses.SessionVariablesClass'
> on the following line of code:
> try
> {
> _bnUserHasBeenValidated = Session["UserHasBeenValidated"].ToString();
> }
> catch
> {
> _bnUserHasBeenValidated = false;
> }
>
When you reference Session within a Page, you are resolving a property of
the page object. When referencing Session within a class other than a page,
you will need to qualify it as follows:
HttpContext.Current.Session["MySessionVariableName"] = "abc";
Also, you really shouldn't be using a try / catch to check for a valid
Session variable. Exceptions are expensive. Instead, try testing your
session variable for null:
if(Session["UserHasBeenValidated"] != null)
{
_bnUserHasBeenValidated = true;
}
else
{
_bnUserHasBeenValidated = false;
}
Hope this helps you out.
Andrew Robinson
http://blog.binaryocean.com
"Robert E. Flaherty" <Bobf@.TimeVision.Com> wrote in message
news:eTGd%23gjSGHA.4608@.tk2msftngp13.phx.gbl...
> Working with ASP.NET 1.1 - C#
> I have been attempting to locate all of reading and writing of session
> variables into a class in its own file. The file contains:
> using System;
> using System.Collections;
> using System.Web;
> using System.Web.SessionState;
> using System.Xml;
> using System.Text;
> using Microsoft.Win32;
> namespace SessionVariablesClasses
> {
> public class SessionVariablesClass
> {
> I am getting the following error message:
> c:\inetpub\wwwroot\OB_EEG_WhatIf\Session
Variables.cs(84): The name
> 'Session' does not exist in the class or namespace
> 'SessionVariablesClasses.SessionVariablesClass'
> on the following line of code:
> try
> {
> _bnUserHasBeenValidated = Session["UserHasBeenValidated"].ToString();
> }
> catch
> {
> _bnUserHasBeenValidated = false;
> }
>
I have a well encapsulated Session object wrapper at my blog:
http://spaces.msn.com/sholliday/ 10/24/2005 entry
it would be a trivial exercise to add a .ClearAll() method to it, since
I have all the objects in a collection member variable.
Robert E. Flaherty wrote:
> Working with ASP.NET 1.1 - C#
> I have been attempting to locate all of reading and writing of session
> variables into a class in its own file. The file contains:
> using System;
> using System.Collections;
> using System.Web;
> using System.Web.SessionState;
> using System.Xml;
> using System.Text;
> using Microsoft.Win32;
> namespace SessionVariablesClasses
> {
> public class SessionVariablesClass
> {
> I am getting the following error message:
> c:\inetpub\wwwroot\OB_EEG_WhatIf\Session
Variables.cs(84): The name 'Sessio
n'
> does not exist in the class or namespace
> 'SessionVariablesClasses.SessionVariablesClass'
> on the following line of code:
> try
> {
> _bnUserHasBeenValidated = Session["UserHasBeenValidated"].ToString();
> }
> catch
> {
> _bnUserHasBeenValidated = false;
> }
> Also, you really shouldn't be using a try / catch to check for a valid
> Session variable. Exceptions are expensive.
depends. see http://www.yoda.arachsys.com/csharp/exceptions.html

> Instead, try testing your session
> variable for null:
> if(Session["UserHasBeenValidated"] != null)
> {
> _bnUserHasBeenValidated = true;
> }
> else
> {
> _bnUserHasBeenValidated = false;
> }
>
but yes, this would be better.
Hans Kesting

Tuesday, March 13, 2012

session variables and global.aspx.cs - where do i put them?

if i put an array in

public class Global : System.Web.HttpApplication
{

//e.g.

public static int [] count=new int[5]

}

and then refer to it in my page .cs files as Global.count[0]... [4] will
every session in my application be accessing the same count array or will
they each have their own?

I guess i am really saying is, is there a difference between the above and
:

protected void Session_Start(Object sender, EventArgs e)
{

Sesson["count"]=new int[5]

}

It strikes me that if they are the same then the first option is better
because i don't have to keep casting from object to int everytime i access
the array in web pages.Hi Tony,

You should think of the Application scope the same way you would think of Environment variables.
They are not only global, but they are also readable and writable to all users of the system at the same
time.

Session is better to use if the values are not final or need to be changed per user.
A session is created for each user making a request.

____________________________________
Wil Moore III, MCP | Integrations Specialist | Senior Consultant
Business | Personal

Session Variables and Static Variables

I have found it very easy to have a Helper class that has static
members which access Session Variables. For example:

public class HelperClass
{
public static doCustomer CurrentCustomer
{
get
{
if(HttpContext.Current.Session["Current_Customer"] == null)
CurrentCustomer = new doCustomer();

return (doCustomer)
HttpContext.Current.Session["Current_Customer"];
}
set
{
HttpContext.Current.Session["Current_Customer"] = value;
}
}
}

Is this thread safe? Will each user of the Application still have his
own instance of doCustomer, even though it is accessed via an
Application Wide static member? What is the best practice regarding
Thread Safety, Session Management and Static Members?

ThanksAnybody?

Session Variables arent retrieved during Postback

Hi I have a web page, which has a login corner. When someone logs in and clicks the "Go" button, a class called Security gathers the users details and posts it back to the same page, under a session variable called "User"

Private Sub cmdLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLogin.Click
'Login into the system
Dim l As New Security()
Dim Outcome As PPPL.Security.LoginOutcome

Outcome = l.DoLogin(Login.Text, Password.Text)
Select Case Outcome
Case Security.LoginOutcome.lgBADLOGIN
Case Security.LoginOutcome.lgBADPASSWORD
Case Security.LoginOutcome.lgINACTIVE
Case Security.LoginOutcome.lgLOCKED
Case Security.LoginOutcome.lgLOGGEDIN
Session("User") = l
If l.IsAdmin Then
EnableFixtureEntry(True)
Else
EnableFixtureEntry(False)
End If
Label3.Text = "You are logged in as " & l.User
End Select

End Sub


When the page postsback to itself, I need that session variable saved, so that I can access it. Trouble is when I try to retrieve it, I get a null value.

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here

If IsPostBack Then
'Determine if the user is logged in.
Dim l As New Security()
l = Session("User")

If Not l Is Nothing Then
pnlPredictions.Controls.Add(New LiteralControl(l.User))
End If
End If

End Sub


Problem is that when it gets to evaluating whether l Is Nothing, it always returns true. Please can someone help me?Well, I always use
Session.Add("User",1)

1 being the value or whatever you assign to it.

Put a breakpoint on your assignment. After that line executes, type
? Session("User") in your Command Window. If you get a null or nothing, then it isn't setting in the first place.
Thanks for the response.

I have done that as well, and I get the same result.

When I do a response.write on the session("User") within the Button.Click Event, it does work.

The session variable seems to reset when the Postback to the page occurs.
Could you post the entire code of the page, aspx.vb along with the aspx ?

I also wonder if your class is not properly serializing. If it doesn't serialize properly it won't be stored in viewstate. However, ASP.NET compiler would most likely error when you attempt putting Session("user") = l.

This is what I would do, use Session.add("User","LOGGEDIN")
in your login code, then in the postback, put
dim st as string = Session.Item("User")

Put a breakpoint on the line right after you grab the Session.Item("user"), and see if st = "LOGGEDIN". If it does, we know its not some weird web configuration problem.

We would then ascertain your class does not properly serialize to a string (XML).
Strange things happen when trying to reteieve complex objects from viewstate or sessions whout a proper cast. A datagrid for example must be properly casted before it can be used...

try

dim s as new Security()

s = CType(Session("User"), Security)