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

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13245정성태2/6/20234955.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/20234353VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20235171디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234630디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20234037디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20234190디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233879디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20236020.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235712.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20235193개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234845개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235932개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20237318오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234979스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20234005오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234384개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20235404.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235528.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20235179개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234855.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20234045개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234491Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234632오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20234331개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234517Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234620오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...