Is there a Session-unique identifier that can be used as a cache key name? - asp.net-core

I'm porting a legacy ASP.NET WebForms app to Razor. It had stored an object in the Session collection. Session storage is now limited to byte[] or string. One technique is to serialize objects and store as a string, but there are caveats. Another article suggested using one of the alternative caching options, so I'm trying to use MemoryCache.
For this to work as a Session replacement, I need a key name that's unique to the user and their session.
I thought I'd use Session.Id for this, like so:
ObjectCache _cache = System.Runtime.Caching.MemoryCache.Default;
string _keyName = HttpContext.Session.Id + "$searchResults";
//(PROBLEM: Session.Id changes per refresh)
//hit a database for set of un-paged results
List<Foo> results = GetSearchResults(query);
if (results.Count > 0)
{
//add to cache
_cache.Set(_keyName, results, DateTimeOffset.Now.AddMinutes(20));
BindResults();
}
//Called from multiple places, wish to use cached copy of results
private void BindResults()
{
CacheItem cacheItem = _cache.GetCacheItem(_keyName);
if (cacheItem != null) //in cache
{
List<Foo> results = (List<Foo>)cacheItem.Value;
DrawResults(results);
}
}
...but when testing, I see any browser refresh, or page link click, generates a new Session.Id. That's problematic.
Is there another built-in property somewhere I can use to identify the user's session and use for this key name purpose? One that will stay static through browser refreshes and clicks within the web app?
Thanks!

The answer Yiyi You linked to explains it -- the Session.Id won't be static until you first put something into the Session collection. Like so:
HttpContext.Session.Set("Foo", new byte[] { 1, 2, 3, 4, 5 });
_keyName = HttpContext.Session.Id + "_searchResults";
ASP.NET Core: Session Id Always Changes

Related

Managing CosmosDb Session Consistency levels with Session Token in web environment

My environment is ASP.NET Core 2.x accessing CosmosDb (aka DocumentDb) with the .NET SDK.
The default consistency level of my collection is set to "Session". For my use-case I need a single authenticated web user to always have consistent data in terms of reads/writes between web requests.
I have some CosmosDB Repository logic that is made available to my controller logic via ASP.NET Core Singleton dependency injection as such:
services.AddSingleton<DocumentDBRepository, DocumentDBRepository>(x =>
new DocumentDBRepository(
WebUtil.GetMachineConfig("DOCDB_ENDPOINT", Configuration),
WebUtil.GetMachineConfig("DOCDB_KEY", Configuration),
WebUtil.GetMachineConfig("DOCDB_DB", Configuration),
"MyCollection",
maxDocDbCons));
DocumentDBRespository creates a cosmos client like so:
public DocumentDBRepository(string endpoint, string authkey, string database, string collection, int maxConnections)
{
_Collection = collection;
_DatabaseId = database;
_Client = new DocumentClient(new Uri(endpoint), authkey,
new ConnectionPolicy()
{
MaxConnectionLimit = maxConnections,
ConnectionMode = ConnectionMode.Direct,
ConnectionProtocol = Protocol.Tcp,
RetryOptions = new RetryOptions()
{
MaxRetryAttemptsOnThrottledRequests = 10
}
});
_Client.OpenAsync().Wait();
CreateDatabaseIfNotExistsAsync().Wait();
CreateCollectionIfNotExistsAsync().Wait();
}
As far as I understand that means one CosmosDB client per Web App server. I do have multiple web app servers, so a single user might hit the CosmosDB from multiple AppServers and different CosmosDb clients.
Before a user interacts with the ComosDB, I check their session object for a CosmosDb SessionToken, like so:
string docDbSessionToken = HttpContext.Session.GetString("StorageSessionToken");
Then, when writing a document for example, the method looks something like so:
public async Task<Document> CreateItemAsync<T>(T item, Ref<string> sessionTokenOut, string sessionTokenIn = null)
{
ResourceResponse<Document> response = null;
if (string.IsNullOrEmpty(sessionTokenIn))
{
response = await _Client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(_DatabaseId, _Collection), item);
}
else
{
response = await _Client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(_DatabaseId, _Collection), item, new RequestOptions() { SessionToken = sessionTokenIn });
}
sessionTokenOut.Value = response.SessionToken;
Document created = response.Resource;
return created;
}
The idea being that if we have a session token, we pass one in and use it. If we don't have one, just create the document and then return the newly created session token back to the caller. This works fine...
Except, I'm unclear as to why when I do pass in a session token, I get a DIFFERENT session token back. In other words, when _Client.CreateDocumentAsync returns, response.SessionToken is always different from parameter sessionTokenIn.
Does that mean I should be using the new session token from that point on for that user? Does it mean I should ignore the new session token and use the initial session token?
How long do one of these "sessions" even last? Are they sessions in the traditional sense?
Ultimately, I just need to make sure that the same user can always read their writes, regardless of which AppServer they connect with or how many other users are currently using the DB.
I guess the confusion here is on what a session is?
In most scenarios/frameworks treat session as static identifier (correlation), where as with cosmos the sessionToken is dynamic (kind of bookmark/representation of cosmos db state, which changes with writes). Naming it as 'sessionToken' might be root of the confusion.
In this specific scenario, you should use the "returned sessiontoken" from cosmos API's.

