Skip to content

Implement SqlGeography and SqlGeometry for Spatial Types support for .Net Core #30

Closed

Description

@ststeiger

Cannot run Microsoft.SqlServer.Types because \Microsoft.SqlServer.Server\IBinarySerialize.cs is missing in System.Data.

Since no source code is available, and contact owners on nuget yields a HTTP-500, I'm opening an issue here. I'd like to compute a polygon union...

#if false
namespace AnySqlWebAdmin
{
    public class GeoPoint
    {
        public decimal Lat;
        public decimal Long;
        public GeoPoint(decimal latitude, decimal longitude)
        {
            this.Lat = latitude;
            this.Long = longitude;
        }
        public GeoPoint() : this(0,0) { }
        public override string ToString()
        {
            return this.Lat.ToString(System.Globalization.CultureInfo.InvariantCulture)
                + " "
                + this.Long.ToString(System.Globalization.CultureInfo.InvariantCulture);
        }
    }
    public class GeographicOperations 
    {
        public static string ObjJoin(string separator, params object[] objs)
        {
            string result = null;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            
            bool isNotFirst = false;
            
            for (int i = 0; i < objs.Length; ++i)
            {
                if (objs[i] == null)
                    continue;
                if (separator != null && isNotFirst)
                {
                    sb.Append(separator);
                }
                else
                    isNotFirst = true;
                
                if(objs[i] != null)
                    sb.Append(objs[i].ToString());
            }
            
            result = sb.ToString();
            sb.Clear();
            sb = null;
            
            return result;
        }
        // geography::STPolyFromText('POLYGON((9.3763619 47.4330074,9.3764389 47.4329684,9.3764072 47.4329405,9.3763969 47.4329322,9.3759864 47.4326004,9.376056 47.4325644,9.3761349 47.4325167,9.37619 47.4325653,9.376312 47.4326732,9.3765907 47.4328683,9.3766389 47.4328521,9.3767794 47.4329452,9.3764748 47.4331106,9.3763619 47.4330074))', 4326)
        // geography::STPolyFromText('POLYGON((9.3766833 47.4319973,9.3772045 47.4324131,9.3771257 47.432459,9.3769959 47.4323535,9.3767225 47.4325076,9.3768938 47.432637,9.3769843 47.4325975,9.3772713 47.432826,9.3771862 47.4328789,9.376941 47.4326789,9.3767283 47.4327757,9.3765053 47.4325749,9.376312 47.4326732,9.37619 47.4325653,9.3761349 47.4325167,9.376056 47.4325644,9.3757946 47.43237,9.3760399 47.4322419,9.376144 47.4323272,9.3761809 47.4323125,9.3762975 47.432428,9.3762371 47.4324602,9.3763095 47.4325246,9.3764699 47.4324328,9.3763633 47.4323437,9.3763976 47.4323193,9.3763247 47.4322628,9.3763972 47.4322251,9.3764363 47.4322061,9.3766528 47.4323718,9.3768611 47.4322514,9.3765976 47.4320409,9.3766833 47.4319973))', 4326)
        
        public static Microsoft.SqlServer.Types.SqlGeography ToPolygon(string text)
        {
            // text = @"POLYGON((-122.358 47.653, -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))";
            System.Data.SqlTypes.SqlChars polygon = new System.Data.SqlTypes.SqlChars(new System.Data.SqlTypes.SqlString(text));
            Microsoft.SqlServer.Types.SqlGeography poly = Microsoft.SqlServer.Types.SqlGeography.STMPolyFromText(polygon, 4326);
            return poly;
        }
        
        public static Microsoft.SqlServer.Types.SqlGeography ToPolygon(GeoPoint[] points)
        {
            string pointText = ObjJoin(", ", points);
            string text = "POLYGON((" + pointText + "))";

            Microsoft.SqlServer.Types.SqlGeography poly = ToPolygon(text);
            return poly;
        }
        
