.NET Session Alternative in Global Scope - c#

Quick question: Is there a "per-user" data storage object (similar to Session) that I can store data in the global scope (similar to HttpRuntime.Cache)? Almost as if Session and HttpRuntime.Cache had a baby.
Full Background: I have a ASP.NET website that was originally written for a single thread. Now I changed it so that certain actions will spawn a background thread and the browser polls a service to get status updates.
The problem I am having with this is that certain pieces of data are stored into the HttpContext.Session[] object (membership authentication token, for example). These pieces of data need to be unique to each user and accessible to the background thread. Session is not available to the background thread.
I am aware of HttpRuntime.Cache but that would require micromanagement to segment out the users and to expire it at the same time the session is expired. Session, on the other hand, automatically expires this things at the right times that I want it too and is already used by things like the SqlMembershipProvider.
My question is, is there something that behaves similar to the Session but exists in the global scope?

I don't think there is anything like you need out of the box. I would do the following though:
User the application cache
Make the key the user ID or unique identifier
Store a Dictionary or some object list in the value for the user. Use this to store all the data you require.
Consider all prepending something on the user ID if you think there could be a conflict with the user unique identifier (eg domain etc)
Make sure to set an expiry on the cached data similar to the session (eg sliding)

Try passing the HttpContext.Current object to the method on your background thread. You should be able to access the session from the background thread through currentContext.Session assuming currentContext is the HttpContext parameter that was passed in.
See this blog post on how to safely access the HttpContext object from multiple threads.

No.
Since when application pool restarts all backgound activity die I suggest to think about moving user's state to your own database or external storage. Unfortunately you'll lose automatic session management benifits (sliding expiration), but if you need backgound activity it will work better - i.e. you'll be able to move your activity out of IIS process to separate process/machine if needed later.

Related

keep track of current context of user action using SignalR for push notification

If you look at StackOverflow (SO) site, while you are looking at a specific thread and there is some update to that thread, SO pushes the notification to you. That means SO is aware of user context/user action (which thread you are currently seeing). I am trying to build something similar in my ASP.NET web API application using SignalR.
In order to implement this similar behavior, I am performing following steps.
Every time user views a thread, I make a get call to an endpoint to return thread information along with that, I am maintaining a dictionary which I update every time, this endpoint is called. In this dictionary I store the context.connectionId as key and threadId as value (keeping threadId as value since multiple users can view the same thread at the same time).
Anytime a change is made to any thread, I ask the dictionary to return me all the connectionId (keys) where value == threadId.
Then I push notification to all the coonectionId's returned in step2.
Questions:
I feel this is overkill and there might be an easier way to do all this. What is the best approach to handle this scenario?
Do you think this approach will scale well and application performance will not be impacted.
Tomorrow if I move to server farm, would this approach will still work ?
There's nothing wrong with this approach. This seems like a fairly straightforward pubsub approach. A user subscribes to a particular thread upon viewing. The server then publishes updates to that thread to the users who have subbed to it. What you outlined for a context dictionary is really the minimum amount of data needed to send targeted updates to users.
Scaling is fine, although I would argue that you should reverse your dictionary for better performance. You should key off the threadId, and keep a list of connectionIds that have subbed to that thread. In doing so, you'd be able to simply add a connectionId to a an existing list when a new user is viewing a thread. You minimize the amount of data you need to keep in memory. As it stands now, you have to loop over every connectionId to figure out what they're looking at and aggregate that into a single list, so you might as well just reverse it and store the list itself.
It would work so long as each server in the farm handles their own list of connectionId/threadId maps. If each server can respond to a change in the thread independently, then a farm setup should be fine.

Is there a way to access another session via its ID and read it's session variables?

This application is running in a load balanced environment. It uses a SQL database as the session store. The app is simple and does not have it's own database.
I have created an endpoint to be called from another internal server that knows the SessionId. I want this endpoint to be able to grab a session variable by SessionId instead of from the current session.
I know that I could create a new database to do this, but it would be overkill as it would only have 1 table with 2 fields, SessionId and the one value related to it. I could even put this table in the current session database. I am trying to avoid having to add database connection code if at all possible.
Is there a way to access the variables of a different session other than the current session?
I might be wrong and if I am - downvote; the fact that the session state storage is database-based (and not in-memory) does not change the principles of how the IHttpSessionState works. I doubt you will be able to do that and I doubt you actually want to: you simply cannot access an absolutely separate context from a different context. Doing so has a lot of potential issues (thread safety, problems if the session state implementation is changed and so on). Your web application might not be aware of the session state store.
For example, if I simply use session state and have the session state configured directly in IIS, there is no way for the application thread to know it's in the database which immediately presents an issue: what if I decide to run the same application without the DB-backed session state? No changes to application code are required, just IIS reconfiguration. It might introduce unexpected behavior and/or runtime errors.
The suggestion (in the comment) to set the cookie to the known session ID is the only "way out" but from the security perspective it's less than optimal.
However, what you are trying to implement seems like a proper job for a Cache Provider. You can use SqlCacheDependency from System.Web.Caching to use the database for your cache. Then you could use the aforementioned SessionId as one of the cache identifiers.

