ASP.net: How to list a WebApplication All users Session - asp.net

I want to know my website memory usage,first i want to know Session detail of all users,this will help me decide whether to change sessionState Mode to "SqlServer" or "StateServer".
How can i do?
Thanks

For website memory usage, I would look at perfmon. If I really wanted to count how much memory I was using in each user session, I would do that count when adding not when abandoning the session. This could be tricky if you've got Session["foo"]=bar all over the place, it needs to be wrapped up somehow.
If you do change to out of process session state, you will need to test everything that touches the session. Your session variables are crossing process boundaries, they need to be serializable and there are definitely some things that don't work.

I am not sure if this will help you solve the problem but you can try this piece of code in Session_End event... Assuming that this event is fired from your logout process..
This is the last of the events where Session Variable is available.
protected void Session_End(object sender, EventArgs e)
{
string strMessage = string.Empty;
for (int i = 0; i < this.Session.Count; i++)
{
strMessage += string.Format("Session of {0} Value is {1}", i.ToString(), this.Session[i].ToString());
strMessage += "/n";
}
}
this.Session.Count should give you the number of sessions in the server for the application. This solution may hold good only if your application is hosted in single web server and not on a web server farm. I am ignorant of how sessions are handled in a web server farm.

Related

C# code to increment by 1 an item in Application state

How to write the C# code to increment by 1 an item in Application state named “total” in ASP.net?
In order to modify any Application variables, you need to lock them before modifying it to ensure no inadvertent changes between parallel requests happen.
An example
Application.Lock();
var userCount = Convert.ToInt32(Application["OnlineUserCount"]);
Application["OnlineUserCount"] = ++userCount;
Application.UnLock();
Application.Lock ensures that only one thread or request has access to the variables and other requests wait in queue. You modify the values as per the need and Application.Unlock to release your lock so other requests can work on Application variables.
Please note that there may be a performance hit, if you depend on this!!
Note: A page does not need to lock the application object to edit the
application collection. If one page tries to edit the application
collection without locking and a second page also tries to edit the
collection, no error is sent by IIS and the Application object ends up
in an inconsistent state.
Better use a
static variable
and
Interlocked.Increment
like this:
private static int total= 0;
public static void Increment()
{
Interlocked.Increment(ref total);
}

Why does my ASP.NET keep-alive logic not work?

In order to ensure that my session always stays on, I created a simple stayalive.aspx page. The header of the page contains metadata to refresh the page every 5 minutes.
In my page-load logic, I simply set a value into session.
protected void Page_Load(object sender, EventArgs e) {
System.Web.HttpContext.Current.Session["Alive"] = 1;
}
My understanding is that as long as you keep putting a value in the session, the session will continue to stay alive. However, this does not seem to be working. I still get a session timeout in about 30 minutes.
I am wondering if anyone has any insight on why is not working.
Note that the sessionstate as well as forms authentication timeout values in web.config are set to 300 (5 hours).
One thought I had was, instead of setting the same value on the session, I set a different value each time:
System.Web.HttpContext.Current.Session["Alive"] = DateTime.Now;
Do you think this would help?
Adding a value in to the session is not required to session alive. If you keep on refreshing the aspx page, session should automatically extend.

How to kill/abandon ALL asp.net sessions on server

If I need all the sessions, of all users on a website to reinitialize themselves, or perhaps all of them to go abandoned so that they will re-init themselves, how to go about this besides restarting the www service?
Many thanks!
You can't really do that using out of the box code.
One way I can think of is storing all Sessions in global context then iterate over this collection: add to the collection in Session_Start and remove in Session_End.
For example:
void Session_Start()
{
if (HttpContext.Current.Cache["Sessions"] == null)
HttpContext.Current.Cache["Sessions"] = new List<HttpSessionState>();
(HttpContext.Current.Cache["Sessions"] as List<HttpSessionState>).Add(HttpContext.Current.Session);
}
void Session_End()
{
if (HttpContext.Current.Cache["Sessions"] != null)
(HttpContext.Current.Cache["Sessions"] as List<HttpSessionState>).Remove(HttpContext.Current.Session);
}
I found a sort of a solution to this - rather than restarting the WWW service to achieve the reset of all sesssions result, you can just reycle the application poll from withing IIS Manager. Just faster, and does what i wanted it to do.
Sorry if this sounds trivial to some :)

