Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

Microsoft.SqlServer.Types.SqlGeography 형변환 시 null 반환하는 문제

SQL Server 2008부터 SqlGeography 타입이 지원됩니다. 저도 그동안 쓸 일이 없다가 최근에야 사용해 보았는데요. SqlGeography 타입의 컬럼을 SELECT하고 DataReader에서 값을 읽어 SqlGeoGraphy로 형변환을 하는데,

object data = reader.GetValue("Location"); // not null
SqlGeography geoData = data as SqlGeography; // null

geoData 변수의 값이 null이 나왔습니다. 이상하군요. Visual Studio 디버거로 data 변수를 살펴보면 정상적으로 Microsoft.SqlServer.Types.SqlGeography를 가리켰습니다.

geography_is_null_1.png

하지만, Watch 창에 "data as SqlGeoGraphy"라고 입력했더니 다음과 같이 형변환이 안되었습니다.

geography_is_null_2.png

The type 'Microsoft.SqlServer.Types.SqlGeography' exists in both 'Microsoft.SqlServer.Types.dll' and 'Microsoft.SqlServer.Types.dll'


그래도 메시지에 원인이 나왔습니다. Visual Studio의 "Modules" 창을 통해 확인해 보면 Microsoft.SqlServer.Types.dll 어셈블리가 10.0.0.0, 12.0.0.0 버전으로 2개 로드된 것을 볼 수 있습니다.

geography_is_null_3.png

문제를 분석하니 다음과 같은 동작을 확인할 수 있었습니다.

  1. SQL 쿼리 실행 시 SQL 서버로부터 12.0.0.0 Microsoft.SqlServer.Types.dll 버전의 SqlGeography 타입이 반환됨.
  2. 코드에서 "data as SqlGeography" 형변환시 GAC로부터 10.0.0.0 버전의 Microsoft.SqlServer.Types.dll 어셈블리가 로드됨

결정적인 원인은 밝혀졌지만 상황이 더욱 재미있어졌습니다. ^^ 왜냐하면 제 C# 프로젝트는 12.0.0.0 버전의 Microsoft.SqlServer.Types.dll을 참조하고 있기 때문이었습니다.

그런데, 왜? 코드 수행 시 10.0.0.0 버전이 로드된 것일까요? 원인을 찾아보니, 제 C# 프로젝트는 .NET 4.0 대상이었고, C:\Windows\Microsoft.NET\assembly\GAC_MSIL 경로의 .NET 4.0 GAC 저장소에는 12.0.0.0 버전의 Microsoft.SqlServer.Types.dll이 등록이 안되어 있었습니다. 대신 .NET 2.0 GAC(C:\Windows\assembly) 저장소에는 10.0.0.0, 11.0.0.0, 12.0.0.0이 모두 등록되어 있었는데 그중에서 10.0 버전이 선택된 것입니다.

그래도 이상하군요. 분명히 프로젝트 참조에서 12.0.0.0을 지정했는데, .NET 4.0 GAC 대신 .NET 2.0 GAC가 선택되면서 낮은 버전의 어셈블리가 로드된 것입니다. (이 부분은 나중에 한번 더 테스트를 해봐야겠습니다.)




어쨌든 현상이 그렇기 때문에 해결을 해야 하는데요. 이에 대해서는 다음의 글에 나와 있습니다.

Breaking Changes to Database Engine Features in SQL Server 2012
; https://docs.microsoft.com/en-us/sql/database-engine/breaking-changes-to-database-engine-features-in-sql-server-2016

2가지 방법이 나오는데요. 하나는 .NET 4.5 부터 지원된다고 하는 SQL ConnectionString의 "Type System Version" 속성을 지정하는 것이 있고, 두번째는 app.config에 다음과 같은 바인딩 정보를 추가해 주는 것입니다.

<dependentAssembly>
    <assemblyIdentity name="Microsoft.SqlServer.Types" publicKeyToken="89845dcd8080cc91" culture="neutral" />
    <bindingRedirect oldVersion="10.0.0.0-11.0.0.0" newVersion="12.0.0.0" />
</dependentAssembly>

그런데, 이것이 정말 최선일까요? ^^ 만약 SQL 서버 관리자가 데이터베이스를 (향후 미래의) SQL Server 2016으로 마이그레이션했다고 가정하면 그 때는 다시 13.0.0.0 버전의 Microsoft.SqlServer.Types.dll에 있는 SqlGeography 타입이 직렬화되어 응용 프로그램에 전달될 것이고 이로 인해 응용 프로그램은 어느 날 갑자기 동작하지 않게 될 것입니다. 물론, app.config에 bindingRedirect 정보를 변경하는 것으로 간단하게 해결은 할 수 있겠지만, 현실적으로 이런 오류는 잡기까지 시간이 걸립니다.

그래서 제가 추천하는 3번째 방법이 있습니다. 바로 dynamic 예약어를 사용하는 것!

object data = reader.GetValue("Location"); // not null
if (data == null)
{
    return;
}

dynamic geoData = data;

double lat = geoData.Lat.Value;
double long = geoData.Long.Value;

오~~~ 멋지죠! ^^ 예전 같으면 복잡하게 .NET Reflection으로 해결해야 하지만, 이제는 dynamic이 있어 좀 더 깔끔한 해결책이 나옵니다.




Microsoft.SqlServer.Types.dll 어셈블리를 사용한 경우 다른 컴퓨터에 배포한다면 (SQL 서버를 설치하지 않으면 없기 때문에) 꼭 함께 배포해야 합니다. 아니면 해당 어셈블리에 포함된 타입을 사용한 메서드가 실행되는 순간 예외가 발생합니다.

