Showing posts with label clr. Show all posts
Showing posts with label clr. Show all posts

Thursday, March 22, 2012

Error deploying managed stored proc

When I try to deploy this managed stored proc assembly on SQL Server 2005 I get this error:

Failed to initialize the Common Language Runtime (CLR) v2.0.50727 with HRESULT 0x8007000e. You may fix the problem and try again later

I looked on the net but found no documentation about it. I know the CLR v2.0 is working as I have some ASP.NET apps running from this server that use it. Any ideas?

Try the simple code to get a .dll file:

using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure()]
public static void SampleSP(string connstring, out int spid)
{
using (SqlConnection conn = new SqlConnection(connstring))
{
conn.Open();

SqlCommand cmd = new SqlCommand("SELECT @.@.SPID", conn);
spid = (System.Int16)cmd.ExecuteScalar();
}
}
}

And then let's manually create assmebly from the dll file in Management Studio:

1. Login to SQL2005 as 'sa', locate a database->new query->execute following command:

alter database yourdb set trustworthy on

go

sp_configure 'clr enabled',1
reconfigure with override

go

2. create an assembly from the dll file

3. create a stored procedure which references the assembly:

create procedure testCLR @.conn nvarchar(max),@.i int output as
external name ClassLibrary2.[StoredProcedures].SampleSP

4. Test the procedure:

declare @.i int

exec testCLR 'Data Source=.;Integrated Security=SSPI;Database=master',@.i output

select @.i

And here is a good torturial for using CLR in SQL2005:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsql90/html/mandataaccess.asp

Error deploying a CLR Stored Procedure that uses a web service

Ok, first some background.

I am writing my first (complex) CLR Stored Procedure using Visual Studio 2005.

This SP worked fine until I added code to make a web service call. That web service is a wrapper web service I created because the actual web service I need to call uses System. Web.Extensions which was not available in my VS2005 Database Project.

At first I was getting the standard "External Access Assembly" errors, so I created a new user (was using SA) and assigned database ownership to the new user, then assigned permissions to that user. This worked to get it deployed, but I get the following error when its run:

<code>

System.InvalidOperationException: Cannot load dynamically generated serialization assembly. In some hosting environments assembly load functionality is restricted, consider using pre-generated serializer. Please see inner exception for more information. > System.IO.FileLoadException: LoadFrom(), LoadFile(), Load(byte[]) and LoadModule() have been disabled by the host.

System.IO.FileLoadException:

at System.Reflection.Assembly.nLoadImage(Byte[] rawAssembly, Byte[] rawSymbolStore, Evidence evidence, StackCrawlMark& stackMark, Boolean fIntrospection)

at System.Reflection.Assembly.Load(Byte[] rawAssembly, Byte[] rawSymbolStore, Evidence securityEvidence)

at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)

at Microsoft.CSharp.CSharpCodeGenerator.FromSourceBatch(CompilerParameters options, String[] sources)

at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, String[] sources)

at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(CompilerParameters options, S

</code>

Anyone have any ideas?

Thanks!

Dave Borneman

Solution Architect,

anyWare Mobile Solutions.

OK, so when you are using Web services the .NET framework will dynamically generate an assembly based on your proxy code. Dynamic assembly generation is not allowed inside SQL Server (SQLCLR).

What you need to do is to pre-generate the proxy assembly by using the sgen tool and deploy that generated assembly into the database.

Look at this thread: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=74480&SiteID=1 and specifically the 6:th message in that thread how to achieve the pre-generation.

Niels

Monday, March 19, 2012

Error Creating CLR UDF

Hi:

I am trying to create a CLR UDF in SQL 2005 and cosnistently run into the following error. What am I doing wrong?. Please correct me and show me the right way of doing this.

Msg 6551, Level 16, State 2, Procedure EmailSplitter, Line 3

CREATE FUNCTION for "EmailSplitter" failed because T-SQL and CLR types for return value do not match.

Here is what I am trying to achieve. Split a Email field in the database. For that I am trying to return an array using C# and then trying to call the UDF for the C#.

--1).CLR Code. (EmailSpitter.cs)

using System;
using System.Collections.Generic;
using System.Text;

namespace SQLTools
{
public class EmailSplitter
{
public static string[] Parse(string data)
{
string[] columnData;
string[] separators = new string[1];
separators[0] = " ";

if (data != null)
{
columnData = data.Split(separators, StringSplitOptions.None);
return columnData;
}
return null;
}
}
}

--2). Assembly code.

CREATE Assembly SQLArrayBuilder

FROM 'E:\CLR\EmailSplitter\bin\Debug\EmailSplitter.dll'

WITH PERMISSION_SET=SAFE

Select * from sys.assemblies.

--3). Create the function.

CREATE Function dbo.EmailSplitter

(@.EmailString NVARCHAR(4000))

RETURNS VARCHAR(4000)

AS

EXTERNAL NAME SQLArrayBuilder.[SQLTools.EmailSplitter].Parse

Run into the error:

Msg 6551, Level 16, State 2, Procedure EmailSplitter, Line 3

CREATE FUNCTION for "EmailSplitter" failed because T-SQL and CLR types for return value do not match.

Please help me.

Thank you very much.

AK

Your CREATE FUNCTION returns a string, but your CLR function returns an array of strings, that is why you are getting an error. If you want to return an array of strings you will have to create a CLR function that returns an IEnumerable object and define a table valued function in T-SQL. Look up CLR table valued functions in the BOL for the details.

