In order to call a webservice, I’ve created a DLL in C# .NET 2.0 .
After registering the DLL in SQL Server 2008 R2, I tried, in this DLL, to retreive its directory in order to load a configuration file.
The problem is all methods I found on Google doesn’t work, and it’s a problem because I can’t load the file. I don’t want put some “hard paths” in my code, because it can change depending of the environment.
There is how I register my dll in SQL Server 2008 :
DROP FUNCTION [Tools].[CallWriteDepot]
GO
DROP FUNCTION [Tools].[CallExtractDepot]
GO
drop assembly SqlAssembly
go
create assembly SqlAssembly
from 'C:\webservices\dll\SqlAssembly.dll'
with permission_set = unsafe
go
---------------------------------------------------------------------------------------------------
CREATE FUNCTION [Tools].[CallWriteDepot](@xmlInputFile [nvarchar](max))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [SqlAssembly].[SqlAssembly.Main].[writeToSafe]
GO
---------------------------------------------------------------------------------------------------
CREATE FUNCTION [Tools].[CallExtractDepot](@xmlInputFile [nvarchar](max))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [SqlAssembly].[SqlAssembly.Main].[readFromSafe]
GO
As you see, the DLL is in C:\webservices\dll\SqlAssembly.dll and it is impossible to find this path in the DLL code, as you can see below.
There is the result after few tests :
Assembly.GetAssembly(typeof(SqlAssembly.Main)).CodeBase
Result : empty
attrTest2.Value = Assembly.GetAssembly(typeof(SqlAssembly.Main)).Location
Result : empty
Assembly.GetCallingAssembly().Location
Result : C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn\SqlAccess.dll
Assembly.GetCallingAssembly().GetName().CodeBase
Result : file:///C:/Program Files/Microsoft SQL Server/MSSQL10_50.MSSQLSERVER/MSSQL/Binn/SqlAccess.DLL
Assembly.GetExecutingAssembly().Location
Result : empty
Assembly.GetExecutingAssembly().GetName().CodeBase
Result : empty
Directory.GetCurrentDirectory();
Result : C:\Windows\system32
AppDomain.CurrentDomain.BaseDirectory;
Result : C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn\
Environment.CurrentDirectory;
Result : C:\Windows\system32
If anybody knows how SQL Server register a DLL function ? It’s like it save the function in a memory zone and don’t read the dll file anymore.
If anybody have the solution too 😉
When you create an assembly in SQL Server the binary code of the dll is loaded into SQL Server. You can find it in
sys.assembly_files. The dll used to create the assembly is not used when you execute functions in the assembly.A possible solution to your problem could be to have an
.inifile that contains the path to the configuration file. Just make sure you put your.inifile in a place you can find it through thepathenvironment variable.