I think this may be the same as This Issue
I have also referenced it but still not able to get the solution of my problem. This is the first time I am creating any CLR and getting problem.
I have delveloped a CLR into C# as::
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlDateTime GetTimeForCompanyID(SqlInt64 CompanyID)
{
string strZoneID;
string connStr = @"data source=.;initial catalog=dbName;Integrated Security=SSPI;user id=RJ;password=RJ@123;enlist=false;";
using (SqlConnection connection = new SqlConnection(connStr))
{
connection.Open();
using (SqlCommand select = new SqlCommand(
"select SettingValue from CompanySetting where CompanyID="+CompanyID+" and Setting='TimeZone'",
connection))
{
using (SqlDataReader reader = select.ExecuteReader())
{
strZoneID = reader.GetString(0);
}
}
}
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(strZoneID);
DateTime result = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi);
SqlDateTime Final = result;
return Final;
}
}
and the creation of Assembly into SQL is as::
1) I have created the Assembly Key
first into master database as::
use master
CREATE ASYMMETRIC KEY MyDllKey FROM EXECUTABLE FILE = 'C:\Temp\CueBusinessFunctions.dll'
CREATE LOGIN MyDllLogin FROM ASYMMETRIC KEY MyDllKey
GRANT EXTERNAL ACCESS ASSEMBLY TO MyDllLogin
2) Created the Assembly as::
use Learn
CREATE ASSEMBLY CueBusinessFunctions FROM 'C:\Projects\CueBusinessFunctions.dll'
WITH PERMISSION_SET = EXTERNAL_ACCESS
GO
3) Creating CLR UDF as::
CREATE FUNCTION [dbo].[GetTimeForCompanyID](@CompanyID bigint)
RETURNS datetime
WITH EXECUTE AS CALLER
AS
EXTERNAL NAME CueBusinessFunctions.UserDefinedFunctions.GetTimeForCompanyID;
GO
But the Problem is when executing the UDF as::
select [dbo].[GetTimeForCompanyID](1)
I am getting the Error as::
Msg 6522, Level 16, State 1, Line 2
A .NET Framework error occurred during execution of user-defined routine or aggregate "GetTimeForCompanyID":
System.Security.HostProtectionException: Attempted to perform an operation that was forbidden by the CLR host.
The protected resources (only available with full trust) were: All
The demanded resources were: MayLeakOnAbort
System.Security.HostProtectionException:
at UserDefinedFunctions.GetTimeForCompanyID(SqlInt64 CompanyID)
.