ASP.Net SQL Server Session State vs Persistent Session state - asp.net

I am researching and trying some things out with regards to the automatic saving of session variables into SQL Server. I have found this link discussing SQL Server session state (call it 'Option 1') and this link discussing Persistent SQL Server session state (call it 'Option 2').
The main difference seems to be that with Option 1, if the machine running SQL Server is turned off, the session data is lost, contrary to Option 2 which persists it. In Option 1 it seems that the process makes use of the tempdb, whereas, Option 2 seems to persist the session data through the use of the ASPState database.
I have a few questions that I can't seem to find any answers to:
In the first option, the article discusses the configuration required in the web config with regards to the < sessionState > tag. This is not added to the persistent case (Option 2). Should the < sessionState > be the same in both cases?
I have tried the second option as that seems to be more in-line to my case scenario. I started by downloading PersistSQLState.exe which simply self-extracts the InstallPersistSqlState.sql and UninstallPersistSqlState.sql scripts. I ran the InstallPersistSQLState.sql which completed successfully and created the 'ASPState' database in the SQL Server. I set the < sessionState > tag using the format stated in Option 2 as discussed in point 1) above.
Upon running the app I got the below error:
"Unable to use SQL Server because either ASP.NET version 2.0 Session State is not installed on the SQL server, or ASP.NET does not have permission to run the dbo.TempGetVersion stored procedure. If the ASP.NET Session State schema has not been installed, please install ASP.NET Session State SQL Server version 2.0 or above. If the schema has been installed, please grant execute permission on the dbo.TempGetVersion stored procedure to either the ASP.NET application pool identity, or the Sql Server user specified in the sqlConnectionString attribute."
This outlines 2 things: the Asp.Net Version 2.0 Session state potentially being not installed yet, and the process being unable to run the dbo.TempGetVersion stored procedure (for various reasons).
The stored procedure dbo.TempGetVersion does not exist in the ASPState database created by the InstallPersistSqlState.sql script. Is this stored procedure actually related to the tempdb (non-persistent) and therefore why the schema of the ASPState does not include it?
Is this the Asp.Net Version 2.0 Session state that needs to be installed? If so what is the process to be followed?! Should it be installed in the ASPState database after running the InstallPersistSQLState.sql script? If not, what is to be done exactly? There is nothing related to this ".exe" in either Option 1 or Option 2!
Finally, I have also tried uninstalling the persistent case instead run the scripts related to the Option 1 (non-persistent). In this case, the scripts provided in the first link above do not seem to work; returning 2 errors with jobs not being found ?!. Anyone has any idea why this would happen and do the correct scripts exist in some kind of online location?!
Any help would be appreciated as documentation seems poor on this subject.

The Option 1 and Option 2 articles as listed in my question are misleading, which is why I ended up wasting a whole day trying to make it work with the wrong info: I just did not have the right article at hand!
The below is what I ended up doing to implement persistent session state. Hope it can prove helpful to anyone wanting to implement the same thing.
On the machine open CMD in Administrator mode.
Change directory to .Net framework folder:
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
Run this command:
aspnet_regsql.exe -S "SQLServerInstanceName" -U "Username" -P "Password" -ssadd -sstype p
Small explanation of command in Point 2 above.
Aspnet_regsql.exe - is the .exe that installs Asp.Net Session state on the machine.
-S defines SQL Server instance name
-U defines Username -
-P defines Password
ssadd defines creating a new database for session state
sstype defines the type of session state. p is persistent.
Finally, in the web.config of the Asp.Net application where persistent session state is to be implemented, change the tag to look like the below:
< sessionState mode="SQLServer" sqlConnectionString="data source=127.0.0.1\sqltest;User ID=*****;Password=******" cookieless="false" timeout="20" / >
For full info visit this article and refer to the SQL Server mode.

Related

Various difficulties creating ASP.NET Session tables via aspnet_regsql.exe

