Wednesday, November 17, 2010

ASP.NET with SQL 2005 Cache Dependence

1) Check to see Service Broker is enabled

SELECT name, is_broker_enabled FROM sys.databases

2) To enable the Service Broker on your database

ALTER DATABASE Pubs SET ENABLE_BROKER
GO

3) Inform SQL Server that the user running IIS has permission to subscribe to query notificatoins.

GRANT SUBSCRIBE QUERY NOTIFICATIONS TO "IIS_SERVER\ASPNET"

4) Create a connectionStrings in the web.config

<connectionstrings>
<add name="myDbConnectionString" connectionstring="Data Source=localhost;Initial Catalog=MyDB;Integrated Security=True" providername="System.Data.SqlClient">
</connectionstrings>

5) Enable the website to be able to receive notifications.

protected void Application_Start(object sender, EventArgs e)
{
SqlDependency.Start(ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString);
}

The following code also stops the listener:

protected void Application_End(object sender, EventArgs e)
{
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString);
}

6) Sets up the cach dependency. Example code.

string tableName = query.Context.Mapping.GetTable(typeof(T)).TableName;
List result = HttpContext.Current.Cache[tableName] as List;

if (result == null)
{
using (SqlConnection cn = new SqlConnection(query.Context.Connection.ConnectionString))
{
cn.Open();
SqlCommand cmd = new SqlCommand(query.Context.GetCommand(query).CommandText, cn);
cmd.Notification = null;
cmd.NotificationAutoEnlist = true;
SqlCacheDependencyAdmin.EnableNotifications(query.Context.Connection.ConnectionString);
if (!SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(query.Context.Connection.ConnectionString).Contains(tableName))
{
SqlCacheDependencyAdmin.EnableTableForNotifications(query.Context.Connection.ConnectionString, tableName);
}

SqlCacheDependency dependency = new SqlCacheDependency(cmd);
cmd.ExecuteNonQuery();

result = query.ToList();
HttpContext.Current.Cache.Insert(tableName, result, dependency);
}
}

Friday, November 5, 2010

Re-Associate the dbo to sa login after db restored

You could use the following SQL script to relink the dbo user of a db to login.

ALTER AUTHORIZATION ON DATABASE::[db name] TO [login name]