Показват се публикациите с етикет SqlServer. Показване на всички публикации
Показват се публикациите с етикет SqlServer. Показване на всички публикации

четвъртък, 20 януари 2011 г.

How to Store ASP.NET Sessions in MSSql Database


Change the settings inside the session tag in your application web.config file:

<sessionState allowCustomSqlDatabase="true" cookieless="UseCookies" cookieName="HTTP_COOKIE" mode="SQLServer"
    regenerateExpiredSessionId="true" sqlConnectionString="data source=ServerName\SqlInstance;
    DataBase=dbName;Integrated Security=True" stateConnectionString="tcpip=127.0.0.1:42424"
    stateNetworkTimeout="20" timeout="500" />

Open the Command Prompt, go to "C:\Windows\Microsoft.NET\Framework\v2.0.50727" 
and run this command:  
aspnet_regsql.exe -S <Server\Instance> -U <Username> -P <Password> -ed -d <DataName>  
 
After this command, two tables (ASpStateTempApplications and ASPStateTempSessions
are created in the selected database as well as several stored procedures and sql job for 
deleting/updating/inserting sessions in the tables. The SQL account you used in this 
command must also have rights to make changes on the database, otherwise you get an 
"no execute permission" error. You can check the settings you just set in the web.config 
file in the IIS "Session State" section - they should be the same. In this scenario you 
have 500 minutes timeout of your session cookies. You have regenerateExpiredSessionId 
set to "True" which means that any postback made by the user updates the record in the 
database and changes the expiration time of your session record.

Get Data From MS SQL Database with ADO.NET C#

In the code-behind you have: 
-------------------------------
using System.Data.SqlClient;
using System.Data;
string yourSqlQuery = "SELECT ID, Decsription FROM Articles Where ManufacturerName = @ParamName";
string connString = "Data Source=ServerName\\SqlInstance;Database=dbName;User=UserAcc;password=Pwd;Integrated Security=False";

SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(yourSqlQuery, conn);
cmd.Parameters.AddWithValue("@ParamName", "paramValue");
if (conn.State != ConnectionState.Open)
    conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
------------------------------
Note: Account "UserAcc" used to run the query needs permissions in the SqlServer -> Security -> Logins. In case you use Integrated Security=True you actually use Network Services account (or ASPNET in Win XP) and should consider granting necessary permissions. Have in mind that firewalls, routers can also block your connection to the SqlServer.