5,702,067 members and growing! (16,132 online)
Email Password   helpLost your password?
Database » Database » SQL Server     Intermediate License: The Code Project Open License (CPOL)

Execute .net code under SQL Server 2005

By Kamal Singh Kharayat

Article describes all the problem and constraints defined to use managed code under SQL Server 2005.
C#, Windows, .NET, Visual Studio, DBA, Dev

Posted: 9 Aug 2007
Updated: 26 Aug 2007
Views: 26,996
Bookmarked: 44 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
32 votes for this Article.
Popularity: 6.13 Rating: 4.07 out of 5
1 vote, 3.1%
1
0 votes, 0.0%
2
2 votes, 6.3%
3
12 votes, 37.5%
4
17 votes, 53.1%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

First of all I would like to congratulate Microsoft Development Team for their superb and innovative technology using which we can use managed code written in any of the .net supported language into Ms SQL Server 2005 Stored Procedure. If I make it simple then "Now you can call any function written in .net class library in your SQL Server stored procedure". This technology will allow us to use the features of .net language with the extendibility of SQL Server.

Description

I got a article of using MSMQ from SQL Server in codeproject written by a gentlemen regarding MSMQ, and Messaging was used from SQL SP. I tried to show the constraints and limitation of using such assemblies and the reguired configuration in SQL Server 2005, so that the developers can start with. And I am sharing the practical problems which I faced in the actual implementation of this.

Before starting you have to enable the managed code execution feature of the SQL Server which is disabled by default. To enable it execute the following code as a query in your SQL Server query editor.

sp_configure 'clr enable', 1
GO
RECONFIGURE
GO

Now your server is ready to run managed code under its runtime. But let me tell you it's not the magic but it's the same technology being used by the .net framework. The only important part is that now SQL Server also is able to execute code on CLR. Isn't it great? Before writing this article I did a lot of Research on this, I got a lot of articles explaining the same. But I faced a lot of problems because things were scattered. Now I am trying to simulate the whole procedure in this article. I did this study because of my specific requirements. I was using Message Queuing Service of Microsoft in C# .net. But after some time I got a requirement in which I need to send a message from Stored Procedure to MSMQ Queue. And till that time for me it was possible by using System. Messaging namespace of .net runtime only. I know most of the developers are wondering about MSMQ. Don't worry I won't go into the details of that right now. We will start with a simple application which will use a simple string returning function of C# .net class library. Let's start with the class library.

? Start .net 2005 studio.
? Open a new class library.
? Select C# as the language.
? Name the project as ManagedCodeAndSQLServer.
? By default you will find a class named Class1.cs created for you.
? Rename it with BaseFunctionClass.cs.

Create a simple function in the class as following:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

namespace ManagedCodeAndSQLServer
{
    public class BaseFunctionClass
    {
        #region "Default Constructor"
        public BaseFunctionClass()
        { 
                   
        }
        #endregion

        #region "Welcome Function"
        /// <summary>
        /// This function will be called from the SQL Stored Procedure.
        /// </summary>
        /// Name
        /// <returns>Welcome Message</returns>
        [SqlProcedure]
        public static void GetMessage(SqlString strName, out SqlString  
        strMessge)
        {
          strMessge = "Welcome," + strName + ", " + "your code is getting
          executed under CLR !";
        }

        #endregion
    }
}

Important Points

I hope you are able to notice some new things in the above code. First of all the [SqlProcedure] attribute on the GetMessage function, this intimates the CLR that the function is callable from SQL Server Stored procedure. The things that I am telling you are my own experiences; you may not found these things on articles published on Internet. When using a CLR function you must remember that the SQL server nvarchar is equivalent to System.String. But the most important part is that "CLR enable procedure can only return Int32, Int and void data types". That's why I have use output parameter with the GetMessage function. Also I have used SqlString instead of System.String. Please keep all the above things in mind.

Now build the project and leave it because your work from the .net class library point of view is over. Now come to your SQL Server again. I hope you still remember that we enabled CLR integration in our server at the start of the article. If not, then don't wait for me to come and enable it.
We have to register ManagedCodeAndSQLServer.dll as an assembly in our Database. To register the assembly you should have owner right in you database or you should be the local system admin or Server Admin. The assebmlies that we are going to register should be registerd in UnSafe mode. Otherwise they would not be able to accesss resources external to SQL Server 2005. And to register an unsafe assembly you sholud have 'unsafe' right enable in your username or role. All the above things are very important so take care of it, otherwise you won't be able to register your assembly. So create a database 'TestingCLR'. Before registering the .net assembly in the Database you have to set the trust worthy option of the database on using the following code:

ALTER DATABASE TestingCLR SET TRUSTWORTHY ON
GO

Now Register ManagedCodeAndSQLServer.dll under that using the following code:

CREATE ASSEMBLY ManagedCodeAndSQLServer
AUTHORIZATION dbo
FROM 'E:\Important\SQL\ManagedCodeAndSQLServer\ManagedCodeAndSQLServer\bin\
Debug\ManagedCodeAndSQLServer.dll'
WITH PERMISSION_SET = UNSAFE
GO


I am again saying if the dbo is not having 'unsafe assembly' right it won't work. Similarly if I am using specific class of .net in my dll I have to register it prior to dll registration in the same way. For example I am using System.Messaging in my assemly, then I have to register it using the following code:

CREATE ASSEMBLY Messaging
AUTHORIZATION dbo
FROM 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Messaging.dll'
WITH PERMISSION_SET = UNSAFE
GO

To use the normal functionality we need not to registered dll from .net runtime as in our case Now in your server explorer, go to your TestingCLR database, select Programmability and in Assemblies you will find an assembly registered with the name given by you i.e., "HelloDotNet". Now you are almost done. You should know the full path (namespace convention) of the function that you are going to use from that assembly. In our case it is: ManagedCodeAndSQLServer.BaseFunctionClass and GetMessage is our function to be used. Now I am creating a simple Stored Procedure to use this assebmly as following:

CREATE PROCEDURE usp_UseHelloDotNetAssembly
@name nvarchar(200),
@msg nvarchar(MAX)OUTPUT
AS EXTERNAL NAME ManagedCodeAndSQLServer.[ManagedCodeAndSQLServer.
BaseFunctionClass].GetMessage
GO

To execute the Procedure:

DECLARE @msg varchar(MAX)
EXEC usp_UseHelloDotNetAssembly 'Kittu And Tannu',@msg output
PRINT @msg

You will get the following output: Welcome,Kittu And Tannu, your code is getting executed under CLR !

Try it and enjoy…….. TC……

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Kamal Singh Kharayat


Hi, I hold Bachelor and Master in Computer Application. As a habit of learning I always use to learn new technologies. I own keen interest in self learning, specially in Microsoft .net technologies. In sports, I like to play Soccer. I own 2 year of Software Development experience in .net technologies.
Also I have an experience of more than 1 years as a Technical Trainer for .net technologies in various IT Companies. Also I own 1 year of Software Development experience.
Currently I am working as a Senior Software Engineer with: "Gateway Technolabs Private Limited", Ahmedabad, INDIA.

"Improvement is the only thing which makes me happy...."
e-mail Addresses:
kamal.singh@gatewaytechnolabs.com
kamalkharayat@gmail.com
Occupation: Web Developer
Location: India India

Other popular Database articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 14 of 14 (Total in Forum: 14) (Refresh)FirstPrevNext
Generalnice articalmembermhemal19:37 2 Sep '07  
GeneralEnable CLRmemberkurisutofuJP16:27 26 Aug '07  
QuestionError in naming?memberkurisutofuJP16:22 26 Aug '07  
AnswerRe: Error in naming?memberKamal Singh D. Kharayat19:24 26 Aug '07  
GeneralRe: Error in naming?memberkurisutofuJP20:03 26 Aug '07  
GeneralThanx!! Had not known this functionality of SQL server...membernishantsagar8323:32 17 Aug '07  
QuestionInteresting article but a few questionsmemberJon Masters0:08 15 Aug '07  
AnswerRe: Interesting article but a few questionsmemberKamal Singh D. Kharayat21:29 15 Aug '07  
GeneralRe: Interesting article but a few questionsmemberJon Masters0:01 16 Aug '07  
GeneralRe: Interesting article but a few questionsmemberKamal Singh D. Kharayat0:43 16 Aug '07  
GeneralRe: Interesting article but a few questionsmemberJon Masters1:08 16 Aug '07  
GeneralExcellent!!!!!!!!!!!!!!!memberRashmi Patel RJ4:06 14 Aug '07  
GeneralVery Help Fullmembersneharahul2:55 14 Aug '07  
GeneralInterestingmemberlallous22:37 13 Aug '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 26 Aug 2007
Editor:
Copyright 2007 by Kamal Singh Kharayat
Everything else Copyright © CodeProject, 1999-2008
Web20 | Advertise on the Code Project