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;
}
Related
I have written a console app to fetch data from Database and update Active Directory. It is not able to replace null values already present in active directory, throwing "Object Reference is not set to an instance.."
I am handling null values fetched from DB and replacing them with "-". So I'm not passing any null value to AD.
if (string.IsNullOrEmpty(lastName)) { lastName = "-"; }
entry.Properties[ADProperties.LASTNAME].Value = lastName;
I want to update Active Directory thoroughly (even if there is any null present in AD).
The error was in trying to save null or invalid value in the Manager property.
To resolve this issue, I'm checking whether the value is valid or not.
In case, it is coming null or invalid from DB, I'm using .Clear() function.
Below is the sample code:
try
{
if (entry.Properties[propertyName].Value == null)
{
if (dbValue != "")
{
//Value Null in AD, but Not Null in DB. AD value to be updated with DB value
//Write Log
entry.Properties[propertyName].Value = dbValue;
return 1;
}
}
else
{
//Value Not Null in AD
if (!dbValue.Equals(entry.Properties[propertyName].Value))
{
// Value Not Null in AD And Not Matching With DB Value
//Write Log
if (dbValue != "")
{
//Value Present in AD & DB Both, but not same. AD Value to be updated with DB Value
entry.Properties[propertyName].Value = dbValue;
}
else
{
//Value Present in AD but blank in DB. AD Value to be cleared.
entry.Properties[propertyName].Clear();
}
return 1;
}
}
return 0;
}
catch (Exception ex)
{
//Write Log
return 0;
}
I have a Web Forms application that does not have a login page. Technically a user can access any page directly. However, I need to be able to identify who the logged-in user is on each page. I don't want to add code to each page. I would rather set a unique session variable at the start of the session. For this I added into my Global.asax.cs the following:
protected void Session_Start(object sender, EventArgs e)
{
if (Session["LoggedInUser"] == null)
{
string networkId = HttpContext.Current.User.Identity.Name;
using (UnitOfWork unit = new UnitOfWork())
{
if (networkId.IndexOf("HLM\\") > -1) { networkId = networkId.Substring(4, networkId.Length - 4); }
loggedInUser = unit.PersonRepository.GetByNetworkID(networkId);
Session["LoggedInUser"] = loggedInUser;
}
}
else
{
loggedInUser = (Person)Session["LoggedInUser"];
}
}
I now see that it sets the loggedInUser to whatever user last created a session. Meaning, if Mike goes to the site he will see data that represents him as the loggedInUser. However, if Kate goes to the site after him, Mike will now see Kate's data. Basically, the last one in overwrites everyone's settings and Session_Start is overwriting the value for loggedInUser for all active Sessions.
Based on this link: https://books.google.com/books?id=nQkyi4i0te0C&pg=PA202&lpg=PA202&dq=C%23+set+unique+session+variable+in+global.asax&source=bl&ots=GV9nlEUzE5&sig=E4TT3NDbjp1GwEehgU3pLXKdvr0&hl=en&sa=X&ved=0ahUKEwiU9f322tvSAhVF7yYKHYaXCtwQ6AEITzAI#v=onepage&q=C%23%20set%20unique%20session%20variable%20in%20global.asax&f=false
It reads that I should be able to set unique session variables for each new session but my results don't show that.
Am I misunderstanding how this works? I need to set a unique session value at the beginning of each session for each user.
I found the issue. The Session_Start is doing what is supposed to at a unique session level. The way I was referencing the session value was all wrong. Instead of accessing the session value I was actually doing:
Person loggedInUser = Global.loggedInUser;
Which makes sense that it was returning the latest user to start a session.
My session is not getting destroyed. This is how I set it up in Login.aspx.cs:
Session["User"] = UserName.Text; // Set the session called User.
Link on the MasterPage:
<img src="images/login.png"><span runat="server" id="authspan">Login</span>
The text in the link changes depending on whether the user has session or not:
if (Session["User"] != null)
{
authspan.InnerHtml = "Logout";
}
else
{
authspan.InnerHtml = "Login";
}
This link redirects to Login.aspx file in which on PageLoad I tell the code to close the session. In theory, this should work, right?
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
Response.Redirect("Default.aspx"); // Redirect user.
Session["User"] = null;
Session.Remove("User");
}
else
{
// run code that logs the user in, and sets up the session.
}
}
How can I end it for the logged in user correctly?
You must first clear session and then redirect.
Session["User"] = null;
Session.Remove("User");
Response.Redirect("Default.aspx"); // Redirect user.
Also note that, it is safer to remove session id on client side too:
var sessionCookie = new HttpCookie("ASP.NET_SessionId");
sessionCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(sessionCookie);
You should use:
Session.Clear();
Response.Redirect("Default.aspx");
To remove the value from session in different ways
//Set the session variable
Session["User"]=Value;
//Destroy the session variable
Session.Remove("User");
Session["User"]=null;
// Abandon will destroy the session completely, meaning that you need to begin a new session before you can store any more values in the session for that user
Session.Abandon();
//Clearing the session will not unset the session, it still exists with the same ID for the user but with the values simply cleared.
Session.Clear();
Call Session.Abandon(); (and I must write at least 30 chars)
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");
}
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
}