/// <summary>
        /// Creates a new instance of frmQueryBuilder class
        /// </summary>
        public frmQueryBuilder(MapWinGIS.Shapefile sf, int layerHandle, string expression, bool SelectionMode)
        {
            InitializeComponent();

            if (sf == null)
            {
                return;
            }

            _shapefile     = sf;
            _selectionMode = SelectionMode;
            _layerHandle   = layerHandle;

            btnTest.Text = SelectionMode ? "Select" : "Test";

            dgvField.Rows.Clear();
            dgvField.Rows.Add(_shapefile.NumFields);

            for (int i = 0; i < _shapefile.NumFields; i++)
            {
                dgvField[CMN_NAME, i].Value = _shapefile.get_Field(i).Name;
                if (_shapefile.get_Field(i).Type == MapWinGIS.FieldType.STRING_FIELD)
                {
                    dgvField[CMN_ICON, i].Value           = "Aa";
                    dgvField[CMN_ICON, i].Style.ForeColor = Color.Maroon;
                }
                else
                {
                    dgvField[CMN_ICON, i].Value = "09";
                    //dgvField[CMN_ICON, i].Style.ForeColor = Color.Blue;
                }
            }

            if (dgvField.Rows.Count > 0)
            {
                // TODO: show unique values
            }
            richTextBox1.Text          = expression;
            richTextBox1.HideSelection = false;
            richTextBox1.SelectAll();
            richTextBox1.Focus();

            if (chkShowValues.Checked)
            {
                ShowValues(0);
            }

            _noEvents = true;

            // restoring values
            SymbologySettings settings = Globals.get_LayerSettings(_layerHandle);

            chkShowValues.Checked      = settings.ShowQueryValues;
            chkShowDynamically.Checked = settings.ShowQueryOnMap;

            _noEvents = false;
        }
Beispiel #2
0
        // Add the shapes one by one
        private bool AddShapes(MapWinGIS.Shapefile inSF, out string errorMessage)
        {
            errorMessage = "No Error.";
            int outShp = _outSF.NumShapes;

            // Add all the shapes and attributes from the first shapefile
            for (int shp = 0; shp < inSF.NumShapes; shp++)
            {
                MapWinGIS.Shape shape = inSF.get_Shape(shp);
                _outSF.EditInsertShape(shape, ref outShp);
                for (int fld = 0; fld < inSF.NumFields; fld++)
                {
                    string name  = inSF.get_Field(fld).Name;
                    int    index = IndexOf(name);
                    if (index == -1)
                    {
                        errorMessage = "Could not find a field in the output shapefile: [" + name + "]";
                        return(false);
                    }
                    if (_outSF.EditCellValue(index, outShp, inSF.get_CellValue(fld, shp)) == false)
                    {
                        errorMessage = _outSF.get_ErrorMsg(_outSF.LastErrorCode);
                        return(false);
                    }
                }
                outShp++;
            }
            return(true);
        }
Beispiel #3
0
 // Use the string name to test each field in the output shapefile to determine the correct index
 private int IndexOf(string fieldName)
 {
     for (int fld = 0; fld < _outSF.NumFields; fld++)
     {
         if (_outSF.get_Field(fld).Name == fieldName)
         {
             return(fld);
         }
     }
     return(-1);
 }
Beispiel #4
0
        // Build a list of unique fields for the output file
        private bool CombineFields(out string errorMessage)
        {
            errorMessage = "No Error";
            List <MapWinGIS.Field> fields = new List <MapWinGIS.Field>();
            List <string>          names  = new List <string>();

            for (int fld = 0; fld < _inSF1.NumFields; fld++)
            {
                MapWinGIS.Field field = _inSF1.get_Field(fld);
                fields.Add(field);
                names.Add(field.Name);
            }
            for (int fld = 0; fld < _inSF2.NumFields; fld++)
            {
                MapWinGIS.Field field = _inSF2.get_Field(fld);
                string          name  = field.Name;
                if (names.Contains(name) == false)
                {
                    fields.Add(field);
                    names.Add(name);
                }
                else
                {
                    if (fields[names.IndexOf(name)].Type != field.Type)
                    {
                        errorMessage = "Fields with a common name [" + name + "] did not share the same type.";
                        return(false);
                    }
                }
            }

            int fi = 0;

            foreach (MapWinGIS.Field field in fields)
            {
                if (_outSF.EditInsertField(field, ref fi, null) == false)
                {
                    errorMessage = _outSF.get_ErrorMsg(_outSF.LastErrorCode);
                    return(false);
                }
                fi++;
            }
            return(true);
        }
        /// <summary>
        /// Creates a table based upon fileds of specified shapefile
        /// </summary>
        public bool CreateTable(MapWinGIS.Shapefile sf, string tableName)
        {
            this.CheckConnection();

            DbCommand command = m_connection.CreateCommand();

            string sql = " ([Geometry] " + m_provider.GetBinaryTypeName() + ", ";

            int count = sf.NumFields;

            for (int i = 0; i < count; i++)
            {
                MapWinGIS.Field field = sf.get_Field(i);
                string          s     = "[" + field.Name + "] ";
                switch (field.Type)
                {
                case MapWinGIS.FieldType.DOUBLE_FIELD:
                    s += m_provider.GetDoubleTypeName();
                    break;

                case MapWinGIS.FieldType.INTEGER_FIELD:
                    s += m_provider.GetIntergerTypeName();
                    break;

                case MapWinGIS.FieldType.STRING_FIELD:
                    bool   fixedLength = true;
                    string name        = m_provider.GetStringTypeName(out fixedLength);
                    s += fixedLength ? name + "(" + field.Width.ToString() + ")" : name;
                    break;

                default:
                    continue;
                }
                sql += s;
                sql += i < count - 1 ? ", " : ")";
            }

            command.CommandText = "CREATE TABLE [" + tableName + "]" + sql;
            command.ExecuteNonQuery();
            return(DbUtilities.TableExists(m_connection, tableName));
        }
Beispiel #6
0
        private void populateFields()
        {
            MapWinGIS.Field            curField;
            MapWinGIS.Shapefile        sf = new MapWinGIS.Shapefile();
            MapWindow.Interfaces.Layer curLayer;
            cmbFields.Items.Clear();

            for (int i = 0; i < m_MapWin.Layers.NumLayers; ++i)
            {
                curLayer = m_MapWin.Layers[i];
                //the layer type is shapefile (ensured by PopulateLayers)
                if (curLayer != null)
                {
                    if (curLayer.Name == cmbLayers.Text)
                    {
                        sf = (MapWinGIS.Shapefile)curLayer.GetObject();
                        break;
                    }
                }
            }

            //add the fields in the shapefile to the list of fields
            //for simplification, only numeric fields can be added
            //because the resulting grid can only contain numeric values

            for (int i = 0; i < sf.NumFields; ++i)
            {
                curField = sf.get_Field(i);
                if (curField.Type == MapWinGIS.FieldType.DOUBLE_FIELD ||
                    curField.Type == MapWinGIS.FieldType.INTEGER_FIELD)
                {
                    cmbFields.Items.Add(curField.Name);
                }
            }
            if (cmbFields.Items.Count > 0)
            {
                cmbFields.SelectedIndex = 0;
                m_ShpFileName           = sf.Filename;
            }
        }
