Determine if ASP.NET Sessions are enabled - c#

What is the best way to do a boolean test in C# to determine if ASP.NET sessions are enabled? I don't want to use a try-catch block and Sessions != null throws an Exception.
Regards.

You will not get an exception if you use HttpContext.Current:
if(HttpContext.Current.Session != null)
{
// Session!
}

You want to interrogate the EnableSessionState property in Web.config.

Here is how you can determine if session state is enabled:
PagesSection pagesSection = ConfigurationManager.GetSection("system.web/pages") as PagesSection;
if ((null != pagesSection) && (pagesSection.EnableSessionState == PagesEnableSessionState.True))
// Session state is enabled
else
// Session state is disabled (or readonly)

You can use something like this(Pseudo code)
XmlDocument document = new XmlDocument();
document.Load("Web.Config");
XmlNode pagesenableSessionState = document.SelectSingleNode("//Settings[#Name = 'pages']/Setting[#key='enableSessionState']");
if(pagesenableSessionState .Attributes["value"].Value =="true)
{
//Sessions are enabled
}
else
{
//Sessions are not enabled
}

Related

Session is set or not in ASP.NET

How to check that any of a Session is set or not in ASP.NET C# as we do in PHP
if(session_id() == '')
{
// session has NOT been started
session_start();
}
else
{
// session has been started
}
And in ASP.Net C#
if (Session["userRole"].ToString() == "2")
GridView3.Columns[7].Visible= true;
else{
GridView3.Columns[7].Visible= false;
The above code only checks the session named userRole.
What is the alternate way of the above PHP code to C#?
In order to check if any session key is set try:
if(Session.Keys.Count > 0)
{
Console.WriteLine("Session is filled");
}
else
{
Console.WriteLine("Session is empty");
}
Every item is a 'key' in the Session object. So when the count equals zero, there are no session keys set. Is this what you wanted?
To check if the session key exists in Session collection you have to compare it with null
if (Session["userRole"] != null && Session["userRole"].ToString() == "2")
Edit based on comments, Session is property of Page class and will always exists and will not be null.
This property provides information about the current request's
session. A Session object is maintained for each user that requests a
page or document from an ASP.NET application. Variables stored in the
Session object are not discarded when the user moves from page to page
in the application; instead, these variables persist as long as the
user is accessing pages in your application, MSDN.
Another Solution use try catch
try
{
if (Session["userRole"].ToString() == "2")
GridView3.Columns[7].Visible = true;
else
GridView3.Columns[7].Visible = false;
}
catch (Exception)
{
GridView3.Columns[7].Visible = false;
}

How to know if a session has been set [duplicate]

This question already has answers here:
What is the best way to determine a session variable is null or empty in C#?
(12 answers)
Closed 10 years ago.
In php i used to use
session_start();
if(isset(SESSION["user"]))
{
//session is set
}
els{
// there is no session
}
but do i do that in asp.net? I mean. What code can tells wheather a session is set or not
ex:
asp.net c#
//login.aspx
SESSION["USER"];
//user_profile.aspx
if(SESSION["USER"])// how do i validate that??
{
}
SESSION["USER"]; //this should throw an error since it's not setting a value and not a method.
You can test your session values like this:
if (Session["USER"] != null)
{
//do something interesting
}
If you want to check for the existance of a session variable this will be fine:
if(Session["USER"] != null)
{
//If you get here a session variable "USER" exists...
}
Though it is possible to disable session state in an asp.net application it is very rare to see that.
From php side, cince isset function
Determine if a variable is set and is not NULL.
Just check if this session null or not like:
if(Session["USER"] != null)
{
// Do something
}

Check if user is logged in using sessions

I want to check if a user is logged in and if they are, deny them access to the registration and login pages. When a user logs in I'm setting these session variables:
HttpContext.Current.Session["LoggedIn"] = true;
HttpContext.Current.Session["FullName"] = (string)Reader["FirstName"] + " " + (string)Reader["LastName"];
Response.Redirect("Default.aspx");
And I'm checking them at the top of the register and login pages like so:
if ((bool)HttpContext.Current.Session["LoggedIn"])
{
Response.Redirect("Default.aspx");
}
However, when I try to go to the page while not logged in this exception gets thrown:
Object reference not set to an instance of an object.
I'm assuming it's ebcause the LoggedIn key doesn't exist because I only create it after a successful login.
So, how can I check if the LoggedIn key exists and if it doesn't, redirect the user to Default.aspx?
Thanks!
I think you can do a simple null check on this like....
if (HttpContext.Current.Session["LoggedIn"] != null)
{
// once inside this loop
// you can now read the value from Session["LoggedIn"]
Response.Redirect("Default.aspx");
}
you need to make shure that the object is not null before unboxing it
if(HttpContext.Current.Session["LoggedIn"]!=null)
{
if ((bool)HttpContext.Current.Session["LoggedIn"])
{
Response.Redirect("Default.aspx");
}
}
Why to avoid the default webforms authentication model altogether? Simply use web.config to define a restricted area, set all the settings correctly and you won't have to perform checks like this for every page.
But, if you want to reinvent the wheel....
You check for something that probably doesn't exist yet. You must modify your if-statement like this:
bool isLoggedIn = (HttpContext.Current.Session["LoggedIn"] == null ? false : (bool)HttpContenxt.Current.Session["LoggedIn"];
if (isLoggedIn)
{
Response.Redirect("Default.aspx");
}

Access application setting by name

In application settings I have a group of settings called "Name01", "Name02" and so on.
I have a list of strings "Name01", "Name16", "NameWhatever"..
How to check if there is a setting called "NameXX" in Settings.Default ?
You could test it like this:
var x = Properties.Settings.Default.Properties["NameXX"];
if(x != null) {
//....
}

Useing Registry value to launch a application? whats wrong with it? .net 2.0 ONLY please

I am trying to write a little piece of code that retrieves the install path of an application, and uses it + the applications name to start the application on click. This is what I have so far but I keep getting the error "Object reference not set to an instance of an object". This is the code I'm trying to use, whats wrong?
RegistryKey Copen = Registry.LocalMachine.OpenSubKey(#"Software\ComodoGroup\CDI\1\");
Copen.GetValue("InstallProductPath");
System.Diagnostics.Process.Start(Copen + "cfp.exe");
You're not actually storing the value you're retrieving. Try this:
RegistryKey Copen = Registry.LocalMachine.OpenSubKey(#"Software\ComodoGroup\CDI\1\", RegistryKeyPermissionCheck.ReadSubTree);
if(Copen != null)
{
object o = Copen.GetValue("InstallProductPath");
if(o != null)
{
System.Diagnostics.Process.Start(IO.Path.Combine(o.ToString(), "cfp.exe"));
}
else
MessageBox.Show("Value not found");
}
else
MessageBox.Show("Failed to open key");
Edited: to also check for NULL as Martin mentioned
Your call to Registry.LocalMachine.OpenSubKey or GetValue might fail and then it returns null. Then when they are used you will get the null reference exception.
Try to see if any of the values returned by these methods are null. Something like this:
RegistryKey key = Registry.LocalMachine.OpenSubKey(#"Software\ComodoGroup\CDI\1");
if (key != null)
{
object = installProductPath = key.GetValue("InstallProductPath");
// You could also supply a default value like this:
// installProductPath = key.GetValue("InstallProductPath", #"C:\The\Default\Path");
if (installProductPath != null)
{
System.Diagnostics.Process.Start(Path.Combine(installProductPath.ToString() + "cfp.exe");
}
}
Edit
Guess you just wrote this line wrong, but you are not supplying the value, but the RegistryKey value:
System.Diagnostics.Process.Start(Copen + "cfp.exe");

Categories

Resources