I tried to write a CLR stored procedure using C# in SQL 2005 to access an Access
database.
When I use the OleDbConnection class in System.Data, the procedure throws SecurityException at runtime.
Output as following:
System.Security.SecurityException: Request for the permission of type 'System.Data.OleDb.OleDbPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.PermissionSet.Demand()
at System.Data.Common.DbConnectionOptions.DemandPermission()
at System.Data.OleDb.OleDbConnection.PermissionDemand()
at System.Data.OleDb.OleDbConnectionFactory.PermissionDemand(DbConnection outerConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.OleDb.OleDbConnection.Open()
at Dbbest.Data.BulkStuff.bulkcopy(String source_oledb_connection_string, String source_table, String destination_table, Int32 batchSize, Int32 notifyAfter)
The action that failed was:
Demand
The type of the first permission that failed was:
System.Data.OleDb.OleDbPermission
The Zone of the assembly that failed was:
MyComputer
Hello Va1era,
The exception you encountered indicates that the C# assembly containing the stored procedure that you registered has insufficient permissions to create an OleDbConnection object, with respect to the .Net framework Code Access Security (CAS) policies. This probably means that your assembly was registered WITH PERMISSION_SET = SAFE, which is also the default if PERMISSION_SET is unspecified in the CREATE ASSEMBLY DDL statement.
To fix this, you can re-register your assembly WITH PERMISSION_SET = EXTERNAL_ACCESS to gain access to the ADO.Net classes (including OleDbConnection). If you are using Visual Studio, you will have to make this change from SAFE to EXTERNAL_ACCESS in the properties page of your C# database project.
To understand more about the CAS security permission buckets in SQL Server's hosted CLR (SAFE, EXTERNAL_ACCESS and UNSAFE), you can look at this document: http://bordecal.mvps.org/Nicole/SqlClrCas/SqlClrCasSpeculations.htm. Also, here is the MSDN page on CAS and ADO.Net 2.0: http://msdn2.microsoft.com/en-us/library/0x4t63kb.aspx
Hope this helps.
Thanks,
Ravi