Introduction
This article will walk you through all the steps necessary to setup a sample project demonstrating how to create a CLR Trigger in SQL Server 2005 that will communicate with a WCF service of your design. This is not an introduction to WCF, but an introduction to using WCF from SQL Server 2005 CLR Triggers.
Background
After reading up about WCF, I was keen to start utilizing it in some of my existing database projects. One of my objectives was to get a CLR Trigger speaking to a WCF service. I figured this should be a fairly straightforward process, but there are so many gotchas involved that I thought it would be useful to share some of them and to produce a demo of a way in which to achieve this goal.
Using the Code
Prerequisites
- Development machine: VS2005, WCF extensions for VS2005, .NET 3.0 Runtime
- Database machine: SQL Server 2005 or SQL Server 2005 Express, .NET 3.0 Runtime
Create the WCF Service
- Open Visual Studio.
- Create a new C# console application and call it 'Service'.
- Add a reference to:
System.ServiceModel
. - Create a service contract:
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
namespace SampleService
{
[ServiceContract]
interface IServiceContract
{
[OperationContract]
void UpdateOccured();
[OperationContract]
void InsertOccured();
}
- Add an
interface
to the project and call it 'IServiceContract
'. - Replace the code in the interface with:
- Implement the service contract.
using System;
using System.Collections.Generic;
using System.Text;
namespace SampleService
{
class MyService : IServiceContract
{
public void UpdateOccured()
{
Console.WriteLine("Update Occured");
}
public void InsertOccured(int RecordID)
{
Console.WriteLine("Insert Occured");
}
}
}
- Add a new class and name it '
ServiceContract
'. - Replace the code in the class with:
- Host the service
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace SampleService
{
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8000/services");
ServiceHost MyHost = new ServiceHost(typeof(MyService),
baseAddress);
WSHttpBinding MyBinding = new WSHttpBinding();
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
MyHost.AddServiceEndpoint(typeof(IServiceContract),
MyBinding, "MyService");
MyHost.Description.Behaviors.Add(smb);
MyHost.Open();
Console.WriteLine("Your service has been started");
Console.WriteLine("Press <enter /> to terminate service.");
Console.WriteLine();
Console.ReadLine();
}
}
}
- Replace the code in Program.cs with:
Preparing the Database
This part of the process took the longest to work out, and caused the greatest number of problems. If you follow the steps outlined here, it should allow you to prepare any database to allow communication with a WCF service.
EXEC sp_configure 'show advanced options' , '1';
go
reconfigure;
go
EXEC sp_configure 'clr enabled' , '1'
go
reconfigure;
EXEC sp_configure 'show advanced options' , '0';
go
use custdb
ALTER DATABASE custdb SET TRUSTWORTHY ON
reconfigure
CREATE ASSEMBLY
SMDiagnostics from
'C:\Windows\Microsoft.NET\Framework\v3.0\Windows
Communication Foundation\SMDiagnostics.dll'
with permission_set = UNSAFE
GO
CREATE ASSEMBLY
[System.Web] from
'C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Web.dll'
with permission_set = UNSAFE
GO
CREATE ASSEMBLY
[System.Messaging] from
'C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Messaging.dll'
with permission_set = UNSAFE
GO
CREATE ASSEMBLY
[System.IdentityModel] from
'C:\Program Files\Reference Assemblies\Microsoft\
Framework\v3.0\System.IdentityModel.dll'
with permission_set = UNSAFE
GO
CREATE ASSEMBLY
[System.IdentityModel.Selectors] from
'C:\Program Files\Reference Assemblies\Microsoft\
Framework\v3.0\System.IdentityModel.Selectors.dll'
with permission_set = UNSAFE
GO
CREATE ASSEMBLY
[Microsoft.Transactions.Bridge] from
'C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication
Foundation\Microsoft.Transactions.Bridge.dll'
with permission_set = UNSAFE
GO
- Create a basic database called '
custDB
', and add a table called 'tbCR
' to it with the following columns:
[CustomerName] [varchar](50)
[CustomerTel] [varchar](50)
[CustomerEmail] [varchar](50)
- By default, CLR is disabled in SQL Server 2005. Enable CLR execution by executing the following query:
- Your database will be accessing "unsafe" assemblies. In order to prevent security exceptions, you will have to mark your database as "trustworthy" by executing the following query. (For more information on this option, see: TRUSTWORTHY Database Property):
- By default, the assemblies that you can reference from SQL Server CLR objects are limited. In order to access some of the assemblies we need in order to communicate with WCF, we need to load them into our database. To do this, execute the following query:
Preparing the DB - Points of Interest
You may receive the following warning when creating the assemblies. It is quite ignorable.
Warning: The Microsoft .Net frameworks assembly 'system.servicemodel, version=3.0.0.0,
culture=neutral, publickeytoken=b77a5c561934e089, processorarchitecture=msil.'
you are registering is not fully tested in SQL Server hosted environment.
On one of my test systems (SQL Server 2005 - unpatched), I received various "Out of Memory
" errors when creating the assemblies. There didn't seem to be any good reason for this, and the same problem was not evident on any of my other systems. The solution to the problem? Install SQL Server 2005 SP2.
Create the CLR Objects
You should now see that a Service Reference has been added to our client project and that a file named localhost.map has been created.
- Add a new C# SQL Database Project to the solution called "
ServiceClient
". - Choose or add a reference to your target database (if you are not prompted: right click on your "
ServiceClient
" project, choose properties, Database, Browse, and select your connection). - Add a reference to the service we created:
- Right click the '
Service
' project in Solution Explorer and choose 'Debug' > 'Start New Instance'. - With the service running: right click the '
ServiceClient
' project and choose 'Add Service Reference'. - In 'Service URI', type: http://localhost:8000/services.
- Click OK.
- Add a trigger to the project and name it '
WCFTrigger
'.
using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.Collections;
using System.Diagnostics;
using System.Threading;
public partial class Triggers
{
public static EndpointAddress endpoint =
new EndpointAddress(new Uri("http://localhost:8000/services/myservice"));
public static WSHttpBinding httpBinding = new WSHttpBinding();
public static ServiceClient.localhost.ServiceContractClient myClient =
new ServiceClient.localhost.ServiceContractClient(httpBinding, endpoint);
public delegate void MyDelagate(String crudType);
[SqlProcedure()]
public static void SendData(String crudType)
{
switch (crudType)
{
case "Update":
myClient.UpdateOccured();
break;
case "Insert":
myClient.InsertOccured();
break;
}
}
[Microsoft.SqlServer.Server.SqlTrigger(Name = "WCFTrigger",
Target = "tbCR", Event = "FOR UPDATE, INSERT")]
public static void Trigger1()
{
SqlTriggerContext myContext = SqlContext.TriggerContext;
MyDelagate d;
switch (myContext.TriggerAction)
{
case TriggerAction.Update:
SendData("Update");
break;
case TriggerAction.Insert:
SendData("Insert");
break;
}
}
}
- Replace the trigger code with the following:
Creating the CLR Objects - Points of Interest
The code above creates two objects in the database:
- The Stored Procedure
SendData
is required for making use of the Service Proxy. You cannot reference a service proxy from inside a trigger. To be perfectly honest, I am not sure exactly why this is, but if anyone can shed any light on this, that would be great! SendData
doesn't really do anything fancy, it just calls the correct method on the proxy based on the input parameter. - The Trigger
WCFTrigger
is setup to fire when updates or inserts occur in our table. Again, nothing complicated here, the trigger is used to call the SendData
Stored Procedure with the correct parameters. Two methods for calling the Stored Procedure are shown in the above code: the simple method (commented as the slow method) which is implemented simply calls the Stored Procedure directly. A second option (commented as the fast method) uses a delegate to asynchronously call the Stored Procedure. This helps to improve the performance of the Trigger.
Here are the points of interest:
- In my tests, using the SQL profiler, the delegate based method reduced the time it took a query to complete from 100ms to 8ms!
- DISCLAIMER: I have included the slow (synchronous) method as the default solution in this project for the sake of simplicity. I strongly recommend using the fast (asynchronous) method in any production implementation.
Bringing It All Together
We have now created all the elements required to demonstrate communicating with a WCF service from an SQL Server 2005 CLR Trigger; all that is required now is to bring them together!
- Publish the Service to your database server: right click your '
Service
' project in VS2005 and choose 'Publish
'. Choose a location on the machine running your database (e.g., \\YourDBServer\Samples) and then click 'Finish
'. - Start the Service on your database server: Connect to your database server. Find the Service location you just published to. Double click "Setup.exe". Your service should now start.
- Back on the dev machine: deploy your Trigger and procedure: right click your '
ServiceClient
' in VS2005 and choose 'Deploy
'. - Verify the deployment of the Trigger and procedure using SQL Server Management Studio (make sure you can see them!).
Ready To Go!
Everything should now be ready to go. Run some INSERT
and UPDATE
queries against your test table, and you should see some output in the Service console.