We're trying to move ASP.NET session state for one of our Azure web apps into a database, and it seems like the aspnet_regsql.exe tool is the way to go. Unfortunately, I'm getting stuck on a few issues below. It's an Azure SQL database, and I'm connecting using the server's admin account.
I initially wanted to add the session tables to our existing database, so I ran .\aspnet_regsql.exe -U adminusername -P adminpassword -S servername.database.windows.net -d databasename -ssadd -sstype c. Which throws the exception "Database 'databasename' already exists. Choose a different database name"
Omitting the database name and running it again throws the exception: "Execution Timeout Expired" after about 30 seconds, which is just the default for SqlCommand.CommandTimeout. This occurs while executing the "CREATE DATABASE" command. I tried creating a database manually, and it takes about 50 seconds for some reason. This database is S0 tier and is not under any load
Running aspnet_regsql again on the already-created database (because it's idempotent, right?) leads to the "Database already exists" error, as does pre-creating an empty database for it to start from.
There's no flag that lets me increase the timeout, and I can't set command timeout using the -C (connection string) flag
Adding the -sqlexportonly flag to generate a script and just running that directly doesn't work either (yes, I know I'm not supposed to run InstallSqlState.sql directly). It throws a whole load of error messages saying things like:
Reference to database and/or server name in 'msdb.dbo.sp_add_job' is not supported in this version of SQL Server.
USE statement is not supported to switch between databases.
Which makes me think this script might have some issues with an Azure SQL database...
Does anyone have any ideas?
Update:
It looks like all the errors involving 'msdb' are related to removing and re-adding a database job called 'Job_DeleteExpiredSessions'. Azure SQL doesn't support database jobs, so the only options I can see are
Run SQL on a VM instead (vastly more expensive, and I'd rather stick with the platform services than have to manage VMs)
Implement one of those "Elastic Job Agents"
Perhaps move the same functionality elsewhere (e.g. a stored proc)?
Turns out Microsoft has an article about how to do exactly what I need, which I somehow
missed during my searching yesterday. Hopefully this answer saves someone else a few hours of frustration. All the info you need is at https://azure.microsoft.com/en-au/blog/using-sql-azure-for-session-state/ earlier.
Note that YMMV since it's from 2010 and also says in scary red letters
"Microsoft does not support SQL Session State Management using SQL Azure databases for ASP.net applications"
Nevertheless, they provide a working script that seems to do exactly what I need.

Automatic fix for tempdb error related to 'ASPStateTempSessions'

As per this how-to, I've successfully configured IIS on my XP-SP3 dev box for SQL Server 2008 Express to save ASP.NET session state information. I'm just using SQL Server because otherwise on every recompile, I was losing the session state which was obnoxious (having to re-login). But, I'm facing an annoying issue in that every time I restart SQL there's this error, and sometimes one or two other very similar friends:
The SELECT permission was denied on the object 'ASPStateTempSessions',
database 'tempdb', schema 'dbo'.
To fix the error, I just open Management Studio and edit the User Mapping for the login/dbo I'm using on the ASPState db, and re-add tempdb to that user with all but deny permissions. Apparently, once the right permissions are there, ASP.NET is able to automatically create the tables it uses. It just can't run that CreateTempTables sproc until the right security is there.
THE QUESTION...
Is there a way to not have to re-do this on every restart of the SQL Server?
I don't really care right now about keeping the temp data across restarts, but I would like to not have to go through this manual step just to get my web app working on localhost, which uses session state variables throughout. I suppose one could resort to some kind of stored procedure within SQL Server to accomplish the task for this machine when the service starts, to not have to do it manually. I'd accept such an answer as a quick fix. But, I'm also assuming there's a better recommended configuration or something. Not seeing an answer to this on the how-to guide or elsewhere here on StackOverflow.
Both answers seem valid; but with most things Microsoft, its all in the setup...
First uninstall the ASPState database by using the command:
aspnet_regsql –ssremove –E -S .
Note:
-E is to indicate you want to use integrated security connection.
-S informs what SQL server and SQL instance to use, and the "." (dot) specifies default local instance
Then re-install using the command:
aspnet_regsql –ssadd –sstype p –E -S .
Note:
The sstype has three options, t | p | c ... the first "t", tells the installer to host all stored procedures in the ASPState database, and all data in the tempdb. The second option "p" tells the installer to persist data to the ASPState database. The last option "c" allows you to specify a different 'custom' database to persist the session state data.
If you reinstall using the "-sstype p" you then need only to supply datareader/datawriter to the ASPState database for the user that's making the connection (in most cases, the application pool's identity in IIS).
The added benefit of persisting the data is that session state is retained even after a restart of the service. The only drawback is that you need to ensure the agent cleanup job is pruning old sessions regularly (it does this by default, every minute).
Important:
If you are running a cluster, you must persist session data. You're only option is to use sstype 'p' or 'c'.
Hope this sheds light on the issue!
For the record, I did find a way to do this.
The issue is that the tempdb is recreated from the model db each time the service restarts. The gist of the solution is to create a stored procedure that does the job, and then make that procedure run at startup.
Source code (credit to the link above) is as follows:
use master
go
-- remove an old version
drop proc AddAppTempDBOwner
go
-- the sp
create proc AddAppTempDBOwner as
declare #sql varchar(200)
select #sql = 'use tempdb' + char(13) + 'exec sp_addrolemember ''db_owner'', ''app'''
exec (#sql)
go
-- add it to the startup
exec sp_procoption 'AddAppTempDBOwner', 'startup', 'true'
go
Well done for finding the strangest way possible to do this.
The correct answer is as follows:
use master
go
EXEC sp_configure 'Cross DB Ownership Chaining', '1'
go
RECONFIGURE
go
EXEC sp_dboption 'ASPState', 'db chaining', 'true'
go

How To Query A Database That's Being Used By Asp.Net

I have a Sql Server 2008 Express database file that's currently being used by an ASP.NET application, and I'm not sure how to query the database without taking the website down.
I'm unable to copy the database files (.mdf and .ldf files) to another directory, since they're in use by the web server. Also, if I attach the databases to an instance of the sql server (using the 'Create Database [DB name] on (filename = '[DB filename.mdf]') for attach;' command at the sqlcmd prompt), then the application pool user becomes unable to access the database (i.e. the webpages start producing http 500 errors. I think this might have to do with the username for the application pool becoming somehow divorced from the login credentials in the sql server database).
Any suggestions? I realize this is probably a newbie question, since it seems like a rather fundamental task. However, due to my inexperience, I really don't know what the answer is, and I'm pretty stumped at this point, since I've tried a couple of different things.
Thanks!
Andrew
if I attach the databases to an instance of the sql server (using the 'Create Database [DB name] on (filename = '[DB filename.mdf]') for attach;' command at the sqlcmd prompt),
Don't do this to a live database - it's attempting to be setup an MDF to be written to by two different databases...
Use Backup/Restore
As you've found, Attach/ReAttach requires the database to be offline - use the Backup/Restore functionality:
MSDN: Using SSMS to Backup the Database
MSDN: Using SSMs to Restore the Backup
Be aware that the backup/restore doesn't maintain logins (& jobs if you have any associated with the database) - you'll have to recreate & sync if using an account other than those with uber access.
Maybe Linked Server would work?
Another alternative would be to setup another SQL Server Express/etc instance on a different box, and use the Linked Server functionality to create a connection to the live/prod data. Use a different account than the one used for the ASP application...

Asp.net session state server with SQL Server

We're trying to get session state working using the following web.config line:
<sessionState
mode="SQLServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data Source=dbServer;User ID=stateUser;Password='thepassword'"
cookieless="false"
timeout="20"/>
On dbServer, we've run the following command to set up the ASPState db:
aspnet_regsql.exe -S localhost-E -ssadd -sstype p
On the webServer, we've started the ASP.Net state service, however, no records show up in tables ASPStateTempApplications or ASPStateTempSessions, and it seems very much like session is still being stored in process.
What's wrong? Should the state service be running on the DB server? Does it get installed with IIS, because it's not available on that machine, despite .net 3.5.1 being installed.
The IIS logs show no hint of failure. What's wrong?
If there's really quotes around the password, try to remove them:
sqlConnectionString="Data Source=dbServer;User ID=stateUser;Password=thepassword"
And remove the following line, it has no function for SQL session storage:
stateConnectionString="tcpip=127.0.0.1:42424"
And you might as well stop the state service; it's needed for out-of-process session state, not for SQL Server session state.
Also, SQL Server session state requires you to run InstallSqlState.sql on the database, not aspnet_regsql.exe. It should create a new ASPState database.
First, you don't need to start the State Service in order to use SQL Server session state. Forget about the ASP.NET State Service.
Are you sure that your site is creating a session variable? Just because you put these changes in your web.config, if you never use session variables, it won't be used.
How about writing a small HttpModule? You could drop it into place for the period of time when you need to transition users to the new codebase. The module could do some work on each page request to check the user's session and decide whether it needs to be abandoned. Perhaps you store an application version string in the user's session when the session is first created and compare the current app version string against that.

BizTalk SSO configuration and SQL Error 18456, Severity 14, State 16

I'm having a major issue trying to configure a new install of BizTalk Server 2006 (not R2). The server had BizTalk installed on it before, and it was working fine. I've uninstalled BizTalk, removed the databases and jobs from the SQL server, which is a separate machine, and re-installed BizTalk. The install was successful, with no errors during the install, and nothing in the install logs.
I'm configuring the BizTalk server to be the SSO master secret server, along with creating a new BizTalk group and registering the BizTalk runtime. The process always errors out on creating the SSO database on the SQL server. In the ConfigLog, there are a couple of warnings that the MSSQLServerOLAPService does not exist, then it shows errors on creating the SSO database. There are 4 in a row. In order, they are:
Error ConfigHelper] [DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.
Error ConfigHelper] SQL error: 08001 Native error code: 17
Error ConfigHelper] c:\depotsetupv2\private\common\configwizard\confighelper\sqlhelper.cpp(1176): FAILED hr = 80004005
Error ConfigHelper] c:\depotsetupv2\private\common\configwizard\confighelper\sqlhelper.cpp(918): FAILED hr = 80004005
It then has similar errors trying to create each of the BizTalk databases.
On the SQL server, there are corresponding errors in the SQL Server Logs - 2 for each attempt
Login failed for user '[USERNAME]'.[CLIENT: [IP ADDRESS]]
Error: 18456, Severity: 14, State: 16
The first error from the SQL logs also shows up as a failure audit in the SQL server's application event log.
The biggest issue I am having with this is that the user I am logged on to the BizTalk server is a local admin on both the BizTalk server and the SQL server, and is in the SQL sysadmin group. The user that I am configuring the BizTalk services to run under is also a local admin on both servers and in the sysadmin group on the SQL server. I've checked the MSDTC settings on both machines and made sure they are set as the BizTalk documentation recommends. SQL Browser is running on the SQL machine, and I've verified that network access is allowed using the SQL Surface Area Configuration tool.
Can anyone help me find something that I might have missed?
Re: Igal:
Yes, all of the servers and users are on the same domain. I've run across that posting on SQL protocols in researching this, but I tried to select a count from one of the tables in the default database of the logged in user while connected to another database. I had no problems at all running that query.
Re: Yossi:
I'm installing BizTalk on Windows Server 2003 R2 SP1. Yes, I have removed the SSODB (Wouldn't out it past myself to miss something like that though!). I will make sure I am providing the usernames correctly and check out the sources you linked and get back to you.
A few of pointers:
Check out the two points at the end of the Configuring Enterprise SSO Using the Configuration Manager page on MSDN:
When configuring the SSO Windows
accounts using local accounts, you
must specify the account name without
the computer name.
When using a local SQL Server named
instance as data store, you must use
LocalMachineName\InstanceName instead
of LocalMachineName\InstanceName,
PortNumber.
Check out the relevant installation guide (don't worry about the fact that it relates to R2, they seems to have hidden the 'R1' documentation, but they are the same), and specifically the section around "Windows Groups and Service Accounts"
also - just to be sure - when you have uninstalled BizTalk and removed the databases - you have removed the SSODB as well, right?! :-)
The log files are very confusing - especially when deciding which error is the acutal problem - have you tried looking up any other errors you've had? (check out this blog entry, for example)
I had everything set up properly. Unfortunately for me, the answer was the standard "Windows" answer - reboot and try again. As soon as I rebooted the SQL server, I was able to configure BizTalk just fine.
I am going to set Yossi's answer as accepted, however, since that would be the most relevant for anyone else who may be reading this question.
Just remember to reboot after all setting changes!
Make sure the BizTalkMgmtDb and BizTalkMsgBoxDb have your local admin account as DB OWNER.
Right click on the databases --> Properties --> Files --> Owner:

Resources