Dan

Error create a second independent transaction inside a CLR stored procedure?

I use the context connection for the "normal" work in the CLR procedure.
But I need to commit some data in every case. So I need to create a second transaction which is independent from the calling transaction.

What is the best way to do this inside a CLR procedure?

Thanx a lot

Hi!

Create another connection to the server and create a transaction on this second connection. Please note that since your main connection is inproc (“context connection=true” in the connection string), the second connection should be non-inproc (network. Of cause, you can connect to the same server.).

|||Thank you,

I tried this already. But I got an error when I call BeginTransaction on the second connection. When I remember correctly it as "Transcation already in use by another session". I call the procedure from t-sql inside a begin tran block

Any idea about that?

I will try to build a small example an post it here.|||

Hello,
I made a small example to reproduce the error.

CLR procedure
<Microsoft.SqlServer.Server.SqlProcedure()> _

Public Shared Sub Test(ByVal sConnectString As String)

Dim t As SqlClient.SqlTransaction = Nothing

Dim c As SqlClient.SqlConnection = Nothing

c = New SqlClient.SqlConnection(sConnectString)

c.Open()

t = c.BeginTransaction()

t.Commit()

c.Close()

End Sub

T-SQL caller:
begin tran
execute Test 'Server=(local);database=cpwerx;user Id=sa;password=xyz'
commit tran

Error:
A .NET Framework error occurred during execution of user defined routine or aggregate 'Cas':
System.Data.SqlClient.SqlException: Transaction context in use by another session.
System.Data.SqlClient.SqlException:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.TdsExecuteTransactionManagerRequest(Byte[] buffer, TransactionManagerRequestType request, String transactionName, TransactionManagerIsolationLevel isoLevel, Int32 timeout, SqlInternalTransaction transaction, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlInternalConnectionTds.PropagateTransactionCookie(Byte[] cookie)
at System.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction tx)
at System.Data.SqlClient.SqlInternalConnection.Enlist(Transaction tx)
at System.Data.SqlClient.SqlInternalConnectionTds.Activate(Transaction transaction)
at System.Data.ProviderBase.DbConnectionInternal.ActivateConnection(Transaction transaction)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()

|||

Hi!

Modify your connection string so that it has "Enlist=false" in it. Otherwise the connection inherits current transaction.

More on "Enlist" option is in doc on SqlConnection.ConnectionString property

|||

Than you!

We've been stuck for a week. We had a .Net CLR stored procedure that worked locally but, failed when invoked remotely. That connection string setting is exactly what we needed.

-Joe

Wednesday, February 15, 2012

Error adding Assembly to SQL 2005

I have a clr assembly that access the internet via Sockets and file access. This require me to set the Assembly permissions level to External.

There are lots of messages on the net regarding this issue. none have worked for me.

Currently I'm trying to install the assembly with "sign the assembly" checked, createing a strong name key file.

When I run the installation I get the following message from the server

"Create failed for SqlAssembly 'xxx'.(Microsoft.sqlServer.Smo)

an exception occured while executing a Transact-SQL statement or batch

(Microsoft.SqlServer.ConnectionInfo)

A severe error occured in the current command. The results, if any, should be discarded.

This is the messag I get.

The following link does not display any usefull information.

TITLE: Microsoft SQL Server Management Studio

Create failed for SqlAssembly 'KBTTriggers'. (Microsoft.SqlServer.Smo)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=9.00.1399.00&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Create+SqlAssembly&LinkId=20476


ADDITIONAL INFORMATION:

An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)

A severe error occurred on the current command. The results, if any, should be discarded.
A severe error occurred on the current command. The results, if any, should be discarded. (Microsoft SQL Server, Error: 0)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=0&LinkId=20476


BUTTONS:

OK

Hi,

I am getting the same error. Anyone please help me out on this issue.

Thanks,

Arun

|||

I resolved this issue.

please refer the link for more details:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=194501&SiteID=1

Error adding Assembly to SQL 2005

I have a clr assembly that access the internet via Sockets and file access. This require me to set the Assembly permissions level to External.

There are lots of messages on the net regarding this issue. none have worked for me.

Currently I'm trying to install the assembly with "sign the assembly" checked, createing a strong name key file.

When I run the installation I get the following message from the server

"Create failed for SqlAssembly 'xxx'.(Microsoft.sqlServer.Smo)

an exception occured while executing a Transact-SQL statement or batch

(Microsoft.SqlServer.ConnectionInfo)

A severe error occured in the current command. The results, if any, should be discarded.

This is the messag I get.

The following link does not display any usefull information.

TITLE: Microsoft SQL Server Management Studio

Create failed for SqlAssembly 'KBTTriggers'. (Microsoft.SqlServer.Smo)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=9.00.1399.00&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Create+SqlAssembly&LinkId=20476


ADDITIONAL INFORMATION:

An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)

A severe error occurred on the current command. The results, if any, should be discarded.
A severe error occurred on the current command. The results, if any, should be discarded. (Microsoft SQL Server, Error: 0)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=0&LinkId=20476


BUTTONS:

OK

Hi,

I am getting the same error. Anyone please help me out on this issue.

Thanks,

Arun

|||

I resolved this issue.

please refer the link for more details:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=194501&SiteID=1