        public static void Test()
        {
            // DECLARE @Geom TABLE ( shape geometry ); 
            // SELECT geometry::UnionAggregate(shape).ToString() FROM @Geom;
            // geometry ST_Union(geometry[] g1_array);
            // https://docs.microsoft.com/en-us/sql/t-sql/spatial-geometry/unionaggregate-geometry-data-type?view=sql-server-2017
            // https://gis.stackexchange.com/questions/237644/what-does-the-st-union-of-the-geometry-column-of-two-tables-produce

            GeoPoint[] points = new GeoPoint[]
            {
                  new GeoPoint(0,0)
                , new GeoPoint(0,0)
                , new GeoPoint(0,0)
                , new GeoPoint(0,0)
                , new GeoPoint(0,0)
            };

            string s1 = "POLYGON((9.3763619 47.4330074,9.3764389 47.4329684,9.3764072 47.4329405,9.3763969 47.4329322,9.3759864 47.4326004,9.376056 47.4325644,9.3761349 47.4325167,9.37619 47.4325653,9.376312 47.4326732,9.3765907 47.4328683,9.3766389 47.4328521,9.3767794 47.4329452,9.3764748 47.4331106,9.3763619 47.4330074))";
            string s2 = "POLYGON((9.3766833 47.4319973,9.3772045 47.4324131,9.3771257 47.432459,9.3769959 47.4323535,9.3767225 47.4325076,9.3768938 47.432637,9.3769843 47.4325975,9.3772713 47.432826,9.3771862 47.4328789,9.376941 47.4326789,9.3767283 47.4327757,9.3765053 47.4325749,9.376312 47.4326732,9.37619 47.4325653,9.3761349 47.4325167,9.376056 47.4325644,9.3757946 47.43237,9.3760399 47.4322419,9.376144 47.4323272,9.3761809 47.4323125,9.3762975 47.432428,9.3762371 47.4324602,9.3763095 47.4325246,9.3764699 47.4324328,9.3763633 47.4323437,9.3763976 47.4323193,9.3763247 47.4322628,9.3763972 47.4322251,9.3764363 47.4322061,9.3766528 47.4323718,9.3768611 47.4322514,9.3765976 47.4320409,9.3766833 47.4319973))'";

            // ST_GeomFromText(text WKT, integer srid);
            // ST_Union, ST_AsText
            // ST_GeomFromText('POINT(-2 3)') ) )
            // ST_Intersects( geography geogA , geography geogB )

            // Could not load Microsoft.SqlServer.Server

            Microsoft.SqlServer.Types.SqlGeography poly1 = ToPolygon(s1); // points);
            Microsoft.SqlServer.Types.SqlGeography poly2 = ToPolygon(s2); // points);

            Microsoft.SqlServer.Types.SqlGeography poly3 = poly1.STUnion(poly2);
            System.Data.SqlTypes.SqlChars chars = poly3.STAsText();
            string value = new string(chars.Value);
            System.Console.WriteLine(value);
        }
    }
}
#endif

And while you are at it, the version for the full .NET framwork (core also) should also work if SQL-Server is not installed on the machine that Microsoft.SqlServer.Types is executed on...

