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)
13321정성태4/14/20234102개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233994개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234499개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20234383개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234419오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233688오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233983Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20234123개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20234130개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20234201Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234638C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20234295C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234416.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20234335스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20234093.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
13306정성태4/3/20233975Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
13305정성태4/1/20234338Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전)파일 다운로드1
13304정성태3/31/20234635VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/20233983Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/20234587Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/20234696Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션파일 다운로드1
13300정성태3/28/20234412Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/20234158Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/20234129Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234719Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20234099Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...