0

I have made a CLR by using SQL Project Templates into Visual studio using language C# as::

  [Microsoft.SqlServer.Server.SqlFunction()]
    public static SqlDateTime ScalarUDF(SqlInt64 CompanyID)
    {
        SqlInt64 temp = CompanyID;
        string zoneId = "Singapore Standard Time";
        TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
        DateTime result = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi);

        return new SqlDateTime(result);
    }

And also created the UDF into SQL using query::

-- Install Assembly
CREATE ASSEMBLY UDF_Trial FROM 'C:\Users\Rahul\Documents\visual studio 2013\Projects\UDF_Trial\UDF_Trial\bin\Debug\UDF_Trial.dll'
GO
-- Create ScalarUDF
CREATE FUNCTION [dbo].[ScalarUDF](@CompanyID bigint)
RETURNS datetime
WITH EXECUTE AS CALLER
AS
EXTERNAL NAME UDF_Trial.UserDefinedFunctions.ScalarUDF;
GO

But while Executing the UDF I am gettin some Error:

I am executing UDF as,

select [dbo].[ScalarUDF](15)

But Getting the Exception as::

Msg 6522, Level 16, State 2, Line 2
A .NET Framework error occurred during execution of user-defined routine or aggregate "ScalarUDF": 
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.ScalarUDF(SqlInt64 CompanyID)
.

I have also made the Permission to UNSAFE at the time of creating Assembly as::

CREATE ASSEMBLY UDF_Trial FROM 'C:\Users\Rahul\Desktop\pro_temp\UDF_Trial.dll' WITH PERMISSION_SET = UNSAFE; GO

but in this case I am getting Error as::

CREATE ASSEMBLY for assembly 'UDF_Trial' failed because assembly 'UDF_Trial' is not authorized for PERMISSION_SET = UNSAFE.  The assembly is authorized when either of the following is true: the database owner (DBO) has UNSAFE ASSEMBLY permission and the database has the TRUSTWORTHY database property on; or the assembly is signed with a certificate or an asymmetric key that has a corresponding login with UNSAFE ASSEMBLY permission.
3

1 Answer 1

3

I have set the Trustworthy of the Database to ON as::

ALTER DATABASE Learn SET TRUSTWORTHY ON

and have created Assembly as ::

CREATE ASSEMBLY UDF_Blog FROM 'C:\Users\Rahul\Documents\visual studio 2013\Projects\UDF_Trial\UDF_Trial\bin\Debug\UDF_Trial.dll'
WITH PERMISSION_SET = UNSAFE;
GO

and the Problem is solved.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.