Activity

  1. rlisnoff commented on Oct 30, 2018

    @rlisnoff

    I'm experiencing the same problem, but when interacting with a table that has a HierarchyId column on it.

  2. divega commented on Jan 31, 2019

    @divega

    I believe the main issue here is that Microsoft.SqlServer.Types.dll is not available for .NET Core. This library is part of the SQL Server product.

    @karelz based on this and our exchange on dotnet/core#2273 (comment), I added the "tracking-external-issue". Is this the right label?

    There are a few workarounds:

  3. karelz commented on Feb 1, 2019

    @karelz
    Member

    That's the right label + no assignment + Future milestone + bug label.
    What is the external issue? Which (internal?) db? Which product?

  4. dotMorten commented on Feb 1, 2019

    @dotMorten

    @dotMorten has created a version of the Microsoft.SqlServer.Types library that works on .NET Core, but my understanding is that it does not implement spatial calculations.

    That is correct. While I could probably implement most of the calculations, the results are going to be slightly off. I don't think that's a good idea (for now perform those calculations server-side as part of your query). I'd rather we can get the native part of the spatial types open-sourced, so we can recompile it for more platforms (that would be a lot less work than porting it to C#).

  5. justintoth commented on Feb 4, 2019

    @justintoth

    +1 for implementing Microsoft.SqlServer.Types for .NET Standard. We're attempting to convert our class libraries from .NET Framework to .NET Standard, and the code is littered with references to SqlGeography and SqlGeometry. I appreciate @dotMorten for building his nuget package, but it doesn't implement enough of the original to be viable for us to port to. Trying to convert to using NetTopologySuite looks promising, but would be a huge effort to implement...

  6. ststeiger commented on Feb 4, 2019

    @ststeiger
    Author

    Well, basically, If there were any fully managed C# library that would correctly implement STUnion of two WGS84-polygons, that would have been sufficient.
    At the time, I found nothing that did it halfway reliably.
    But now it looks like DotSpatial.Topology does that.

  7. dotMorten commented on Feb 4, 2019

    @dotMorten

    @ststeiger @justintoth Are you still running on Windows though? If so, we can still use the native library and call into it from .NET Core. Just wouldn't work on Linux/mac/android/ios etc.

  8. justintoth commented on Feb 4, 2019

    @justintoth

    @dotMorten Yes, we're only running our applications on Windows. I saw in SO threads that you can supposedly reference the .NET framework version of the Microsoft.SqlServer.Types dll's and then call something like this in .NET Core:

    Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory);

    However, I tried it and the Utilities class doesn't exist in Microsoft.SqlServer.Types so it was a dead end for me. Any idea the proper way to do this?

  9. dotMorten commented on Feb 5, 2019

    @dotMorten

    @justintoth I was able to make it work in .NET core. I added the System.Data.SqlClient v4.6.0 and Microsoft.SqlServer.Types v14.0.1016.290 nuget packages.
    Next I manually added the Loader.cs file from inside the nuget package to my project as well as the required native libraries:

      <ItemGroup>
        <Content Include="$(USERPROFILE)\.nuget\packages\microsoft.sqlserver.types\14.0.1016.290\nativeBinaries\**\*.dll">
          <Link>SqlServerTypes\%(RecursiveDir)%(Filename)%(Extension)</Link>
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </Content>
        <Compile Include="$(USERPROFILE)\.nuget\packages\microsoft.sqlserver.types\14.0.1016.290\content\SqlServerTypes\Loader.cs" Link="Loader.cs" />
      </ItemGroup>
    
      <ItemGroup>
        <PackageReference Include="Microsoft.SqlServer.Types" Version="14.0.1016.290" />
        <PackageReference Include="System.Data.SqlClient" Version="4.6.0" />
      </ItemGroup>

    After this, I was successfully able to do the following in a .NET Core 3.0 app (I'm guessing it'll work on earlier versions too):

    SqlServerTypes.Utilities.LoadNativeAssemblies(".");
    SqlGeometry p1 = SqlGeometry.Point(23, 34, 4326);
    SqlGeometry p2 = SqlGeometry.Point(23, 35, 4326);
    var union = p1.STUnion(p2);

    Of course this will ONLY work when running your app on Windows as x86 or x64,

  10. dotMorten commented on Feb 5, 2019

    @dotMorten

    WOAH I even got this working on UWP. And because I don't have to deal with AnyCPU, I don't even need the LoadNativeAssemblies call. Here's what I added to .csproj to make it work in UWP:

      <ItemGroup>
        <PackageReference Include="System.Data.SqlClient">
          <Version>4.6.0</Version>
        </PackageReference>
        <Reference Include="Microsoft.SqlServer.Types, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL">
          <SpecificVersion>False</SpecificVersion>
          <HintPath>$(USERPROFILE)\.nuget\packages\microsoft.sqlserver.types\14.0.1016.290\lib\net40\Microsoft.SqlServer.Types.dll</HintPath>
        </Reference>
      </ItemGroup>
      <ItemGroup Condition="'$(Platform)'=='x64'">
        <Content Include="$(USERPROFILE)\.nuget\packages\microsoft.sqlserver.types\14.0.1016.290\nativeBinaries\x64\*.dll">
          <Link>%(Filename)%(Extension)</Link>
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </Content>    
      </ItemGroup>
      <ItemGroup Condition="'$(Platform)'=='x86'">
        <Content Include="$(USERPROFILE)\.nuget\packages\microsoft.sqlserver.types\14.0.1016.290\nativeBinaries\x86\*.dll">
          <Link>%(Filename)%(Extension)</Link>
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </Content>    
      </ItemGroup>

    (just note that the binaries violate store certification checks so you won't be able to put it in the store)

  11. ststeiger commented on Feb 5, 2019

    @ststeiger
    Author

    @dotMorten: Yea well, our Windows-only shop runs on Windows.
    But on my private laptop(s) which I use use to test new things on the way to and from work, there I only have Linux, and at home as well. Windows just doesn't go into standby and back fast enough, and it crashes, too. Also, I don't like the endless updates at moments in time that I don't want them (such as on a metered connection or when I have to change a train) and can't do anything against them, because although I have switched everything off and to manual and marked the connection as metered, it still does so whenever it feels like it...

    I think if I remember right, I just did it in SQL on SQL-server, which worked on Linux, too - to my not little surprise. Which would probably indicate that the binaries are ported, or at the very least they found a replacement.

    SELECT 
    	geography::STPolyFromText('POLYGON((7.5999034 47.5506347,7.6001195 47.550805,7.5999759 47.5508885,7.5998959 47.5508256,7.5997595 47.5507183,7.5999034 47.5506347))', 4326)
    	.STUnion(
    	geography::STPolyFromText('POLYGON((7.6003356 47.5509754,7.6001926 47.551059,7.6000322 47.5509328,7.5999759 47.5508885,7.6001195 47.550805,7.6003356 47.5509754))', 4326)
    	).STAsText()
    
  12. justintoth commented on Feb 5, 2019

    @justintoth

    @dotMorten How did you add the Microsoft.SqlServer.Types nuget package to your .NET Core package when it's a .NET Framework nuget package? When I try to add it to my .NET Standard class library it fails to add.

  13. 49 remaining items

  14. dotMorten commented on Feb 1, 2023

    @dotMorten

    Is this actually complete? Last I checked this only works on x86 and x64 Windows, which isn't in the spirit of claiming .net core support. With .NET 6 running on mac, linux, ios and android, there's not really much benefit to this work until we have a proper crossplatform solution.

    The nuget package explorer confirms it too with only runtimes supplied for 2 of the 3 Windows architectures and none for anything else:
    image

    It is in fact rather weird that the library claims to be netstandard2.1 instead of net5.0-windows which is what it really is.

  15. ststeiger commented on Feb 1, 2023

    @ststeiger
    Author

    It is in fact rather weird that the library claims to be netstandard2.1 instead of net5.0-windows which is what it really is.

    Haha, that's not weird, that's expected.
    Same old Microsoft.
    By the way, assuming you want polygons that can span accross the equator, it's not finished in x86 and x64, either.
    (or maybe not, i didn't test since last time i tested)

    But I guess quick & dirty was cheapter than proper engineering.
    Now about filestream support on SQL-Server on Linux ...
    It's been 6 years since 2017 ...
    How long did they claim they have to port sql-server, two weeks ?
    I guess it all depends on what you understand under sql-server.

    If you still haven't jumped ship to PostgreSQL/CockroachDB, you have nobody but yourselfs to blame.

  16. pjmlp commented on Feb 2, 2023

    @pjmlp

    Supporting only Windows is yet another example of why .NET fails to get some love on UNIXy platforms, marketing message is everything is cross platform in modern .NET, yet when we dive into the details there are hurdles like in this case.

  17. dmytro-gokun commented on Feb 15, 2023

    @dmytro-gokun

    @Wraith2 @cheenamalhotra Guys, is there any plans to support SqlGeometry/SqlGeography on Linux? I think lot of folks would like to know if its even planned..

  18. Wraith2 commented on Feb 15, 2023

    @Wraith2
    Contributor

    I have no plans to contribute in this area. The sort of response above from @ststeiger illustrates why.

    If someone else wanted to work on integrating @dotMorten 's open source geopgraphy stuff instead of relying on the closed source windows-only implementation that the sql server team (note: not the team that works on sql client and you see posting in this repo) maintains, then I'd be happy to help. I just have no need for the api personally and no need to expose myself to harmful toxicity.

  19. ErikEJ commented on Feb 15, 2023

    @ErikEJ
    Contributor

    @dmytro-gokun Have you tested on Linux and what is not working for you?

  20. dmytro-gokun commented on Feb 15, 2023

    @dmytro-gokun

    @ErikEJ Methods like STContains(), STArea() etc

  21. dmytro-gokun commented on Feb 15, 2023

    @dmytro-gokun

    @Wraith2 I understand.

    I would be happy to help. The problem is that we would need access to that closed source in order to implement it in 100% compatible way. I guess, no one want STContains() which work differently on Windows & Linux. Do you think there is any chance we can get hold of that source code?

  22. ErikEJ commented on Feb 15, 2023

    @ErikEJ
    Contributor

    Do you think there is any chance we can get hold of that source code?

    No

  23. dmytro-gokun commented on Feb 15, 2023

    @dmytro-gokun

    @ErikEJ I see. Then i do not think i will be able to help. Reverse engineering C code or trying to guess what exact algorithms were used is not my favorite passtime :)

    Does MS at least plan to have this ported to Linux at some point? I guess it would be fair to let community know what to (not) expect.

  24. dotMorten commented on Feb 15, 2023

    @dotMorten

    Does MS at least plan to have this ported to Linux at some point?

    It is my impression it is in their plans.

  25. dmytro-gokun commented on Feb 16, 2023

    @dmytro-gokun

    @dotMorten Would be really nice if someone from MS has actually confirmed or denied this :)
    @Kaur-Parminder Probably you could help here?

  26. maxmann74 commented on Mar 7, 2023

    @maxmann74

    Is this actually complete? Last I checked this only works on x86 and x64 Windows, which isn't in the spirit of claiming .net core support. With .NET 6 running on mac, linux, ios and android, there's not really much benefit to this work until we have a proper crossplatform solution.

    The nuget package explorer confirms it too with only runtimes supplied for 2 of the 3 Windows architectures and none for anything else: image

    It is in fact rather weird that the library claims to be netstandard2.1 instead of net5.0-windows which is what it really is.

    The previous versions of sqlserver.types also had an "msvcr.dll" c++ runtime in these folders. Can anyone confirm if that is no longer needed? Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    External 🔗

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions