forked from DapperLib/Dapper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlServerTypesLoader.cs
More file actions
57 lines (53 loc) · 2.19 KB
/
SqlServerTypesLoader.cs
File metadata and controls
57 lines (53 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace Dapper.Tests
{
/// <summary>
/// Utility methods related to CLR Types for SQL Server
/// </summary>
internal static class SqlServerTypesLoader
{
private static readonly object _nativeLoadLock = new object();
private static bool _nativeAssembliesLoaded;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr LoadLibrary(string libname);
/// <summary>
/// Loads the required native assemblies for the current architecture (x86 or x64)
/// </summary>
/// <param name="rootApplicationPath">
/// Root path of the current application. Use Server.MapPath(".") for ASP.NET applications
/// and AppDomain.CurrentDomain.BaseDirectory for desktop applications.
/// </param>
public static void LoadNativeAssemblies(string rootApplicationPath)
{
if (_nativeAssembliesLoaded)
return;
lock (_nativeLoadLock)
{
if (!_nativeAssembliesLoaded)
{
var nativeBinaryPath = IntPtr.Size > 4
? Path.Combine(rootApplicationPath, @"x64\")
: Path.Combine(rootApplicationPath, @"x86\");
Console.Write("(from: " + nativeBinaryPath + ")...");
LoadNativeAssembly(nativeBinaryPath, "msvcr120.dll");
LoadNativeAssembly(nativeBinaryPath, "SqlServerSpatial140.dll");
_nativeAssembliesLoaded = true;
}
}
}
private static void LoadNativeAssembly(string nativeBinaryPath, string assemblyName)
{
var path = Path.Combine(nativeBinaryPath, assemblyName);
var ptr = LoadLibrary(path);
if (ptr == IntPtr.Zero)
{
throw new Exception(string.Format(
"Error loading {0} (ErrorCode: {1})",
assemblyName,
Marshal.GetLastWin32Error()));
}
}
}
}