[GIS] How to persist a polygon to SQL Server database and vice versa

arcmaparcobjectscpolygonsql server

How do I extract all the points from a Polygon drawn in ArcMAP and then persist that data into a SQLServer database table containing a geometry column and then when I've got the data persisted read from the database and draw the polygon again.

I'm working with ArcGIS 10 sp1 using ArcObjects for .NET (C#) sp1. I've made an add-in tool to draw the polygon and want that add-in to persist it too. I know how to do the last steps e.g putting the geometry data into the database and drawing an IPolygon instance in ArcMAP, what I don't know how to do is to somehow "convert" the Polygon into something that will "fit" into the geometry column of the database and vice versa.

I'm completely new to ArcObjects programming and GIS systems in general, started two weeks ago, so bare with me…

Best Answer

Your comment adds more insight as to what you are trying to do. You could just store it as WKT (well known text) Use ArcObjects to get the geometry to WKB, then use something like Sharpmap to convert to WKT.

    /// <summary>
    /// Converts geometry into WKB
    /// </summary>
    /// <param name="geometry">The geometry.</param>
    /// <returns>byte array of a WKB geometry</returns>
    public static byte[] ToWKB(this IGeometry geometry)
    {
        IWkb wkb = geometry as IWkb;
        ITopologicalOperator oper = geometry as ITopologicalOperator;
        oper.Simplify();

        IGeometryFactory3 factory = new GeometryEnvironment() as IGeometryFactory3;
        byte[] b = factory.CreateWkbVariantFromGeometry(geometry) as byte[];
        return b;
    }


    /// <summary>
    /// Converts WKB to WKT
    /// </summary>
    /// <param name="geometry">The geometry.</param>
    /// <returns>WKT string</returns>
    public static string ToWKT(this IGeometry geometry)
    {
        byte[] wkb = geometry.ToWKB();
        SharpMap.Geometries.IGeometry sharpGeom = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse(wkb);
        return SharpMap.Converters.WellKnownText.GeometryToWKT.Write(sharpGeom);
    }

    /// <summary>
    /// Sets the byte value.
    /// </summary>
    /// <param name="row">The row to the featureclass or table row</param>
    /// <param name="fieldName">Name of the field.</param>
    /// <param name="data">The byte array to store.</param>
    /// <returns>true if the field is found and value set</returns>
    public static bool SetByteValue(this IRow row, string fieldName, byte[] data)
    {
        int index = row.Fields.FindField(fieldName);

        if (index != -1)
        {
            IMemoryBlobStreamVariant memoryBlobStream = new MemoryBlobStreamClass();
            memoryBlobStream.ImportFromVariant(data);

            if (row.Fields.get_Field(index).Editable)
            {
                row.set_Value(index, memoryBlobStream);
                return true;
            }
        }

        return false;
    }