Beispiel #7
0
 private void populateFields(string shpFileName)
 {
     cmbFields.Items.Clear();
     MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
     MapWinGIS.Field     curField;
     if (sf.Open(shpFileName, sf.GlobalCallback))
     {
         for (int i = 0; i < sf.NumFields; ++i)
         {
             curField = sf.get_Field(i);
             if (curField.Type == MapWinGIS.FieldType.DOUBLE_FIELD ||
                 curField.Type == MapWinGIS.FieldType.INTEGER_FIELD)
             {
                 cmbFields.Items.Add(curField.Name);
             }
         }
         sf.Close();
     }
     if (cmbFields.Items.Count > 0)
     {
         cmbFields.SelectedIndex = 0;
     }
 }
        /// <summary>
        /// Returns an in-memory shapefile of points from the input shapefile that fall within the polygon.
        /// </summary>
        /// <param name="pointSF">Full path to the point shapefile.</param>
        /// <param name="polygon">The polygon used for clipping the point shapefile.</param>
        /// <param name="result">Full path to where the resulting point shapefile should be saved.</param>
        /// <param name="copyAttributes">True if copying attributes over</param>
        /// <returns>False if an error was encountered, true otherwise.</returns>
        public static bool ClipPointSFWithPolygon(ref MapWinGIS.Shapefile pointSF, ref MapWinGIS.Shape polygon, out MapWinGIS.Shapefile result, bool copyAttributes)
        {
            MapWinUtility.Logger.Dbg("ClipPointSFWithPolygon(pointSF: " + Macro.ParamName(pointSF) + ",\n" +
                                     "                       polygon: " + Macro.ParamName(polygon) + ",\n" +
                                     "                       result: out, \n" +
                                     "                       copyAttributes: " + copyAttributes.ToString() + ",\n");
            MapWinGIS.Shapefile resultSF = new MapWinGIS.ShapefileClass();
            int shpIndex = 0;             //all new shapes will be placed at the beginning of the shapefile

            MapWinGIS.ShpfileType sfType = pointSF.ShapefileType;

            //make sure we are dealing with a valid shapefile type
            if (sfType == MapWinGIS.ShpfileType.SHP_POINT || sfType == MapWinGIS.ShpfileType.SHP_POINTM || sfType == MapWinGIS.ShpfileType.SHP_POINTZ)
            {
                string tempPath = System.IO.Path.GetTempPath() + "resultSF.shp";
                DataManagement.DeleteShapefile(ref tempPath);
                string tmpName;
                //create the result shapeFile if it does not already exist
                //if(resultSF.CreateNew(tempPath, sfType) == false)
                //{
                //    gErrorMsg = "Problem creating the result shapeFile: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                //    Debug.WriteLine(gErrorMsg);
                //    MapWinGeoProc.Error.SetErrorMsg(gErrorMsg);
                //    result = resultSF;
                //    return false;
                //}
                //CDM 8/4/2006 resultSF.CreateNew(resultSFPath, sfType);
                Globals.PrepareResultSF(ref tempPath, ref resultSF, sfType);

                if (copyAttributes)
                {
                    MapWinGIS.Field tmpField, pointField;
                    for (int f = 0; f <= pointSF.NumFields - 1; f++)
                    {
                        tmpField   = new MapWinGIS.Field();
                        pointField = pointSF.get_Field(f);
                        tmpName    = pointField.Name;
                        if (tmpName.Contains("MWShapeID"))
                        {
                            tmpField.Name = "Last_" + tmpName;
                        }
                        else
                        {
                            tmpField.Name = tmpName;
                        }
                        tmpField.Width     = pointField.Width;
                        tmpField.Type      = pointField.Type;
                        tmpField.Precision = pointField.Precision;
                        tmpField.Key       = pointField.Key;
                        resultSF.EditInsertField(tmpField, ref f, null);
                    }
                }

                int             numTargetPoints = pointSF.NumShapes;
                MapWinGIS.Point targetPoint     = new MapWinGIS.PointClass();
                //MapWinGIS.Utils utils = new MapWinGIS.UtilsClass();
                int numParts = polygon.NumParts;
                if (numParts == 0)
                {
                    numParts = 1;
                }
                Globals.Vertex[][] polyVertArray = new Globals.Vertex[numParts][];
                Globals.ConvertPolyToVertexArray(ref polygon, out polyVertArray);

                for (int i = 0; i <= numTargetPoints - 1; i++)
                {
                    targetPoint = pointSF.QuickPoint(i, 0);

                    if (Utils.PointInPoly(ref polyVertArray, ref targetPoint) == true)
                    {
                        resultSF.EditInsertShape(pointSF.get_Shape(i), ref shpIndex);
                        if (copyAttributes)
                        {
                            for (int f = 0; f <= pointSF.NumFields - 1; f++)
                            {
                                bool tmpbool = resultSF.EditCellValue(f, shpIndex, pointSF.get_CellValue(f, i));
                            }
                        }
                    }
                }
            }
            else
            {
                gErrorMsg = "The shapefile is of the wrong type. Should be of type Point.";
                Debug.WriteLine(gErrorMsg);
                MapWinGeoProc.Error.SetErrorMsg(gErrorMsg);
                result = resultSF;
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
            result = resultSF;
            MapWinUtility.Logger.Dbg("Finished ClipPointSFWithPolygon");
            return(true);
        }
Beispiel #9
0
        /// <summary>
        /// Removes portions of the lineSF that fall within the erase polygon
        /// </summary>
        /// <param name="lineSF">The shapefile of lines to be erased.</param>
        /// <param name="erasePoly">The polygon to be used for erasing portion of the line shapefile.</param>
        /// <param name="resultSF">The resulting line shapefile with portions removed.</param>
        /// <param name="CopyAttributes">Indicates whether to copy attributes</param>
        /// <returns>False if an error was encountered, true otherwise.</returns>
        public static bool EraseLineSFWithPoly(ref MapWinGIS.Shapefile lineSF, ref MapWinGIS.Shape erasePoly, ref MapWinGIS.Shapefile resultSF, bool CopyAttributes)
        {
            MapWinUtility.Logger.Dbg("EraseLineSFWithPoly(lineSF: " + Macro.ParamName(lineSF) + ",\n" +
                                     "                    erasePoly: " + Macro.ParamName(erasePoly) + ",\n" +
                                     "                    resultSF: " + Macro.ParamName(resultSF) + ",\n" +
                                     "                    CopyAttributes: " + CopyAttributes.ToString() + ")");
            if (lineSF == null || erasePoly == null || resultSF == null)
            {
                gErrorMsg = "One of the input parameters is null.";
                Error.SetErrorMsg(gErrorMsg);
                Debug.WriteLine(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }

            if (CopyAttributes)
            {
                string          tmpName;
                MapWinGIS.Field tmpField, currField;
                for (int f = 0; f <= lineSF.NumFields - 1; f++)
                {
                    tmpField      = new MapWinGIS.Field();
                    currField     = lineSF.get_Field(f);
                    tmpName       = currField.Name;
                    tmpField.Name = tmpName;

                    tmpField.Width     = currField.Width;
                    tmpField.Type      = currField.Type;
                    tmpField.Precision = currField.Precision;
                    tmpField.Key       = currField.Key;
                    resultSF.EditInsertField(tmpField, ref f, null);
                }
            }

            int shpIndex = 0;
            int numLines = lineSF.NumShapes;

            for (int i = 0; i <= numLines - 1; i++)
            {
                MapWinGIS.Shape currLine = new MapWinGIS.ShapeClass();
                currLine.Create(lineSF.ShapefileType);
                currLine = lineSF.get_Shape(i);

                MapWinGIS.Shape lineEnvelope = new MapWinGIS.ShapeClass();
                lineEnvelope.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
                //create lineExtents' points out of the line extent points
                MapWinGIS.Point lTop, rTop, rBottom, lBottom;
                lTop      = new MapWinGIS.PointClass();
                lTop.x    = currLine.Extents.xMin;
                lTop.y    = currLine.Extents.yMax;
                rTop      = new MapWinGIS.PointClass();
                rTop.x    = currLine.Extents.xMax;
                rTop.y    = currLine.Extents.yMax;
                rBottom   = new MapWinGIS.PointClass();
                rBottom.x = currLine.Extents.xMax;
                rBottom.y = currLine.Extents.yMin;
                lBottom   = new MapWinGIS.PointClass();
                lBottom.x = currLine.Extents.xMin;
                lBottom.y = currLine.Extents.yMin;
                //now add the extent points to the new polygon shape: lineEnvelope
                int ptIndex = 0;
                lineEnvelope.InsertPoint(lTop, ref ptIndex);
                ptIndex++;
                lineEnvelope.InsertPoint(rTop, ref ptIndex);
                ptIndex++;
                lineEnvelope.InsertPoint(rBottom, ref ptIndex);
                ptIndex++;
                lineEnvelope.InsertPoint(lBottom, ref ptIndex);
                ptIndex++;
                lineEnvelope.InsertPoint(lTop, ref ptIndex);
                //remove COM points from memory
                while (Marshal.ReleaseComObject(lTop) != 0)
                {
                    ;
                }
                while (Marshal.ReleaseComObject(rTop) != 0)
                {
                    ;
                }
                while (Marshal.ReleaseComObject(rBottom) != 0)
                {
                    ;
                }
                while (Marshal.ReleaseComObject(lBottom) != 0)
                {
                    ;
                }

                //Check if line extents and polygon extents overlap
                if (Globals.CheckBounds(ref lineEnvelope, ref erasePoly))
                {
                    //make the envelope polygon slightly larger
                    MapWinGIS.Shape lgEnvelope = new MapWinGIS.ShapeClass();
                    lgEnvelope.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
                    SpatialOperations.BufferPolygon(ref lineEnvelope, 0.5, Enumerations.Buffer_HoleTreatment.Ignore, Enumerations.Buffer_CapStyle.Pointed, out lgEnvelope);
                    //take the difference of the envelope polygon with the erase polygon.
                    MapWinGIS.Shape diff = new MapWinGIS.ShapeClass();
                    diff.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
                    diff = SpatialOperations.Difference(lgEnvelope, erasePoly);
                    if (diff.numPoints > 0)
                    {
                        //the difference shape represents the line envelope
                        //minus the area of the erase polygon.
                        MapWinGIS.Shapefile inputLine = new MapWinGIS.ShapefileClass();
                        string tempPath = System.IO.Path.GetTempPath() + "tempInputLine.shp";
                        //CDM 8/4/2006 inputLine.CreateNew(tempPath, lineSF.ShapefileType);
                        Globals.PrepareResultSF(ref tempPath, ref inputLine, lineSF.ShapefileType);
                        shpIndex = 0;
                        inputLine.EditInsertShape(currLine, ref shpIndex);

                        int numParts = diff.NumParts;
                        if (numParts == 0)
                        {
                            numParts = 1;
                        }

                        if (numParts > 1)
                        {
                            //separate and test each part individually
                            MapWinGIS.Shape[] diffParts = new MapWinGIS.Shape[numParts];
                            Globals.SeparateParts(ref diff, out diffParts);
                            for (int j = 0; j <= numParts - 1; j++)
                            {
                                //don't check inside of holes
                                if (Globals.IsClockwise(ref diffParts[j]))
                                {
                                    MapWinGIS.Shapefile tempLineResult = new MapWinGIS.ShapefileClass();
                                    string tempLineFile = System.IO.Path.GetTempPath() + "tempLines.shp";
                                    DataManagement.DeleteShapefile(ref tempLineFile);
                                    //CDM 8/4/2006 tempLineResult.CreateNew(tempLineFile, lineSF.ShapefileType);
                                    Globals.PrepareResultSF(ref tempLineFile, ref tempLineResult, lineSF.ShapefileType);
                                    tempLineResult.StartEditingShapes(true, null);

                                    SpatialOperations.ClipShapesWithPolygon(ref inputLine, ref diffParts[j], out tempLineResult, false);

                                    int numResults = tempLineResult.NumShapes;
                                    if (numResults > 0)
                                    {
                                        //add results to the final result file.
                                        for (int k = 0; k <= numResults - 1; k++)
                                        {
                                            shpIndex = resultSF.NumShapes;
                                            resultSF.EditInsertShape(tempLineResult.get_Shape(k), ref shpIndex);
                                            if (CopyAttributes)
                                            {
                                                for (int f = 0; f <= lineSF.NumFields - 1; f++)
                                                {
                                                    bool tmpbool = resultSF.EditCellValue(f, shpIndex, lineSF.get_CellValue(f, i));
                                                }
                                            }
                                        }
                                    }                    //clipping successful
                                }                        //done checking islands
                            }                            //done looping through parts of the difference shape
                        }
                        else
                        {
                            MapWinGIS.Shapefile tempLineResult = new MapWinGIS.ShapefileClass();
                            string tempLineFile = System.IO.Path.GetTempPath() + "tempLines.shp";
                            DataManagement.DeleteShapefile(ref tempLineFile);
                            //CDM 8/4/2006 tempLineResult.CreateNew(tempLineFile, lineSF.ShapefileType);
                            Globals.PrepareResultSF(ref tempLineFile, ref tempLineResult, lineSF.ShapefileType);

                            tempLineResult.StartEditingShapes(true, null);

                            SpatialOperations.ClipShapesWithPolygon(ref inputLine, ref diff, out tempLineResult, false);

                            int numResults = tempLineResult.NumShapes;
                            if (numResults > 0)
                            {
                                //add results to the final result file.
                                for (int k = 0; k <= numResults - 1; k++)
                                {
                                    shpIndex = resultSF.NumShapes;
                                    resultSF.EditInsertShape(tempLineResult.get_Shape(k), ref shpIndex);
                                    if (CopyAttributes)
                                    {
                                        for (int f = 0; f <= lineSF.NumFields - 1; f++)
                                        {
                                            bool tmpbool = resultSF.EditCellValue(f, shpIndex, lineSF.get_CellValue(f, i));
                                        }
                                    }
                                }
                            }    //clipping successful
                        }
                    }            //difference operation successful
                }                //bounds overlapped
                else
                {
                    shpIndex = resultSF.NumShapes;
                    resultSF.EditInsertShape(currLine, ref shpIndex);
                    if (CopyAttributes)
                    {
                        for (int f = 0; f <= lineSF.NumFields - 1; f++)
                        {
                            bool tmpbool = resultSF.EditCellValue(f, shpIndex, lineSF.get_CellValue(f, i));
                        }
                    }
                }
            }            //end of looping through lines in the input shapefile
            MapWinUtility.Logger.Dbg("Finished EraseLineSFWithPoly");
            return(true);
        }
Beispiel #10
0
        /// <summary>
        /// Removes points from the point shapefile that lie within the polygon.
        /// </summary>
        /// <param name="pointSF">The point shapefile.</param>
        /// <param name="polygon">The erase polygon.</param>
        /// <param name="resultSF">The resulting file with points removed.</param>
        /// <param name="CopyAttributes">Indicates whether to copy attributes</param>
        /// <returns>False if an error was encountered, true otherwise.</returns>
        public static bool ErasePointSFWithPoly(ref MapWinGIS.Shapefile pointSF, ref MapWinGIS.Shape polygon, ref MapWinGIS.Shapefile resultSF, bool CopyAttributes)
        {
            MapWinUtility.Logger.Dbg("ErasePointSFWithPoly(pointSF: " + Macro.ParamName(pointSF) + "\n, " +
                                     "                     polygon: " + Macro.ParamName(polygon) + "\n, " +
                                     "                     resultSF: " + Macro.ParamName(resultSF) + "\n, " +
                                     "                     CopyAttributes: " + CopyAttributes.ToString() + ")");

            if (pointSF == null || polygon == null || resultSF == null)
            {
                gErrorMsg = "One of the input parameters is null.";
                Error.SetErrorMsg(gErrorMsg);
                Debug.WriteLine(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }

            if (CopyAttributes)
            {
                string          tmpName;
                MapWinGIS.Field tmpField, currField;
                for (int f = 0; f <= pointSF.NumFields - 1; f++)
                {
                    tmpField      = new MapWinGIS.Field();
                    currField     = pointSF.get_Field(f);
                    tmpName       = currField.Name;
                    tmpField.Name = tmpName;

                    tmpField.Width     = currField.Width;
                    tmpField.Type      = currField.Type;
                    tmpField.Precision = currField.Precision;
                    tmpField.Key       = currField.Key;
                    resultSF.EditInsertField(tmpField, ref f, null);
                }
            }

            int numPts   = pointSF.NumShapes;
            int numParts = polygon.NumParts;

            if (numParts == 0)
            {
                numParts = 1;
            }
            int shpIndex = 0;

            Globals.Vertex[][] vertArray = new Globals.Vertex[numParts][];
            Globals.ConvertPolyToVertexArray(ref polygon, out vertArray);

            for (int i = 0; i <= numPts - 1; i++)
            {
                MapWinGIS.Point currPt = new MapWinGIS.PointClass();
                currPt = pointSF.QuickPoint(i, 0);
                double currX = currPt.x;
                double currY = currPt.y;
                if (Utils.PointInPoly(ref vertArray, currX, currY) == false)
                {
                    shpIndex = resultSF.NumShapes;
                    if (resultSF.EditInsertShape(pointSF.get_Shape(i), ref shpIndex) == false)
                    {
                        gErrorMsg = "ErasePointSF: problem inserting shape into result file: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                        Debug.WriteLine(gErrorMsg);
                        Error.SetErrorMsg(gErrorMsg);
                        MapWinUtility.Logger.Dbg(gErrorMsg);
                        return(false);
                    }
                    if (CopyAttributes)
                    {
                        for (int f = 0; f <= pointSF.NumFields - 1; f++)
                        {
                            bool tmpbool = resultSF.EditCellValue(f, shpIndex, pointSF.get_CellValue(f, i));
                        }
                    }
                }
            }
            MapWinUtility.Logger.Dbg("Finished ErasePointSFWithPoly");
            return(true);
        }
Beispiel #11
0
        private void populateFields()
        {
            MapWinGIS.Field curField;
            MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
            MapWindow.Interfaces.Layer curLayer;
            cmbFields.Items.Clear();

            for (int i = 0; i < m_MapWin.Layers.NumLayers; ++i)
            {
                curLayer = m_MapWin.Layers[i];
                //the layer type is shapefile (ensured by PopulateLayers)
                if (curLayer != null)
                {
                    if (curLayer.Name == cmbLayers.Text)
                    {
                        sf = (MapWinGIS.Shapefile)curLayer.GetObject();
                        break;
                    }
                }
            }

            //add the fields in the shapefile to the list of fields
            //for simplification, only numeric fields can be added
            //because the resulting grid can only contain numeric values

            for (int i = 0; i < sf.NumFields; ++i)
            {
                curField = sf.get_Field(i);
                if (curField.Type == MapWinGIS.FieldType.DOUBLE_FIELD ||
                    curField.Type == MapWinGIS.FieldType.INTEGER_FIELD)
                {
                    cmbFields.Items.Add(curField.Name);
                }
            }
            if (cmbFields.Items.Count > 0)
            {
                cmbFields.SelectedIndex = 0;
                m_ShpFileName = sf.Filename;
            }
        }
        /// <summary>
        /// Returns the portions of the polygons in polySF that lie within polygon as a
        /// new shapefile of polygons: resultPolySF.
        /// </summary>
        /// <param name="polySF">The shapefile of polygons that are to be clipped.</param>
        /// <param name="polygon">The polygon used for clipping.</param>
        /// <param name="resultPolySF">The result shapefile for the resulting polygons to be saved (in-memory).</param>
        /// <param name="copyAttributes">True if copying attrs</param>
        /// <returns>False if an error was encountered, true otherwise.</returns>
        public static bool ClipPolygonSFWithPolygon(ref MapWinGIS.Shapefile polySF, ref MapWinGIS.Shape polygon, out MapWinGIS.Shapefile resultPolySF, bool copyAttributes)
        {
            MapWinUtility.Logger.Dbg("ClipPolygonSFWithPolygon(polySF: " + Macro.ParamName(polySF) + ",\n" +
                                     "                         polygon: " + Macro.ParamName(polygon) + ",\n" +
                                     "                         resultPolySF: out,\n" +
                                     "                         copyAttributes: " + copyAttributes.ToString() + "\n");

            MapWinGIS.Shapefile   resultSF = new MapWinGIS.ShapefileClass();
            MapWinGIS.ShpfileType sfType   = polySF.ShapefileType;
            string tempPath = System.IO.Path.GetTempPath() + "resultSF.shp";

            DataManagement.DeleteShapefile(ref tempPath);
            string tmpName;

            Globals.PrepareResultSF(ref tempPath, ref resultSF, sfType, copyAttributes);

            if (copyAttributes)
            {
                MapWinGIS.Field tmpField, currField;
                for (int f = 0; f <= polySF.NumFields - 1; f++)
                {
                    tmpField  = new MapWinGIS.Field();
                    currField = polySF.get_Field(f);
                    tmpName   = currField.Name;
                    if (tmpName.Contains("MWShapeID"))
                    {
                        tmpField.Name = "Last_" + tmpName;
                    }
                    else
                    {
                        tmpField.Name = tmpName;
                    }
                    tmpField.Width     = currField.Width;
                    tmpField.Type      = currField.Type;
                    tmpField.Precision = currField.Precision;
                    tmpField.Key       = currField.Key;
                    resultSF.EditInsertField(tmpField, ref f, null);
                }
            }

            int shapeIndex = 0;            //insert new shapes at the beginning of the shapefile

            if (polySF.NumShapes != 0 && polygon.numPoints != 0 && (sfType == MapWinGIS.ShpfileType.SHP_POLYGON || sfType == MapWinGIS.ShpfileType.SHP_POLYGONM || sfType == MapWinGIS.ShpfileType.SHP_POLYGONZ))
            {
                MapWinGIS.Shape resultShape     = new MapWinGIS.ShapeClass();
                int             numShapes       = polySF.NumShapes;
                bool            boundsIntersect = false;

                for (int i = 0; i <= numShapes - 1; i++)
                {
                    MapWinGIS.Shape currPoly = new MapWinGIS.ShapeClass();
                    currPoly = polySF.get_Shape(i);
                    //check to see if bounds intersect before sending shape to GPC clip function
                    boundsIntersect = Globals.CheckBounds(ref currPoly, ref polygon);

                    if (boundsIntersect == true)
                    {
                        //find the shape resulting intersection
                        resultShape = SpatialOperations.Intersection(polySF.get_Shape(i), polygon);
                        if (resultShape.numPoints != 0)
                        {
                            //save the new shape to the result shapefile
                            if (resultSF.EditInsertShape(resultShape, ref shapeIndex) == false)
                            {
                                gErrorMsg = "Problem inserting shape: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                                Debug.WriteLine(gErrorMsg);
                                MapWinGeoProc.Error.SetErrorMsg(gErrorMsg);
                                resultPolySF = resultSF;
                                return(false);
                            }
                            if (copyAttributes)
                            {
                                for (int f = 0; f <= polySF.NumFields - 1; f++)
                                {
                                    bool tmpbool = resultSF.EditCellValue(f, shapeIndex, polySF.get_CellValue(f, i));
                                }
                            }
                        }
                    }
                }
            }
            resultPolySF = resultSF;
            return(true);
        }
        /// <summary>
        /// Showing values
        /// </summary>
        private void ShowValues(int FieldIndex)
        {
            _noEvents = true;
            dgvValues.Rows.Clear();

            if (_shapefile.NumFields - 1 < FieldIndex)
            {
                _noEvents = false;
                return;
            }

            MapWinGIS.Table tbl = _shapefile.Table;
            object          obj = null;
            SortedDictionary <object, int> hashTable = new SortedDictionary <object, int>();

            bool isString = (_shapefile.get_Field(FieldIndex).Type == MapWinGIS.FieldType.STRING_FIELD);

            if (true)
            {
                this.Cursor = Cursors.WaitCursor;

                for (int i = 0; i < tbl.NumRows; i++)
                {
                    obj = tbl.get_CellValue(FieldIndex, i);
                    if (hashTable.ContainsKey(obj))
                    {
                        hashTable[obj] += 1;
                    }
                    else
                    {
                        hashTable.Add(obj, 1);
                    }
                }
                int[]    values = hashTable.Values.ToArray();
                object[] keys   = hashTable.Keys.ToArray();

                dgvValues.Rows.Add(values.Length);
                for (int i = 0; i < values.Length; i++)
                {
                    if (isString)
                    {
                        dgvValues[1, i].Value = "\"" + keys[i].ToString() + "\"";
                    }
                    else
                    {
                        dgvValues[1, i].Value = keys[i].ToString();
                    }
                    dgvValues[0, i].Value = values[i];
                }

                this.Cursor = Cursors.Default;
            }
            else

            // field stats: aren't used currently
            {
                // for numeric fields we shall provide statistics
                dgvValues.Rows.Add(7);
                dgvValues[0, 0].Value = "Avg";
                dgvValues[0, 1].Value = "StDev";
                dgvValues[0, 2].Value = "0%";
                dgvValues[0, 3].Value = "25%";
                dgvValues[0, 4].Value = "50%";
                dgvValues[0, 5].Value = "75%";
                dgvValues[0, 6].Value = "100%";

                List <object> list = new List <object>();
                for (int i = 0; i < tbl.NumRows; i++)
                {
                    list.Add((object)tbl.get_CellValue(FieldIndex, i));
                }
                list.Sort();

                int quater = list.Count / 4;
                for (int i = 0; i < list.Count; i++)
                {
                    if (i == quater)
                    {
                        dgvValues[1, 3].Value = list[i];
                    }
                    else if (i == quater * 2)
                    {
                        dgvValues[1, 4].Value = list[i];
                    }
                    else if (i == quater * 3)
                    {
                        dgvValues[1, 5].Value = list[i];
                    }
                }

                dgvValues[1, 0].Value = (float)tbl.get_MeanValue(FieldIndex);
                dgvValues[1, 1].Value = (float)tbl.get_StandardDeviation(FieldIndex);
                dgvValues[1, 2].Value = tbl.get_MinValue(FieldIndex);
                dgvValues[1, 6].Value = tbl.get_MaxValue(FieldIndex);
            }

            dgvValues.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            _noEvents = false;
        }
        /// <summary>
        /// Inserts shapes with the given indices in the specified table.
        /// </summary>
        /// <returns>Number of inserted shapes. -1 if the table doesn't exist.</returns>
        public int InsertShapes(MapWinGIS.Shapefile sf, string tableName, int[] indices)
        {
            this.CheckConnection();

            int count = 0;

            using (DbTransaction dbTrans = m_connection.BeginTransaction())
            {
                using (DbCommand cmd = this.CreateCommand())
                {
                    DbParameter param = this.CreateBinaryParameter();
                    param.SourceColumn  = "Geometry";
                    param.ParameterName = "@Geometry";
                    cmd.Parameters.Add(param);

                    // generating sql and parameters
                    int    fieldCount = sf.NumFields;
                    string sql        = "INSERT INTO [" + tableName + "] ([Geometry], ";
                    string values     = "VALUES (?, ";

                    for (int j = 0; j < fieldCount; j++)
                    {
                        param = this.CreateParameter();

                        MapWinGIS.Field fld = sf.get_Field(j);
                        switch (fld.Type)
                        {
                        case MapWinGIS.FieldType.STRING_FIELD:

                            param.DbType = DbType.StringFixedLength;
                            param.Size   = fld.Width;
                            break;

                        case MapWinGIS.FieldType.INTEGER_FIELD:
                            param.DbType = DbType.Int32;
                            break;

                        case MapWinGIS.FieldType.DOUBLE_FIELD:
                            param.DbType = DbType.Double;
                            break;
                        }

                        param.ParameterName = "@p" + j.ToString();
                        param.SourceColumn  = fld.Name;
                        cmd.Parameters.Add(param);

                        sql    += "[" + fld.Name + "]";
                        sql    += (j == fieldCount - 1) ? ") " : ", ";
                        values += (j == fieldCount - 1) ? "?)" : "?, ";
                    }
                    cmd.CommandText = sql + values;
                    cmd.Transaction = dbTrans;
                    cmd.Connection  = m_connection;
                    System.Diagnostics.Debug.Print(cmd.CommandText);

                    // adding new records
                    DbParameterCollection paramters = cmd.Parameters;
                    MapWinGIS.Table       table     = sf.Table;
                    int maxSize = 0;
                    int percent = 0;

                    for (int i = 0; i < sf.NumShapes; i++)
                    {
                        if (m_callback != null && m_showCallback)
                        {
                            int newPercent = (int)((double)i / (double)(sf.NumShapes - 1) * 100.0);
                            if (newPercent != percent)
                            {
                                m_callback.Progress("", newPercent, "Exporting shapes...");
                                percent = newPercent;
                            }
                        }

                        object          data  = null;
                        MapWinGIS.Shape shape = sf.get_Shape(i);

                        if (shape.ExportToBinary(ref data))
                        {
                            if ((data as byte[]).Length > maxSize)
                            {
                                maxSize = (data as byte[]).Length;
                            }

                            paramters[0].Value = data as byte[];
                            for (int j = 0; j < fieldCount; j++)
                            {
                                paramters[j + 1].Value = table.get_CellValue(j, i);
                            }
                            if (cmd.ExecuteNonQuery() != 0)
                            {
                                count++;
                            }
                        }
                    }

                    if (m_callback != null && m_showCallback)
                    {
                        m_callback.Progress("", 100, "");
                    }
                }
                dbTrans.Commit();
            }
            return(count);
        }
Beispiel #15
0
        /// <summary>
        /// Exports the shapes that are selected in the MapWindow view to a new shapefile.
        /// </summary>
        /// <param name="MapWin">A reference to the running MapWindow.</param>
        /// <param name="ExportToSFPath">The full path to where the result shapefile should be saved.</param>
        /// <param name="AddToMap">Indicates that the output should be added to the map view immediately.</param>
        /// <returns>False if an error occurs, true otherwise.</returns>
        public static bool ExportSelectedMWViewShapes(MapWindow.Interfaces.IMapWin MapWin, string ExportToSFPath, bool AddToMap)
        {
            MapWinUtility.Logger.Dbg("ExportSelectedMWViewShapes(MapWin: IMapWin,\n" +
                                     "                           ExportToSFPath: " + ExportToSFPath + ",\n" +
                                     "                           AddToMap: " + AddToMap.ToString() + ")");

            if (MapWin.Layers.NumLayers == 0)
            {
                gErrorMsg = "Please select a layer first.";
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
            if (MapWin.View.SelectedShapes.NumSelected == 0)
            {
                gErrorMsg = "There are no selected features to export. Please select a feature first.";
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
            MapWinGIS.Shapefile sf     = new MapWinGIS.Shapefile();
            MapWinGIS.Shapefile tollSF = new MapWinGIS.Shapefile();
            MapWinGIS.Field     fld    = new MapWinGIS.Field();
            MapWinGIS.Shape     seg    = new MapWinGIS.Shape();
            int  Segments;
            bool Status;

            Status = sf.Open(MapWin.Layers[MapWin.Layers.CurrentLayer].FileName, null);
            if (Status == false)
            {
                gErrorMsg = sf.get_ErrorMsg(sf.LastErrorCode);
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }

            if (System.IO.File.Exists(ExportToSFPath))
            {
                try
                {
                    DataManagement.DeleteShapefile(ref ExportToSFPath);
                }
                catch
                {
                    gErrorMsg = "The destination file already exists, but could not be deleted. Please check to make sure the file isn't in use.";
                    Error.SetErrorMsg(gErrorMsg);
                    MapWinUtility.Logger.Dbg(gErrorMsg);
                    return(false);
                }
            }

            Status = tollSF.CreateNew(ExportToSFPath, sf.ShapefileType);

            if (Status == false)
            {
                gErrorMsg = tollSF.get_ErrorMsg(tollSF.LastErrorCode);
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }

            try
            {
                tollSF.Projection = sf.Projection;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
            }

            Status = tollSF.StartEditingShapes(true, null);
            if (Status == false)
            {
                gErrorMsg = tollSF.get_ErrorMsg(tollSF.LastErrorCode);
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
            fld.Name  = "MWShapeID";
            fld.Type  = MapWinGIS.FieldType.INTEGER_FIELD;
            fld.Width = 12;
            Segments  = 0;

            // Chris M -- This is already opened above, why open
            // it again here?
            // sf.Open(MapWin.Layers[MapWin.Layers.CurrentLayer].FileName, null);

            for (int j = 0; j <= sf.NumFields - 1; j++)
            {
                tollSF.EditInsertField(sf.get_Field(j), ref j, null);
            }
            MapWin.View.MapCursor = MapWinGIS.tkCursor.crsrWait;
            try
            {
                for (int i = 0; i <= MapWin.View.SelectedShapes.NumSelected - 1; i++)
                {
                    seg    = sf.get_Shape(MapWin.View.SelectedShapes[i].ShapeIndex);
                    Status = tollSF.EditInsertShape(seg, ref Segments);
                    if (Status == false)
                    {
                        gErrorMsg = tollSF.get_ErrorMsg(tollSF.LastErrorCode);
                        Error.SetErrorMsg(gErrorMsg);
                        MapWinUtility.Logger.Dbg(gErrorMsg);
                        return(false);
                    }
                    for (int h = 0; h <= sf.NumFields - 1; h++)
                    {
                        tollSF.EditCellValue(h, i, sf.get_CellValue(h, MapWin.View.SelectedShapes[i].ShapeIndex));
                    }
                    Segments = Segments + 1;
                }
                sf.Close();
                tollSF.StopEditingShapes(true, true, null);
            }
            catch (Exception ex)
            {
                gErrorMsg = ex.Message;
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
            }
            MapWin.View.MapCursor = MapWinGIS.tkCursor.crsrArrow;
            tollSF.Close();
            if (AddToMap)
            {
                MapWin.View.LockMap();
                MapWindow.Interfaces.Layer thelayer;
                thelayer = MapWin.Layers.Add(ExportToSFPath, System.IO.Path.GetFileNameWithoutExtension(ExportToSFPath), true);
                thelayer.ClearLabels();
                MapWin.View.UnlockMap();
            }
            MapWinUtility.Logger.Dbg("Finished ExportSelectedMWViewShapes");
            return(true);
        }
Beispiel #16
0
        /// <summary>
        /// Erases the portions of the polygon shapefile that are within the polygon shape.
        /// </summary>
        /// <param name="polySF">The polygon shapefile.</param>
        /// <param name="polygon">The erase polygon.</param>
        /// <param name="resultSF">The resulting shapefile, with portions removed.</param>
        /// <param name="CopyAttributes">Indicates whether to copy attributes or not.</param>
        /// <returns>False if an error was encountered, true otherwise.</returns>
        public static bool ErasePolySFWithPoly(ref MapWinGIS.Shapefile polySF, ref MapWinGIS.Shape polygon, ref MapWinGIS.Shapefile resultSF, bool CopyAttributes)
        {
            MapWinUtility.Logger.Dbg("ErasePolySFWithPoly(polySF: " + Macro.ParamName(polySF) + ",\n" +
                                     "                    polygon: " + Macro.ParamName(polygon) + ",\n" +
                                     "                    resultSF: " + Macro.ParamName(resultSF) + "\n" +
                                     "                    CopyAttributes: " + CopyAttributes.ToString());
            if (polySF == null || polygon == null || resultSF == null)
            {
                gErrorMsg = "One of the input parameters is null.";
                Error.SetErrorMsg(gErrorMsg);
                Debug.WriteLine(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }

            if (CopyAttributes)
            {
                string          tmpName;
                MapWinGIS.Field tmpField, currField;
                for (int f = 0; f <= polySF.NumFields - 1; f++)
                {
                    tmpField      = new MapWinGIS.Field();
                    currField     = polySF.get_Field(f);
                    tmpName       = currField.Name;
                    tmpField.Name = tmpName;

                    tmpField.Width     = currField.Width;
                    tmpField.Type      = currField.Type;
                    tmpField.Precision = currField.Precision;
                    tmpField.Key       = currField.Key;
                    resultSF.EditInsertField(tmpField, ref f, null);
                }
            }

            int numShapes = polySF.NumShapes;
            int shpIndex  = 0;

            for (int i = 0; i <= numShapes - 1; i++)
            {
                MapWinGIS.Shape currShape = new MapWinGIS.Shape();
                MapWinGIS.Shape resultShp = new MapWinGIS.Shape();

                currShape = polySF.get_Shape(i);

                //if bounds intersect, then check if all polygon points are inside the currShape
                if (Globals.CheckBounds(ref currShape, ref polygon))
                {
                    int  numPts    = polygon.numPoints;
                    bool allInside = true;
                    int  numParts  = currShape.NumParts;
                    if (numParts == 0)
                    {
                        numParts = 1;
                    }
                    Globals.Vertex[][] vertArray = new Globals.Vertex[numParts][];
                    Globals.ConvertPolyToVertexArray(ref currShape, out vertArray);
                    for (int j = 0; j <= numPts - 1; j++)
                    {
                        double x = polygon.get_Point(j).x;
                        double y = polygon.get_Point(j).y;
                        if (Utils.PointInPoly(ref vertArray, x, y) == false)
                        {
                            allInside = false;
                            break;
                        }
                    }

                    if (allInside == true)
                    {
                        resultShp = new MapWinGIS.ShapeClass();
                        resultShp.Create(polygon.ShapeType);
                        //we want the symmetric difference of these two shapes
                        //which should leave us with a hole where the erase polygon was in the currShape
                        resultShp = SpatialOperations.SymmetricDifference(polygon, currShape);
                    }
                    else
                    {
                        //erase overlapping section and add result to the file.
                        MapWinGIS.Shape intersect = new MapWinGIS.ShapeClass();
                        intersect.ShapeType = polygon.ShapeType;
                        intersect           = SpatialOperations.Intersection(polygon, currShape);
                        if (intersect.numPoints > 0)
                        {
                            //there might be parts in the difference result that do not belong,
                            //perform an intersection operation with currShape to remove them.
                            MapWinGIS.Shape diff = new MapWinGIS.ShapeClass();
                            diff.ShapeType = polygon.ShapeType;
                            //diff = SpatialOperations.SymmetricDifference(intersect, currShape);
                            diff = SpatialOperations.Difference(currShape, polygon);
                            int numPoints = diff.numPoints;
                            if (numPoints > 0)
                            {
                                resultShp = diff;
                            }                    //difference operation successful
                        }                        //intersect operation successful
                        else
                        {
                            //no intersection, shapes do not collide
                            resultShp = currShape;
                        }
                    }                    //all points of erase polygon are not inside currShape

                    if (resultShp.numPoints > 0)
                    {
                        shpIndex = resultSF.NumShapes;
                        if (resultSF.EditInsertShape(resultShp, ref shpIndex) == false)
                        {
                            gErrorMsg = "ErasePolySF: problem inserting shape into result file: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                            Debug.WriteLine(gErrorMsg);
                            Error.SetErrorMsg(gErrorMsg);
                            MapWinUtility.Logger.Dbg(gErrorMsg);
                            return(false);
                        }
                        if (CopyAttributes)
                        {
                            for (int f = 0; f <= polySF.NumFields - 1; f++)
                            {
                                bool tmpbool = resultSF.EditCellValue(f, shpIndex, polySF.get_CellValue(f, i));
                            }
                        }
                    }
                }                //end of if bounds intersect
                else
                {
                    //the erase object does not intersect with the current polygon,
                    //add current polygon to resultSF in unchanged form
                    shpIndex = resultSF.NumShapes;
                    if (resultSF.EditInsertShape(currShape, ref shpIndex) == false)
                    {
                        gErrorMsg = "ErasePolySF: problem inserting shape into result file: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                        Debug.WriteLine(gErrorMsg);
                        Error.SetErrorMsg(gErrorMsg);
                        MapWinUtility.Logger.Dbg(gErrorMsg);
                        return(false);
                    }
                    if (CopyAttributes)
                    {
                        for (int f = 0; f <= polySF.NumFields - 1; f++)
                        {
                            bool tmpbool = resultSF.EditCellValue(f, shpIndex, polySF.get_CellValue(f, i));
                        }
                    }
                }
            }            //end of looping through shapes in shapefile
            MapWinUtility.Logger.Dbg("Finished ErasePolySFWithPoly");
            return(true);
        }
Beispiel #17
0
        /// <summary>
        /// Converts a list of 3d-points to a point shapefile with z-value field.
        /// This function creates a new shapefile. The shapefile has two fields:
        /// a 'MWShapeId' field and a field which contains the z-value.
        /// </summary>
        /// <param name="ShpFileName">Name of the resulting point shapefile</param>
        /// <param name="ZFieldName">Name of the z-field in the shapefile</param>
        public void ToShapefile(string ShpFileName, string ZFieldName)
        {
            MapWinGIS.Shapefile newSF = new MapWinGIS.Shapefile();
            try
            {
                Hashtable FieldIndices = new Hashtable();

                MapWinGIS.ShpfileType sftype;
                sftype = MapWinGIS.ShpfileType.SHP_POINT;
                int fldIdx = 0;

                // if shapefile exists - open it and clear all shapes
                if (System.IO.File.Exists(ShpFileName))
                {
                    newSF.Open(ShpFileName, null);
                    newSF.StartEditingShapes(true, null);
                    newSF.EditClear();
                }
                else //else, create a new shapefile
                {
                    if (!newSF.CreateNew(ShpFileName, sftype))
                    {
                        throw new InvalidOperationException
                                  ("Error creating shapefile " + newSF.get_ErrorMsg(newSF.LastErrorCode));
                    }
                    newSF.StartEditingShapes(true, null);
                }

                //check existing fields:
                for (int i = 0; i < newSF.NumFields; ++i)
                {
                    MapWinGIS.Field fl = newSF.get_Field(i);
                    if (fl.Name == "MWShapeID")
                    {
                        FieldIndices.Add("MWShapeID", i);
                    }
                    if (fl.Name == ZFieldName)
                    {
                        FieldIndices.Add(ZFieldName, i);
                    }
                }

                //Add the fields:
                if (!FieldIndices.ContainsKey("MWShapeID"))
                {
                    //First an ID field
                    MapWinGIS.Field idFld = new MapWinGIS.Field();
                    idFld.Name = "MWShapeID";
                    idFld.Type = MapWinGIS.FieldType.INTEGER_FIELD;
                    fldIdx     = newSF.NumFields;

                    if (newSF.EditInsertField(idFld, ref fldIdx, null) == false)
                    {
                        throw new InvalidOperationException("error inserting field " +
                                                            newSF.get_ErrorMsg(newSF.LastErrorCode));
                    }
                    FieldIndices.Add("MWShapeID", fldIdx);
                }

                if (!FieldIndices.ContainsKey(ZFieldName))
                {
                    //Second add a Z-field
                    MapWinGIS.Field zFld = new MapWinGIS.Field();
                    zFld.Name = "Z";
                    zFld.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
                    fldIdx    = newSF.NumFields;

                    if (newSF.EditInsertField(zFld, ref fldIdx, null) == false)
                    {
                        throw new InvalidOperationException("error inserting field " +
                                                            newSF.get_ErrorMsg(newSF.LastErrorCode));
                    }
                    FieldIndices.Add("Z", fldIdx);
                }

                foreach (ICoordinate pt in _points)
                {
                    //first, add a point shape (geometry)
                    MapWinGIS.Shape newShp = new MapWinGIS.Shape();
                    newShp.Create(MapWinGIS.ShpfileType.SHP_POINT);
                    MapWinGIS.Point newPt = new MapWinGIS.Point();
                    newPt.x = pt.X;
                    newPt.y = pt.Y;
                    int ptIdx = 0;
                    newShp.InsertPoint(newPt, ref ptIdx);
                    int shpIdx = newSF.NumShapes;
                    newSF.EditInsertShape(newShp, ref shpIdx);

                    //second add the z-value
                    newSF.EditCellValue(fldIdx, shpIdx, pt.Z);
                }
            }
            finally
            {
                //finally stop editing and close the shapefile
                newSF.StopEditingShapes(true, true, null);
                if (newSF.Close() == false)
                {
                    throw new InvalidOperationException("error closing shapefile " +
                                                        newSF.get_ErrorMsg(newSF.LastErrorCode));
                }
            }
        }
Beispiel #18
0
 private void populateFields(string shpFileName)
 {
     cmbFields.Items.Clear();
     MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
     MapWinGIS.Field curField;
     if (sf.Open(shpFileName,sf.GlobalCallback))
     {
         for (int i = 0; i < sf.NumFields; ++i)
         {
             curField = sf.get_Field(i);
             if (curField.Type == MapWinGIS.FieldType.DOUBLE_FIELD ||
                 curField.Type == MapWinGIS.FieldType.INTEGER_FIELD)
             {
                 cmbFields.Items.Add(curField.Name);
             }
         }
         sf.Close();
     }
     if (cmbFields.Items.Count > 0)
     {
         cmbFields.SelectedIndex = 0;
     }
 }