How do I check whether there is an ongoing session I .NET 7.0? - asp.net

I am trying to check whether there is an ongoing session. To achieve this:
I set the "Id" to the relevant person's ID using:
HttpContext.Session.SetString("Id", user.Id.ToString())
I tried using the following code block to check whether there is an ongoing session:
if ( String.IsNullOrEmpty(HttpContext.Session.GetString("Id")))){
codes if condition is true.
}
However, the code block keeps executing regardless the session "Id" has been set or not. How do I fix this ?
I am using .NET 7 on a windows platform.

You can use the Session property of the HttpContext class in .NET 7.0 to check whether there is an ongoing session. You can store the session identifier in a variable when the session starts and check if the variable is set in subsequent requests to determine if the session is ongoing.
Here is an example:
// Setting the session identifier when the session starts
if (HttpContext.Session.GetInt32("SessionId") == null)
{
HttpContext.Session.SetInt32("SessionId", new Random().Next());
}
// Checking if the session is ongoing in subsequent requests
if (HttpContext.Session.GetInt32("SessionId") != null)
{
// code to execute if the session is ongoing
}
else
{
// code to execute if the session is not ongoing
}
and you can modify your code as follows to fix the issue:
if (!HttpContext.Session.TryGetValue("Id", out byte[] value) ||
String.IsNullOrEmpty(Encoding.UTF8.GetString(value)))
{
// code if session "Id" is not set or has an empty value
}
else
{
// code if session "Id" is set and has a value
}

Related

How to set the bookmarking (cmi.location) for SCORM 1.2?

I tried to bookmarking for flash SCORM 1.2 packages. I'm properly capturing the last visited data(cmi.loation, suspend data), but when I'm trying to reset the data for next launch, SCO is not relocating, it is starting from beginning.
And I set the hard coded values in LMSInitilization() function in javascript.
I used bellow code for setting the location variable to SCO.
// cmi data model storing object
var cmiobj = new Object();
function LMSInitialize(dummyString) {
// already initialized or already finished
if ((flagInitialized) || (flagFinished)) { return "false"; }
// set initialization flag
flagInitialized = true;
this.cmiobj["cmi.core.lesson_location"]="6";
this.cmiobj['cmi.core.lesson_status']='incomplete';
this.cmiobj['cmi.core.session_time']='00:00:50';
this.cmiobj['cmi.suspend_data']='FA1Enon ... ";
// return success value
return "true";
}
Hope you help.
You need to set cmi.core.exit to "suspend" too - otherwise it will not supply any of the old data for you to continue with next time.

Retain the session value when browser is opened for the second time