Do I need a ConcurrentDictionary? Will regular Dictionary do?

I currently am using a ConcurrentDictionary to hold a collection of login names that have authenticated with my API. I do this to prevent duplicate logins from other web clients (a requirement of the system architecture). If a user authenticates with a login that is already "logged in" they are given a choice ...
Continue and the previous login will be expired
Cancel and the current session will be logged out
I am using a ConcurrentDictionary because it is supposed to be thread safe which is important in an environment where multiple clients are accessing the API.
What I am asking is if the ConcurrentDictionary is needed because I am running into trouble deleting all items in the collection that match a given key. Is a ConcurrentDictionary called for in this case? If not, would a plain Dictionary suffice? If not, and a ConcurrentDictionary is needed is there a method that will remove all entries matching a given key? All I can see is TryRemove() which only seems to remove a single entry.
The direct answer to your question:
Yes, you need a ConcurrentDictionary. You are sharing state across several threads.
Remember, a dictionary has one entry per key. That's the definition of what a Dictionary is, and a ConcurrentDictionary doesn't change that.
A fuller and more complete answer to your requirement is below.
The whole solution is short sighted as you have no connection with the session infrastructure to know when a user's session has timed out and effectively caused them to be logged out. Additionally there is no coordination with other instances of your app if you ever think about deploying to a cloud platform that spins up new instances.
In other words, you are putting yourself in a situation that makes it very difficult to scale your app without breaking this feature.
Probably one of the most robust ways of handling the single session requirement is to use your database:
Have a field that keeps track of the last session ID your user had when logging in.
Add a session listener to clear the field when the session times out
If the session ID is not the same as what's in the field, you know you have a new login attempt.
If you need complete control over the session ID, then supply your own session id manager (may be necessary to include an encoded server ID in it).
You'll find that the requirement is much more involved than it sounds on the surface. You can't think like a desktop application in the web space--which is precisely where this requirement even comes from.

Threading in ASP.NET MVC 3

I am currently converting a Windows Phone 7 application to its web counterpart. The application uses a big main thread from which the data is gathered, and for the moment I have just copied and pasted it as is (just a standard thread operation), in my ASP.NET MVC controller.
Sync _Sync = new Sync();
_Sync.StartSync();
The tasks work OK, but because the thread makes use of global data set from the cookies, issues arise when accessing the page with 2 different usernames. For example, if I login with "user1" in Firefox and then try to login in Chrome with another user (say "user2"), then it will automatically change the async data gathered for the first user; meaning that I will always see data pulled out from the last user logged in (regardless of the fact that I was just logged in in Firefox with another user, initially), and not each others' separate data.
In other words, the thread doesn't start separately for each individual user. How could I fix this behavior?
Static fields and properties are shared across threads and should generally not be used to store data that pertains to a specific user or web request.
One of the following suggestions should fix your threading issues and keep your user data separate.
Create an instance of the Sync class for each request and remove any static fields / properties from the class.
Add a method to the Sync class that returns an instance of the data for a specific user instead of storing the data in static fields / properties.

Persistent Controller Members

I have a controller that needs to persist the state of a Dictionary member. On navigating to a specific action, an entry for that user is created and added to the dictionary. I require a separate ajax action to pull the object out, use it, and save it back, however it seems as though between the two events my dictionary is being collected.
Now I've tried a number of things to ensure that this dictionary stays put but to no avail. As a requirement, I need this dictionary to stay resident in memory for quick access. I understand that MVC is supposed to be stateless and I should use a different kind of backing store. Suggestions?
From your description putting the dictionary into the Session should be an option. The session store has the following properties:
Stays alive between requests.
Complete separation of different uses/sessions.
Easy to set up - no database or file to configure.
Quick access since it is normally handled in memory.
Not suitable for large amounts of data.
The session store is cleared if the application pool is recycled (which happends sometimes).
There are many backing stores available:
Session
Files
Database
...
Up to you to pick one.

Categories