System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.SqlServer.Types, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.SqlServer.Types, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'
at TesteLib.Place.GetByRadius(String center, String southWest, String northEast)
at TesteWebApp.PlaceController.Get(String center, String southWest, String northEast)

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].


그런데, Web API에 실어서 서비스를 하니 웹 브라우저 종단에는 "500 (Internal Server Error)"가 떨어졌습니다. 에러 잡기 힘들군요. ^^ 암튼 Microsoft.SqlServer.Types 어셈블리를 사용하면 꼭 참조에 "Copy Local" 옵션을 "True"로 해주는 것이 좋겠습니다. ^^




Microsoft.SqlServer.Types.dll 어셈블리 배포만으로 안 끝나는군요. ^^ 이어서 다음과 같은 오류도 발생합니다.

System.DllNotFoundException: Unable to load DLL 'SqlServerSpatial120.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) 
    at Microsoft.SqlServer.Types.GLNativeMethods.GeodeticPointDistance(Point p1, Point p2, EllipsoidParameters ep) 
    at Microsoft.SqlServer.Types.SqlGeography.STDistance(SqlGeography other) 
    at TesteLib.Place.GetByRadius(String center, String southWest, String northEast) 
    at TesteWebApp.PlaceController.Get(String center, String southWest, String northEast) 

SqlServerSpatial120.dll은 Native 모듈인데 이 때문에 아쉽게도 x86/x64로 나뉘게 됩니다. 그래도 요즘엔 대개의 경우 x64로 작업하기 때문에 64비트 SqlServerSpatial120.dll을 프로젝트 파일에 추가한 다음 "Copy to Output Directory"을 True로 설정해 주시면 됩니다.

[1156] System.IO.FileLoadException: Could not load file or assembly 'Microsoft.SqlServer.Types, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
[1156] File name: 'Microsoft.SqlServer.Types, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'
[1156] at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
[1156] at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
[1156] at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
[1156] at System.Data.SqlClient.SqlConnection.ResolveTypeAssembly(AssemblyName asmRef, Boolean throwOnError)
[1156] at System.TypeNameParser.ResolveAssembly(String asmName, Func`2 assemblyResolver, Boolean throwOnError, StackCrawlMark& stackMark)
[1156] at System.TypeNameParser.ConstructType(Func`2 assemblyResolver, Func`4 typeResolver, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark)
[1156] at System.TypeNameParser.GetType(String typeName, Func`2 assemblyResolver, Func`4 typeResolver, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark)
[1156] at System.Type.GetType(String typeName, Func`2 assemblyResolver, Func`4 typeResolver, Boolean throwOnError)
[1156] at System.Data.SqlClient.SqlConnection.CheckGetExtendedUDTInfo(SqlMetaDataPriv metaData, Boolean fThrow)
[1156] at System.Data.SqlClient.SqlDataReader.GetValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData metaData)
[1156] at System.Data.SqlClient.SqlDataReader.GetValue(Int32 i)
[1156] at SysnetLib.Dac.KnownPlaceDac.<.cctor>b__0(IDataReader reader, Dictionary`2 ordinal)
[1156] at Sysnet.Framework.DacBase.FillToObjectList(String query, IDbDataParameter[] parameters, ReaderMapper functor, IList list, Boolean cacheOrdinalTable)
[1156] at SysnetLib.Dac.KnownPlaceDac.GetByRadius(Int32 level, SqlGeography center, Double meters)
[1156] at SysnetLib.Biz.KnownPlace_NTx.GetByRadius(Int32 level, String center, String southWest, String northEast)
[1156] at SysnetWebApp.heyri.KnownPlaceController.Get(Int32 level, String center, String southWest, String northEast)


이에 대해 검색해 보면 다음의 글이 나옵니다.

Microsoft.SqlServer.Types NuGet Package (Spatial on Azure)
; http://blogs.msdn.com/b/adonet/archive/2013/12/09/microsoft-sqlserver-types-nuget-package-spatial-on-azure.aspx

PM> Install-Package Microsoft.SqlServer.Types

아하~~~ 마이크로소프트에서도 Azure에서의 문제를 인식하고 NuGet 패키지를 배포하고 있었군요. ^^ 그래도 저는 그냥 간단하게 프로젝트 추가하고 bin 폴더에 내보내도록 구성을 해서 완료했습니다.




참고로, dynamic 예약어 사용시 다음과 같은 컴파일 오류가 발생한다면?

One or more types required to compile a dynamic expression cannot be found. Are you missing a reference?

Predefined type 'Microsoft.CSharp.RuntimeBinder.Binder' is not defined or imported

다음의 해결책을 참고하시면 됩니다.

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?
; http://stackoverflow.com/questions/11725514/one-or-more-types-required-to-compile-a-dynamic-expression-cannot-be-found-are

즉, "Microsoft.CSharp.dll" 어셈블리를 새롭게 참조하시면 됩니다.





[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 7/17/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13611정성태4/29/2024145닷넷: 2252. C# - GUID 타입 전용의 UnmanagedType.LPStruct - 두 번째 이야기파일 다운로드1
13610정성태4/28/2024246닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/2024268닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/2024507닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/2024753닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024847닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024900닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024925오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024990닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024991닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/20241011닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/20241022닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024955닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/20241003닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/20241008닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241126닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241077닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241102닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241097닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241239C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241212닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241092Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241199닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241566닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241403오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...