First time login to the asp.net application,stored some session value
Eg: Session["Test"]="Saving Sesison";
Logout the application
When opened the browser for the second time,need to retain the same session value.
Eg: Session["Test"]="Saving Sesison";
How can i do that,can anyone help me with some solution to proceed further please.
if (!Page.IsPostBack)
{
if (Session["Test"] == null)
{
Binding data to repeater control(with out filter)
}
else
{
//Get Session value (To maintain session value across the browser)
var cookieSession = Request.Cookies["Test"]; //While opening the browser for the 2nd time,this line is getting null for all the browsers,but session is getting value for firefox & Chrome not for IE { Session["Test"] }
if (cookieSession != null &&!String.IsNullOrEmpty(cookieSession.Value))
{
Session["Test"] = cookieSession.Value;
}
Binding data to repeater control(with filter using session value)
}
}
//On Drop down selection.
protected void Dropdown_SelectedIndexChanged(object sender, EventArgs e)
{
Binding data to repeater control(based on the dropdown selected value)
Session["Test"] = Dropdown.SelectedItem.Text.ToString(); //To maintain the Dropdown selection all over the app
// Set it
if (Session["Test"] == null)
{
Session["Test"] = Guid.NewGuid().ToString();
var cookie = new HttpCookie("Test", (string)Session["Test"]);
Response.Cookies.Add(cookie);
}
}
ASP.NET Session scope is for only particular session only. So its not possible to have that kind of functionality.
But you can use Cache in same way and it will be there until you make it null or time period exceeds. But beware of fact that it will be there for every browser. So either you need to use different key(Unique key) not like 'test'
You have a few options. Though sessions should be sticky between a browser being re-launched assuming it's not in private/incognito mode. If you're finding the session is timing out too quickly you can extend it in Web.config
<system.web>
<sessionState timeout="10080" mode="InProc" />
</system.web>
Where timeout is in minutes. Note: If you're are debugging stopping and starting the debugger will reset your sessions. So will any kind of re-deployment of the application on IIS. If this is an issue for you, you should check out using something like the SQL session state provider: http://msdn.microsoft.com/en-us/library/vstudio/h6bb9cz9(v=vs.100).aspx
Another method of dealing with this is to store some kind of token in a cookie (again, only works if the browser is not in incognito/private mode, and the user data hasn't been flushed).
// Set it
if (Session["Test"] == null)
{
Session["Test"] = Guid.NewGuid().ToString();
var cookie = new HttpCookie("Test", (string)Session["Test"]);
Response.Cookies.Add(cookie);
}
// Get it
var cookieSession = Request.Cookies["Test"];
if (cookieSession != null && !String.IsNullOrEmpty(cookieSession.Value))
{
Session["Test"] = cookieSession.Value;
}
As a note using the SQL session state provider while is one of the more persistent storages there can be some serious overhead requirements. It's easy to rack up a couple of gigs worth of sessions that are being tracked.
In my experience a combination of cookies and the session provider seem to work best if you need to be very certain that some things are sticking to a users experience on the site.
Edit
So the issue with your drop down selection saver is it's always false and should never set the cookie.
protected void Dropdown_SelectedIndexChanged(object sender, EventArgs e)
{
//Binding data to repeater control(based on the dropdown selected value)
// add to Session
Session["Test"] = Dropdown.SelectedItem.Text.ToString();
// Add Cookie
var cookie = new HttpCookie("Test", (string)Session["Test"]);
Response.Cookies.Add(cookie);
}
Now to get your data back out, put this code in the actions/controllers to run BEFORE you try to access Session["Test"]
var cookieSession = Request.Cookies["Test"];
if (cookieSession != null && !String.IsNullOrEmpty(cookieSession.Value))
{
Session["Test"] = cookieSession.Value; // Should contain the selected text from the drop down
}

Do cookies have the equivalent of a primary key?

Coming from a non-web background I'm struggling with cookie uniqueness. When I read and write to a cookie named CustomerCode I find multiple cookies with the same name in my cookie collection(s). How can this be avoided?
Database rows use a primary key to ensure uniqueness. Is there an equivalent for cookies? I'm using this "Reusable Cookie Container" code to simplify writing to a cookie:
Master.Cookies.CustomerCode = SessionWrapper.CustomerCode;
Then in my SessionWrapper I restore session variables from the cookie(s)
public static void InitiateSessionVariablesFromCookies(IAppCookies appCookies) {
if (SessionWrapper.CustomerCode == null && appCookies.CustomerCode != null) {
SessionWrapper.CustomerCode = appCookies.CustomerCode;
}...
The cookie collection contains CustomerCode multiple times so the wrong value is being passed to the session variable. If this question is difficult to answer without seeing all of my code please describe the proper / best way to set cookies and then read them back into session variables (or include a link to help me out).
Thanks in advance.
If you have different expiration date/times you can get "duplicates".
HttpCookie Temp = new HttpCookie("MyName", "123");
Temp.Expires = DateTime.Now.AddMinutes(5);
Response.Cookies.Add(Temp);
This code will create a new cookie each time it runs with the same name and value.

Newly Created Session doesn't retain session contents

The system I am working on does not use standard ASP.NET Auth/ Membership facilities for logging users in/ out. Therefore after logging the user in I want to issue a new Session ID to the user in order to prevent Session trapping/ Hijacking. The problem i have is that although I have been able to successfully create a new session with a new ID and copy the various components to the newly created session eg. session["value"]. By the end of the code excerpt below the newly created session is the current HTTPContext's session, and has the session values that were copied accross. However after performing a Response.Redirect the new session is in action, but none of the session["values"] have persisted across the two requests. As you can see from the code below i've tried adding the values to a number of collections to avail.
Any help would be amazing!! Thanks in advance
bool IsAdded = false;
bool IsRedirect = false;
HttpSessionState state = HttpContext.Current.Session;
SessionIDManager manager = new SessionIDManager();
HttpStaticObjectsCollection staticObjects = SessionStateUtility.GetSessionStaticObjects(HttpContext.Current);
SessionStateItemCollection items = new SessionStateItemCollection();
foreach (string item in HttpContext.Current.Session.Contents)
{
var a = HttpContext.Current.Session.Contents[item];
items[item] = a;
}
HttpSessionStateContainer newSession = new HttpSessionStateContainer(
manager.CreateSessionID(HttpContext.Current),
items,
staticObjects,
state.Timeout,
true,
state.CookieMode,
state.Mode,
state.IsReadOnly);
foreach (string item in HttpContext.Current.Session.Contents)
{
var a = HttpContext.Current.Session.Contents[item];
newSession.Add(item,a);
}
SessionStateUtility.RemoveHttpSessionStateFromContext(HttpContext.Current);
SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, newSession);
manager.RemoveSessionID(HttpContext.Current);
manager.SaveSessionID(HttpContext.Current, newSession.SessionID, out IsRedirect, out IsAdded);
return newSession.SessionID;
Maybe I'm missing something here but won't this work:
Session["mysession"] = mySessionObject;
Basically it appears it's not possible since you can only add session variables once there has been one round trip to the client to create the corresponding session cookie. Therefore I had to create the new new session (with new ID) so that by the time I came to adding session variables, the client cookie had the appropriate session id: annoying since this in reality is issuing the new session ID before the user is authenticated.
Interestingly, it seems a little strange that issuing a new Session ID is exactly what the standard asp.net authentication/ membership functionality does but is able to maintain session variables, and yet doing it manually it doesn't....are there some methods for this that are not being exposed to us mere developers maybe....

Cannot retrieve Session value

I've written a simple code to keep a USerID with the help of session. However I can't get Session value although it's not null. I've done exactly the way microsoft official tutorial says. Here's the code:
The code on the Default.aspx
string regCode = loginBase.getRegCodePerUser(txtLogin.Text);
Session["regCode"] = regCode;
//lblInfo.text=(string)Session["regCode"];When I check it shows the right string.It's OK
Response.Redirect("Selection.aspx");
I do not directly go to that page.I first go to Selection.aspx, then UpdateStages.
And this is the code on the other page(UpdateStages.apsx):
if ((string)Session["connSTR"] == null && (string)Session["user"] == null)
{
Response.Redirect("Default.aspx");
}
else if ((string)Session["regCode"]!=null)
{
regCode=(string)Session["regCode"];
lblInfo.Text = regCode;//Show nothing. Empty.
}
It might very well be that when you set the session variable:
Session["regCode"] = loginBase.getRegCodePerUser(txtLogin.Text);
That the username is not available yet and that is why it's returning an empty string, and I would assume that you are executing this code: lblStatus.Text =loginBase.getRegCodePerUser(txtLogin.Text); on a different page/after the user has logged in and that is why you get the value in the label when you assign it directly.
Put a breakpoint on where you set the Session variable and see if the value is being set.
Otherwise your session settings could be incorrect in your web.config which causes the session values to be cleared before you get to your second page where you are accessing it.

Resources