Using global variable in ASP.NET Core controller

The question is simple but I don't know how use it.
For example there is a controller
public class MainController : Controller
{
private int a;
public IActionResult Index(bool set = true)
{
if (set) a = 10;
return View(a)
}
}
If I get in Index page at first time, I set a = 10. And I get in Index page again (for example refresh Index page or paging in Index page, i.e. move in same page) Actually, I get in Index page with url : ~Index?set=False after first access.
Then the a has 0 (default for int variable). I did not know the Controller page (Controller class) is always initialized when I gen in it even when I move to same page.
So, I want to use variable like global variable not using session.
Is there any way?
It sounds like you wish to persist a variable between requests.
Per user
If you wish to store a variable that persists but is only visible to the current user, use session state:
public int? A
{
get
{
return HttpContext.Current.Session["A"] as int?;
}
set
{
HttpContext.Current.Session["A"] = value;
}
}
Note that we are using int? instead of int in order to handle the case where the session variable has not yet been set. If you prefer to default to 0, you can simply use the coalesce operator, ??.
Truly global
If you wish to persist a variable in a manner where there is only one copy for all users, you can store it in a static variable or in an application state variable.
So either
static volatile public int a;
Or
public int? A
{
get
{
return HttpContext.Current.Application["A"] as int?;
}
set
{
HttpContext.Current.Application["A"] = value;
}
}
Obviously variables that are shared between users can change at any time (due to activity in other threads), so you should be careful about how you handle them. For variables that are int-sized or smaller, the processor will perform atomic reads and writes, but for variables larger than an int you may need to use Interlocked or lock to control access.
You do not need to worry about thread synchronization for session variables; the framework handles it for you.
Note: The above is just an example to help you find the right API. It does not necessarily demonstrate the best pattern-- accessing HttpContext via the static method Current is considered bad form, as it makes it impossible to mock the context. Please see this article for ways to expose it to your code via DI.

Relation many-to-one retrieved from custom cache

It's more like theoretical question.
I have one table to hold dictionary items, and the next one for hold Users data.
User table contains a lot reference collumns of type many to one indicated on dictionary item table. It's looks like:
public class User
{
public int Id;
public Dictionary Status;
public Dictionary Type;
public Dictionary OrganizationUnit;
......
}
I want retrieve all dictionary on startup of aplication, and then when i retrieved user and invoke reference property to dictionary the dictionary object should be taken from cache.
I know i can use a 2nd level cache in this scenario, but i'm interested about other solution. Is there any?
It's posible to make my custom type and said that: use my custom cache to retrieved value of dictionary??
Across multiple session the second level cache is the best answer, the only other solutions to populate objects from a cache without using second level cache i can think of would be to use an onLoad interceptor (and simply leave your dictionaries unmapped) or do it manually somewhere in your application.
But why don't you want to use the seocondlevel cache? If your views on caching is very different from the storages there are providers for in hibernate it is possible for you to implement your own provider?
Why not store it in the session? Just pull the record set one time and push it into session and retrieve it each time you want it. I do something similar for other stuff and I believe my method should work for you. In my code I have a session manager that I call directly from any piece of code needs the session values. I choose this method since I can query the results and I can manipulate the storage and retrieval methods. When relying on NHibernate to do the Caching for me, I don't have the granularity of control to cause specific record sets to only be available to specific sessions. I also find that NHibernate is not as efficient as using the session directly. When profiling the CPU and memory usage I find that this method is faster and uses a little less memory. If you want to do it on a site level instead of session, look into HttpContext.Current.Cache.
The following example works perfectly for storing and retrieving record sets:
// Set the session
SessionManager.User = (Some code to pull the user record with relationships. Set the fetch mode to eager for each relationship else you will just have broken references.)
// Get the session
User myUser = SessionManager.User;
public static class SessionManager
{
public static User User
{
get { return GetSession("MySessionUser") as User; }
set { SetSession("MySessionUser", value); }
}
private static object GetSession(string key)
{
// Fix Null reference error
if (System.Web.HttpContext.Current == null || System.Web.HttpContext.Current.Session == null)
{
return null;
}
else
{
return System.Web.HttpContext.Current.Session[key];
}
}
private static void SetSession(string key, object valueIn)
{
// Fix null reference error
if (System.Web.HttpContext.Current.Session[key] == null)
{
System.Web.HttpContext.Current.Session.Add(key, valueIn);
}
else
{
System.Web.HttpContext.Current.Session[key] = valueIn;
}
}
}

RavenDB Catch 22 - Optimistic Concurrency AND Seeing Changes from Other Clients

