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)
13372정성태6/15/20233361개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233472개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233615개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233425개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233575개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233747오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233506.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20233175오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20234049.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233610스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233578.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233925오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233267오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233589오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20234056.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233882.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20234208DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20234127.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234268.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233961.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234428VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233724오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20234069.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233963.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234346.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20234192오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...