How does one discard a session variable while closing Web Page?

We are following a procedure in our work while developing a web page, is to bind page to one or more session variables, these session variables are used only for that page, to hold current processing objects, so while closing page no need for them.
How could I discard these session variables while closing page?
Any suggestions regarding that technique or how to solve that problem?
There is no server-side event that is raised when a page is left/closed. Also the Session_End event (mentioned in other answers) is not called when a page is left, since the user might navigate to other pages of the same web application (and therefore the session will continue to exist).
I can think of 3 possible ways to solve (or work around) this issue:
1 - use ViewState to store data with page-scope. This is what ViewState is made for, and unless you have a lot of data, it should not be a problem. If you have a lot of data, remember, that it will be serialized/deserialized and sent to the client/back to the server for every request (which may result in large requests and therefore bad performance).
2 - instead of putting the data into the session, put it into the Cache (with a low sliding expiration timeout). On your page, you can access your data in the same way as from the session, i.e. data = Cache["data"], but you have to be prepared that the data was removed from the Cache (you have to re-load it again from DB for example), if the time between two requests was bigger than the expiration time.
3 - use the client-side (javascript) onUnload event, and trigger some action (e.g. a ajax callback) to remove the data from the session. But I think the onUnload event is not reliable (it will not be fired in any case, e.g. when the browser is terminated by a crash or with the task manager, or if javascript is disabled).
If you use variables for only that page, store them in viewstate. ViewState is suitable for page scoped variables.
If you are using ASP.NET sessions (which you probably are), you can add a global.asax file to your soluting. In there this event-delegate is to be found (if not, create it):
protected void Session_End(object sender, EventArgs e)
{
}
.. In here you can clear your session collection.
protected void Session_End(object sender, EventArgs e)
{
Session.Clear();
}
This will be fired when the session expires or when a user clicks logout :)

Limiting number of users accessing asp.net website

What is the best way to limit the number of (concurrent) users accessing a web application that any one can introduce for selling website/application to client and how to increase the number of users accessing it remotely?
If you use the in-process session state management, you can use the HttpApplicationState class, by introducing the Global.asax file and putting something like this in the code behind:
void Application_Start(object sender, EventArgs e)
{
Application["ActiveSessions"] = 0;
}
void Session_Start(object sender, EventArgs e)
{
try
{
Application.Lock();
int activeSessions = (int) Application["ActiveSessions"] + 1;
int allowedSessions = 10; // retrieve the threshold here instead
Application["ActiveSessions"] = activeSessions;
if (activeSessions > allowedSessions)
System.Web.HttpContext.Current.Response.Redirect("~/UserLimitReached.aspx", false);
}
finally
{
Application.UnLock();
}
}
void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["ActiveSessions"] = (int)Application["ActiveSessions"] - 1;
Application.UnLock();
}
Then, in the UserLimitReached.aspx you would call HttpSession.Abandon() to effectively terminate the current session so it does not count towards the limit. You'll have to figure out the rest yourself. :)
One way would be to track active sessions in a database, and each time a user logs in, check the number of active sessions. If it is below a threshold, let them in, if not, bounce them.
To administer this number remotely, a simple admin form that lets you update the threshold in the database is simple enough.
In addition to the previous answers, I think you will need to introduce your own timeout so that sessions aren't left lingering and locked. Rather than use sessions, if you have a login, you can monitor it based on logins and keep them active by recording the most recent activity per user in a dictionary/array. That should make it easy to see which users are using the site, and which are the n most recently active users. If you tie that with the sessions, you could expire sessions used by the least recently active user. The effect of this is that if more than the specified number of users try use the website, some (the least active) will continually need to login. Given the disconnected nature of web apps, I think you may have to allow a certain % of grace so that when limited to 20 users, you actually allow maybe 22 to be concurrently active.

Resources