With RavenDB, creating an IDocumentSession upon app start-up (and never closing it until the app is closed), allows me to use optimistic concurrency by doing this:
public class GenericData : DataAccessLayerBase, IGenericData
{
public void Save<T>(T objectToSave)
{
Guid eTag = (Guid)Session.Advanced.GetEtagFor(objectToSave);
Session.Store(objectToSave, eTag);
Session.SaveChanges();
}
}
If another user has changed that object, then the save will correctly fail.
But what I can't do, when using one session for the lifetime of an app, is seeing changes, made by other instances of the app (say, Joe, five cubicles away), to documents. When I do this, I don't see Joe's changes:
public class CustomVariableGroupData : DataAccessLayerBase, ICustomVariableGroupData
{
public IEnumerable<CustomVariableGroup> GetAll()
{
return Session.Query<CustomVariableGroup>();
}
}
Note: I've also tried this, but it didn't display Joe's changes either:
return Session.Query<CustomVariableGroup>().Customize(x => x.WaitForNonStaleResults());
Now, if I go the other way, and create an IDocumentSession within every method that accesses the database, then I have the opposite problem. Because I have a new session, I can see Joe's changes. Buuuuuuut... then I lose optimistic concurrency. When I create a new session before saving, this line produces an empty GUID, and therefore fails:
Guid eTag = (Guid)Session.Advanced.GetEtagFor(objectToSave);
What am I missing? If a Session shouldn't be created within each method, nor at the app level, then what is the correct scope? How can I get the benefits of optimistic concurrency and the ability to see others' changes when doing a Session.Query()?
You won't see the changes, because you use the same session. See my others replies for more details
Disclaimer: I know this can't be the long-term approach, and therefore won't be an accepted answer here. However, I simply need to get something working now, and I can refactor later. I also know some folks will be disgusted with this approach, lol, but so be it. It seems to be working. I get new data with every query (new session), and I get optimistic concurrency working as well.
The bottom line is that I went back to one session per data access method. And whenever a data access method does some type of get/load/query, I store the eTags in a static dictionary:
public IEnumerable<CustomVariableGroup> GetAll()
{
using (IDocumentSession session = Database.OpenSession())
{
IEnumerable<CustomVariableGroup> groups = session.Query<CustomVariableGroup>();
CacheEtags(groups, session);
return groups;
}
}
Then, when I'm saving data, I grab the eTag from the cache. This causes a concurrency exception if another instance has modified the data, which is what I want.
public void Save(EntityBase objectToSave)
{
if (objectToSave == null) { throw new ArgumentNullException("objectToSave"); }
Guid eTag = Guid.Empty;
if (objectToSave.Id != null)
{
eTag = RetrieveEtagFromCache(objectToSave);
}
using (IDocumentSession session = Database.OpenSession())
{
session.Advanced.UseOptimisticConcurrency = true;
session.Store(objectToSave, eTag);
session.SaveChanges();
CacheEtag(objectToSave, session); // We have a new eTag after saving.
}
}
I absolutely want to do this the right way in the long run, but I don't know what that way is yet.
Edit: I'm going to make this the accepted answer until I find a better way.
Bob, why don't you just open up a new Session every time you want to refresh your data?
It has many trade-offs to open new sessions for every request, and your solution to optimistic concurrency (managing tags within your own singleton dictionary) shows that it was never intended to be used that way.
You said you have a WPF application. Alright, open a new Session on startup. Load and query whatever you want but don't close the Session until you want to refresh your data (e.g. a list of order, customers, i don't know...). Then, when you want to refresh it (after a user clicks on a button, a timer event is fired or whatever) dispose the session and open a new one. Does that work for you?

ASP.NET Site Maps

Does anyone have experience creating SQL-based ASP.NET site-map providers?
I have the default XML file web.sitemap working properly with my Menu and SiteMapPath controls, but I'll need a way for the users of my site to create and modify pages dynamically.
I need to tie page viewing permissions into the standard ASP.NET membership system as well.
The Jeff Prosise version from MSDN magazine works pretty well, but it has a few flaws:
AddNode freaks out with links to external sites on your menu (www.google.com, etc.)
Here's my fix in BuildSiteMap():
SiteMapNode node = GetSiteMapNodeFromReader(reader);
string url = node.Url;
if (url.Contains(":"))
{
string garbage = Guid.NewGuid().ToString(); // SiteMapNode needs unique URLs
node.Url = "~/dummy_" + garbage + ".aspx";
AddNode(node, _root);
node.Url = url;
}
else
{
AddNode(node, _root);
}
SQLDependency caching is cool, but if you don't want to make a trip to the DB everytime your menu loads (to check to see if the dependency has changed) and your menus don't change very often, then why not use HttpRuntime.Cache instead?
public override SiteMapNode RootNode
{
get
{
SiteMapNode temp = (SiteMapNode)HttpRuntime.Cache["SomeKeyName"];
if (temp == null)
{
temp = BuildSiteMap();
HttpRuntime.Cache.Insert("SomeKeyName", temp, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
}
return temp;
}
}