예제 #1
0
        /// <summary>
        /// closes and makes null layout shapefile and sets layout handle to -1
        /// </summary>
        public void ClearLayout()
        {
            if (_sfLayout != null)
            {
                _sfLayout.Close();
                _sfLayout = null;

                if (_hsfLayout > 0)
                {
                    _majorGrid.MaplayersHandler.RemoveLayer(_hsfLayout);
                }
                _hsfLayout = -1;
            }
        }
예제 #2
0
        public void FixUpShapes()
        {
            // MWGIS-90
            // Open shapefile:
            var sfInvalid = new Shapefile {
                GlobalCallback = this
            };
            Shapefile sfFixed = null;

            try
            {
                var result = sfInvalid.Open(@"sf\invalid.shp");
                Assert.IsTrue(result, "Could not open shapefile");

                Assert.IsTrue(sfInvalid.HasInvalidShapes(), "Shapefile has no invalid shapes");
                Helper.PrintExtents(sfInvalid.Extents);

                result = sfInvalid.FixUpShapes(out sfFixed);
                Assert.IsTrue(result, "Could not fix shapefile");
                Assert.IsFalse(sfFixed.HasInvalidShapes(), "Returning shapefile has invalid shapes");

                Assert.AreEqual(sfInvalid.NumShapes, sfFixed.NumShapes, "Number of shapes are not equal");
                Helper.PrintExtents(sfFixed.Extents);
            }
            finally
            {
                sfInvalid.Close();
                sfFixed?.Close();
            }
        }
예제 #3
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         ShapeFile?.Close();
     }
 }
예제 #4
0
 public void Clear()
 {
     if (_buffer != null)
     {
         _buffer.Close();
         _buffer = null;
     }
 }
예제 #5
0
 public void Dispose()
 {
     if (_shapefile != null)
     {
         _shapefile.Close();
         _shapefile = null;
     }
 }
예제 #6
0
        private void CreateShape(string path, DataTable dataTable)
        {
            Shapefile myShapefile;

            try
            {
                myShapefile = new Shapefile();
                string fileName     = Path.GetFileNameWithoutExtension(txtBox_excel.Text);
                string shapeilePath = Path.GetDirectoryName(path) + "\\" + fileName + ".shp";

                Directory.CreateDirectory(Path.GetDirectoryName(shapeilePath));

                myShapefile.CreateNew(shapeilePath, ShpfileType.SHP_POINT);
                //Create new field
                MapWinGIS.Field myField = new Field();
                //Set the field properties
                myField.Name  = "ID";
                myField.Type  = FieldType.INTEGER_FIELD;
                myField.Width = 10;
                //Add the filed for the shapefile table
                int intFieldIndex = 1;
                myShapefile.EditInsertField(myField, ref intFieldIndex, null);
                int myCounter    = 0;
                int myShapeIndex = 0;

                //First Create header
                CreateHeader(dataTable.Columns, myShapefile);
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    MapWinGIS.Shape myShape = new Shape();
                    myShape.Create(ShpfileType.SHP_POINT);
                    MapWinGIS.Point myPoint = new MapWinGIS.Point();
                    myPoint.x = Convert.ToDouble(dataTable.Rows[i][x_Index]);
                    myPoint.y = Convert.ToDouble(dataTable.Rows[i][y_Index]);
                    object fld_Value    = dataTable.Rows[i][0];
                    int    myPointIndex = 0;
                    myShape.InsertPoint(myPoint, ref myPointIndex);
                    myShapefile.EditInsertShape(myShape, ref myShapeIndex);
                    myShapefile.EditCellValue(0, myShapeIndex, fld_Value);
                    CreatePointData(dataTable, myShapefile, myShapeIndex, i);
                    myShapeIndex++;
                    myCounter++;
                }
                GeoProjection proj = new GeoProjection();
                // EPSG code
                proj.ImportFromEPSG(4326);  // WGS84

                myShapefile.GeoProjection = proj;
                myShapefile.StopEditingShapes(true, true, null);
                myShapefile.Close();
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #7
0
        public void LoadAisTrail(PointSet pointSet)
        {
            Shapefile sf = map.get_Shapefile(shapfileHandle);

            if (sf != null)
            {
                sf.Close();
            }
            //shapfileHandle = drawPoint.CreatPoint(point, pointSet);
        }
예제 #8
0
        private static void MergeShapefile(tkGeometryEngine geometryEngine)
        {
            var tempFolder = Helper.WorkingFolder("MergeShapefile");

            const string sfInputfile  = @"D:\dev\GIS-Data\Issues\MWGIS-78 Clipper\FewPolygons.shp";
            var          sfOutputFile = Path.Combine(tempFolder, $"FewPolygons_Merged_{geometryEngine.ToString()}.shp");

            var sfInput = Helper.OpenShapefile(sfInputfile);

            if (File.Exists(sfOutputFile))
            {
                Helper.DeleteShapefile(sfOutputFile);
            }

            var stopWatch = new Stopwatch();

            stopWatch.Start();
            sfInput.GeometryEngine = geometryEngine;
            var newShape = sfInput.Shape[0];

            for (var i = 1; i < sfInput.NumShapes; i++)
            {
                // Union all shapes together:
                newShape = newShape.Clip(sfInput.Shape[i], tkClipOperation.clUnion);
            }
            Helper.DebugMsg("Time it took: " + stopWatch.Elapsed);
            stopWatch.Restart();
            Assert.IsNotNull(newShape, "newShape is null: " + newShape.ErrorMsg[newShape.LastErrorCode]);

            var sfOutput = new Shapefile();

            sfOutput.CreateNewWithShapeID(sfOutputFile, ShpfileType.SHP_POLYGON);
            var numShape = 0;
            var retVal   = sfOutput.EditInsertShape(newShape, ref numShape);

            Assert.IsTrue(retVal, "Failed to add shape");
            sfOutput.StopEditingShapes();

            Assert.IsTrue(File.Exists(sfOutputFile), "Output does not exists");
            Helper.DebugMsg(sfOutputFile);

            Helper.DebugMsg("NumShapes: " + sfOutput.NumShapes);
            Assert.AreEqual(sfOutput.NumShapes, 1);

            if (!sfInput.Close())
            {
                Assert.Fail("Can't close sfBorder Error: " + sfInput.ErrorMsg[sfInput.LastErrorCode]);
            }
            if (!sfOutput.Close())
            {
                Assert.Fail("Can't close sfClipped Error: " + sfOutput.ErrorMsg[sfOutput.LastErrorCode]);
            }
        }
예제 #9
0
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         if (disposing)
         {
         }
         if (_shapefileMinorGridLines != null)
         {
             _shapefileMinorGridLines.Close();
             _shapefileMinorGridLines = null;
             _minorGridExtents        = null;
             _axMap = null;
         }
         _disposed = true;
     }
 }
예제 #10
0
        public void FixUpShapes()
        {
            var utils = new Utils {
                GlobalCallback = this
            };
            // Open shapefile:
            var sfInvalid = new Shapefile();
            var sfFixed   = new Shapefile();

            try
            {
                var result = sfInvalid.Open(@"sf\invalid.shp");
                Assert.IsTrue(result, "Could not open shapefile");

                result = sfInvalid.HasInvalidShapes();
                Assert.IsTrue(result, "Shapefile has no invalid shapes");
                Helper.PrintExtents(sfInvalid.Extents);

                for (var i = 0; i < sfInvalid.NumShapes; i++)
                {
                    var shp = sfInvalid.Shape[i];
                    Assert.IsFalse(shp.IsValid, "Shape should be invalid");
                    var reason = shp.IsValidReason;
                    Console.WriteLine(reason);
                    Assert.IsFalse(string.IsNullOrEmpty(reason), "Cannot get validation reason");
                }

                var newFilename = Path.Combine(Path.GetTempPath(), "FixUpShapes.shp");
                result = utils.FixUpShapes(sfInvalid, false, newFilename, true);
                Assert.IsTrue(result, "Could not fix shapefile");
                Assert.IsTrue(File.Exists(newFilename), newFilename + " doesn't exists");

                result = sfFixed.Open(newFilename);
                Assert.IsTrue(result, "Could not open fixed shapefile");

                Assert.AreEqual(sfInvalid.NumShapes, sfFixed.NumShapes, "Number of shapes are not equal");
                Helper.PrintExtents(sfFixed.Extents);
            }
            finally
            {
                sfInvalid.Close();
                sfFixed.Close();
            }
        }
예제 #11
0
        public void CopyAttributesToClipped()
        {
            var target = new ClipPolygonWithPolygon();

            // load input 1 Shapefile as IFeatureSet
            IFeatureSet europeShape = Shapefile.OpenFile(@"Data\ClipPolygonWithPolygonTests\EUR_countries.shp");

            // load input 2 Shapefile as IFeatureSet
            IFeatureSet belgiumShape = Shapefile.OpenFile(@"Data\ClipPolygonWithPolygonTests\Belgium.shp");

            // set output file as IFeatureSet shapefile
            IFeatureSet outputShape = new Shapefile()
            {
                Filename = FileTools.GetTempFileName(".shp")
            };

            target.Execute(europeShape, belgiumShape, outputShape, new MockProgressHandler());

            // the output file needs to be closed and re-opened, because the DataTable in memory does not match the DataTable on disk
            outputShape.Close();
            var outputFile = FeatureSet.Open(outputShape.Filename);

            try
            {
                // output shapefile attribute columns should match the input 1 attribute columns
                Assert.That(outputFile.DataTable.Columns[0].Caption.Equals("ID"));
                Assert.That(outputFile.DataTable.Columns[1].Caption.Equals("Name"));

                string[,] dataValues = { { "BE", "Belgium" }, { "DE", "Germany" }, { "LU", "Luxembourg" } };

                var mpCount = 0;
                foreach (var feature in outputFile.Features)
                {
                    Assert.That(feature.DataRow.ItemArray.Length == 2 && feature.DataRow.ItemArray[0].Equals(dataValues[mpCount, 0]) && feature.DataRow.ItemArray[1].Equals(dataValues[mpCount, 1]));
                    mpCount++;
                }
                Assert.That(mpCount == 3);
            }
            finally
            {
                FileTools.DeleteShapeFile(outputShape.Filename);
            }
        }
예제 #12
0
        public void AddField()
        {
            bool result;
            var  sf = new Shapefile {
                GlobalCallback = this
            };

            try
            {
                // Create in-memory shapefile
                result = sf.CreateNewWithShapeID(string.Empty, ShpfileType.SHP_POINT);
                Assert.IsTrue(result, "Could not create shapefile");

                Assert.IsTrue(sf.EditingShapes, "Shapefile is not in edit shapes mode");
                Assert.IsTrue(sf.EditingTable, "Shapefile is not in edit table mode");

                // Add fields:
                Assert.IsTrue(sf.Table.EditingTable, "Table is not in edit table mode");
                // This should work:
                var fieldIndex = sf.Table.EditAddField("date", FieldType.STRING_FIELD, 0, 50);
                Assert.AreEqual(sf.NumFields - 1, fieldIndex, "Could not add string field");
                // This should work:
                fieldIndex = sf.Table.EditAddField("double", FieldType.DOUBLE_FIELD, 10, 20);
                Assert.AreEqual(sf.NumFields - 1, fieldIndex, "Could not add double field");

                // This should fail, because width cannot be 0:
                fieldIndex = sf.Table.EditAddField("date", FieldType.STRING_FIELD, 50, 0);
                Assert.AreEqual(-1, fieldIndex, "Field is not added but -1 is not returned. ");
                Console.WriteLine("Expected error: " + sf.Table.ErrorMsg[sf.Table.LastErrorCode]);

                // This should fail, because precsion cannot be 0 when type is double:
                fieldIndex = sf.Table.EditAddField("date", FieldType.DOUBLE_FIELD, 0, 20);
                Assert.AreEqual(-1, fieldIndex, "Field is not added but -1 is not returned. ");
                Console.WriteLine("Expected error: " + sf.Table.ErrorMsg[sf.Table.LastErrorCode]);
            }
            finally
            {
                // Close the shapefile:
                result = sf.Close();
                Assert.IsTrue(result, "Could not close shapefile");
            }
        }
예제 #13
0
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         if (disposing)
         {
             _frameWidthDict.Clear();
             _frameWidthDict = null;
         }
         if (_shapeFileMask != null)
         {
             _shapeFileMask.EditClear();
             _shapeFileMask.Close();
             _shapeFileMask = null;
         }
         MapLayersHandler = null;
         _axMap           = null;
         _disposed        = true;
     }
 }
예제 #14
0
        public void SaveShapefileTest()
        {
            var tempFolder   = Path.GetTempPath();
            var tempFilename = Path.Combine(tempFolder, "CreateShapefileTest.shp");

            Helper.DeleteShapefile(tempFilename);

            bool result;
            // Create shapefile
            var sf = new Shapefile {
                GlobalCallback = this
            };

            try
            {
                result = sf.CreateNewWithShapeID(tempFilename, ShpfileType.SHP_POINT);
                Assert.IsTrue(result, "Could not create shapefile");

                Assert.IsTrue(sf.EditingShapes, "Shapefile is not in edit shapes mode");
                Assert.IsTrue(sf.EditingTable, "Shapefile is not in edit table mode");

                // Add fields:
                var fieldIndex = sf.EditAddField("date", FieldType.STRING_FIELD, 0, 50);
                Assert.AreEqual(1, fieldIndex, "Could not add field");
                fieldIndex = sf.EditAddField("remarks", FieldType.STRING_FIELD, 0, 100);
                Assert.AreEqual(2, fieldIndex, "Could not add field");
                fieldIndex = sf.EditAddField("amount", FieldType.INTEGER_FIELD, 0, 3);
                Assert.AreEqual(3, fieldIndex, "Could not add field");
                Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect");

                result = sf.Save();
                Assert.IsTrue(result, "Could not save shapefile");
                Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect");
            }
            finally
            {
                // Close the shapefile:
                result = sf.Close();
                Assert.IsTrue(result, "Could not close shapefile");
            }
        }
예제 #15
0
        public void LoadAmericanData()
        {
            const string sfLocation = @"D:\dev\GIS-Data\MapWindow-Projects\UnitedStates\Shapefiles\states.shp";

            var sf = new Shapefile {
                GlobalCallback = this
            };

            if (!sf.Open(sfLocation))
            {
                Assert.Fail("Can't open " + sfLocation + " Error: " + sf.ErrorMsg[sf.LastErrorCode]);
            }

            var value = sf.CellValue[1, 0] as string;

            sf.Close();
            Console.WriteLine(value);
            Assert.IsNotNull(value, "CellValue failed");
            // Value should be Washington
            Assert.AreEqual("washington", value.ToLower());
        }
예제 #16
0
        public void ReadRussianDataFromTable()
        {
            const string sfLocation = @"Issues\MWGIS-72\point.shp";
            const int    fieldIndex = 2;

            var sf = new Shapefile {
                GlobalCallback = this
            };

            if (!sf.Open(sfLocation))
            {
                Assert.Fail("Can't open " + sfLocation + " Error: " + sf.ErrorMsg[sf.LastErrorCode]);
            }

            var value = sf.CellValue[fieldIndex, 0] as string;

            Assert.IsNotNull(value, "No value returned");
            sf.Close();
            Console.WriteLine(value);
            // Value should be Воздух
            Assert.AreEqual('д', value[3]);
        }
예제 #17
0
        public void CreateShapefileTest()
        {
            var tempFolder   = Path.GetTempPath();
            var tempFilename = Path.Combine(tempFolder, "CreateShapefileTest.shp");

            Helper.DeleteShapefile(tempFilename);

            bool result;
            // Create shapefile
            var sf = new Shapefile {
                GlobalCallback = this
            };

            try
            {
                result = sf.CreateNewWithShapeID(tempFilename, ShpfileType.SHP_POINT);
                Assert.IsTrue(result, "Could not create shapefile");

                Assert.IsTrue(sf.EditingShapes, "Shapefile is not in edit shapes mode");
                Assert.IsTrue(sf.EditingTable, "Shapefile is not in edit table mode");

                // Add fields:
                Assert.IsTrue(sf.Table.EditingTable, "Table is not in edit table mode");
                var fieldIndex = sf.Table.EditAddField("date", FieldType.STRING_FIELD, 0, 50);
                Assert.AreEqual(1, fieldIndex, "Could not add field");
                fieldIndex = sf.Table.EditAddField("remarks", FieldType.STRING_FIELD, 0, 100);
                Assert.AreEqual(2, fieldIndex, "Could not add field");
                fieldIndex = sf.Table.EditAddField("amount", FieldType.INTEGER_FIELD, 0, 3);
                Assert.AreEqual(3, fieldIndex, "Could not add field");
                Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect");

                result = sf.Table.Save();
                Assert.IsTrue(result, "Could not save table");
                Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect");

                // Create shape:
                var shp = new Shape();
                result = shp.Create(sf.ShapefileType);
                Assert.IsTrue(result, "Could not create shape");
                // Create point:
                var pnt = new Point
                {
                    x = 200,
                    y = 200
                };
                // Add point:
                var pointIndex = shp.numPoints;
                result = shp.InsertPoint(pnt, ref pointIndex);
                Assert.IsTrue(result, "Could not insert point");
                var shapeIndex = sf.NumShapes;
                result = sf.EditInsertShape(shp, ref shapeIndex);
                Assert.IsTrue(result, "Could not insert shape");
                // Update attributes:
                sf.EditCellValue(fieldIndex, shapeIndex, 3);

                result = sf.Save();
                Assert.IsTrue(result, "Could not save shapefile");

                // Check shapefile:
                Assert.AreEqual(shapeIndex + 1, sf.NumShapes, "Number of shapes are incorrect");
                Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect");

                // Close shapefile and re-open:
                result = sf.Close();
                Assert.IsTrue(result, "Could not close shapefile");

                result = sf.Open(tempFilename);
                Assert.IsTrue(result, "Could not open shapefile");
                // Check shapefile:
                Assert.AreEqual(shapeIndex + 1, sf.NumShapes, "Number of shapes are incorrect");
                Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect");
            }
            finally
            {
                // Close the shapefile:
                result = sf.Close();
                Assert.IsTrue(result, "Could not close shapefile");
            }
        }
예제 #18
0
        public void CheckNullValueTableData()
        {
            bool result;
            var  sf = new Shapefile {
                GlobalCallback = this
            };

            try
            {
                // Create in-memory shapefile
                result = sf.CreateNewWithShapeID(string.Empty, ShpfileType.SHP_POINT);
                Assert.IsTrue(result, "Could not create shapefile");

                // Add fields:
                var fieldIndex = sf.Table.EditAddField("string", FieldType.STRING_FIELD, 0, 50);
                Assert.AreEqual(1, fieldIndex, "Could not add field");

                fieldIndex = sf.Table.EditAddField("integer", FieldType.INTEGER_FIELD, 0, 50);
                Assert.AreEqual(2, fieldIndex, "Could not add field");

                fieldIndex = sf.Table.EditAddField("double", FieldType.DOUBLE_FIELD, 2, 50);
                Assert.AreEqual(3, fieldIndex, "Could not add field");

                fieldIndex = sf.Table.EditAddField("double", FieldType.DOUBLE_FIELD, 0, 50);
                Assert.AreEqual(-1, fieldIndex, "Field was added. This is not correct.");

                Assert.AreEqual(4, sf.NumFields, "Wrong number of fields");

                // Create shape:
                var shp = new Shape();
                result = shp.Create(ShpfileType.SHP_POINT);
                Assert.IsTrue(result, "Could not create point shape");
                // Create point:
                var pnt = new Point
                {
                    x = 200,
                    y = 200
                };
                // Add point:
                var pointIndex = shp.numPoints;
                result = shp.InsertPoint(pnt, ref pointIndex);
                Assert.IsTrue(result, "Could not insert point");
                var shapeIndex = sf.NumShapes;
                result = sf.EditInsertShape(shp, ref shapeIndex);
                Assert.IsTrue(result, "Could not insert shape");

                // Read attribute data, skip the first because that is the ID which always has a value
                for (var i = 1; i < sf.NumFields; i++)
                {
                    var value = sf.CellValue[i, 0];
                    var field = sf.Field[i];
                    Console.WriteLine($"Is the value of fieldId {i} NULL: {value == null} Type of field is {field.Type}");
                    // Assert.IsNull(value, $"Value with fieldId {i} is not null, but is '{value}'");
                }
            }
            finally
            {
                // Close the shapefile:
                result = sf.Close();
                Assert.IsTrue(result, "Could not close shapefile");
            }
        }
예제 #19
0
        public void PointInPolygon()
        {
            // It goes too fast for DotMemory:
            Thread.Sleep(2000);

            const string folder = @"D:\dev\GIS-Data\Issues\Point in Polygon";

            Assert.IsTrue(Directory.Exists(folder), "Input folder doesn't exists");
            var sfPolygons = new Shapefile {
                GlobalCallback = this
            };
            var sfPoints = new Shapefile {
                GlobalCallback = this
            };
            var found     = 0;
            var stopWatch = new Stopwatch();

            stopWatch.Start();

            try
            {
                var retVal = sfPolygons.Open(Path.Combine(folder, "CatchmentBuilderShapefile.shp"));
                Assert.IsTrue(retVal, "Can't open polygon shapefile");

                retVal = sfPoints.Open(Path.Combine(folder, "Sbk_FGrPt_n.shp"));
                Assert.IsTrue(retVal, "Can't open point shapefile");

                var utils = new Utils {
                    GlobalCallback = this
                };
                var numPolygons = sfPolygons.NumShapes;
                Assert.IsTrue(numPolygons > 0, "No polygon shapes in shapefile");

                // Loop polygons:
                for (var i = 0; i < numPolygons; i++)
                {
                    if (found > 100)
                    {
                        break;
                    }

                    // Get polygon
                    var polygonShape = sfPolygons.Shape[i];
                    Assert.IsNotNull(polygonShape, "polygonShape == null");

                    var numPoints = sfPoints.NumShapes;
                    Assert.IsTrue(numPoints > 0, "No point shapes in shapefile");

                    for (var j = 0; j < numPoints; j++)
                    {
                        var pointShape = sfPoints.Shape[j];
                        Assert.IsNotNull(pointShape, "pointShape == null");

                        if (utils.PointInPolygon(polygonShape, pointShape.Point[0]))
                        {
                            Console.WriteLine($"Point {j} lies in polygon {i}");
                            found++;
                        }
                    }
                }
            }
            finally
            {
                // Close shapefiles:
                sfPolygons.Close();
                sfPoints.Close();
            }

            stopWatch.Stop();
            Console.WriteLine("The process took " + stopWatch.Elapsed);
            Console.WriteLine(found + " matching polygons where found");
        }
예제 #20
0
        // <summary>
        // This code calculates an area of polygons, writes it to the attribute table, and displays as labels.
        // </summary>
        public void CalculateArea(AxMap axMap1, string dataPath)
        {
            axMap1.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR;

            string filename = dataPath + "buildings.shp";

            if (!File.Exists(filename))
            {
                MessageBox.Show("Couldn't file the file: " + filename);
                return;
            }

            var sf = new Shapefile();

            if (!sf.Open(filename, null))
            {
                return;
            }

            if (sf.ShapefileType != ShpfileType.SHP_POLYGON)
            {
                MessageBox.Show("Polygon shapefile is expected." + Environment.NewLine +
                                "Received: " + sf.ShapefileType);
            }
            else
            {
                int layerHandle = axMap1.AddLayer(sf, true);
                sf = axMap1.get_Shapefile(layerHandle);     // in case a copy of shapefile was created by GlobalSettings.ReprojectLayersOnAdding

                int fldIndex = sf.Table.FieldIndexByName["CalcArea"];
                if (fldIndex != -1)
                {
                    if (MessageBox.Show("The area field exists. Do you want to overwrite it?", "",
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    {
                        sf.Close();
                        return;
                    }
                }

                if (!sf.StartEditingTable(null))
                {
                    MessageBox.Show("Failed to start editing mode: " + sf.ErrorMsg[sf.LastErrorCode]);
                    sf.Close();
                }
                else
                {
                    // removing the field in case it is already present
                    if (fldIndex != -1)
                    {
                        if (!sf.EditDeleteField(fldIndex, null))
                        {
                            MessageBox.Show("Failed to delete field: " + sf.ErrorMsg[sf.LastErrorCode]);
                            sf.Close();
                            return;
                        }
                    }

                    //adding the new field in the end of the table
                    fldIndex = sf.EditAddField("CalcArea", FieldType.DOUBLE_FIELD, 12, 12);
                    if (fldIndex == -1)
                    {
                        MessageBox.Show("Failed to insert field: " + sf.ErrorMsg[sf.LastErrorCode]);
                        sf.Close();
                        return;
                    }

                    for (int i = 0; i < sf.NumShapes; i++)
                    {
                        Shape shp = sf.Shape[i];
                        sf.EditCellValue(fldIndex, i, shp.Area);
                    }

                    sf.Labels.Generate("[CalcArea] + \" sqr.m\"", tkLabelPositioning.lpCentroid, true);
                    sf.Labels.FrameVisible = true;
                }
            }
        }
예제 #21
0
        public void ShapefileDataTest()
        {
            var tempFolder        = Path.GetTempPath();
            var tempFilename      = Path.Combine(tempFolder, "ShapefileDataTest.shp");
            var esriShapefilePath = @"C:\dev\MapWinGIS\unittests\MapWinGISTests\Testdata\Issues\MWGIS-48-68\EsriShapefile.shp";

            Helper.DeleteShapefile(tempFilename);

            bool result;
            // Create shapefile
            var sf = new Shapefile {
                GlobalCallback = this
            };

            try
            {
                result = sf.CreateNewWithShapeID(tempFilename, ShpfileType.SHP_POINT);
                Assert.IsTrue(result, "Could not create shapefile");

                Assert.IsTrue(sf.EditingShapes, "Shapefile is not in edit shapes mode");
                Assert.IsTrue(sf.EditingTable, "Shapefile is not in edit table mode");

                // Add fields of each data type:
                var fieldIndex = sf.EditAddField("intField", FieldType.INTEGER_FIELD, 0, 10);
                Assert.AreEqual(1, fieldIndex, "Could not add Integer field");
                var width = sf.Field[fieldIndex].Width;
                Assert.AreEqual(9, width, "Integer field did not shrink to 9 digits");
                fieldIndex = sf.EditAddField("dateField", FieldType.DATE_FIELD, 0, 6);
                Assert.AreEqual(2, fieldIndex, "Could not add Date field");
                width = sf.Field[fieldIndex].Width;
                Assert.AreEqual(8, width, "Date field did not expand to 8 digits");
                fieldIndex = sf.EditAddField("boolField", FieldType.BOOLEAN_FIELD, 0, 3);
                Assert.AreEqual(3, fieldIndex, "Could not add Boolean field");
                width = sf.Field[fieldIndex].Width;
                Assert.AreEqual(1, width, "Boolean field did not shrink to 1 character");
                //
                Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect");

                result = sf.Save();
                Assert.IsTrue(result, "Could not save shapefile");
                Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect");

                // Create shape:
                var shp = new Shape();
                result = shp.Create(ShpfileType.SHP_POINT);
                Assert.IsTrue(result, "Could not create point shape");
                var idx = sf.EditAddShape(shp);
                // Add data:
                result = sf.EditCellValue(sf.FieldIndexByName["intField"], idx, 99);
                Assert.IsTrue(result, "Could not edit intField");
                DateTime dt = System.DateTime.Now;
                result = sf.EditCellValue(sf.FieldIndexByName["dateField"], idx, dt);
                Assert.IsTrue(result, "Could not edit dateField");
                result = sf.EditCellValue(sf.FieldIndexByName["boolField"], idx, true);
                Assert.IsTrue(result, "Could not edit boolField");

                result = sf.StopEditingShapes();
                Assert.IsTrue(result, "Could not stop editing shapefile");

                // Read back data:
                for (idx = 0; idx < sf.NumShapes; idx++)
                {
                    int iField = (int)sf.CellValue[sf.FieldIndexByName["intField"], idx];
                    Assert.AreEqual(iField, 99, "intField value of 99 was not returned");
                    DateTime dField = (DateTime)sf.CellValue[sf.FieldIndexByName["dateField"], idx];
                    Assert.IsTrue(DateTime.Now.DayOfYear.Equals(((DateTime)dField).DayOfYear), "dateField value of Now was not returned");
                    bool bField = (bool)sf.CellValue[sf.FieldIndexByName["boolField"], idx];
                    Assert.AreEqual(bField, true, "boolField value of True was not returned");
                }
            }
            finally
            {
                // Close the shapefile:
                result = sf.Close();
                Assert.IsTrue(result, "Could not close shapefile");
            }

            // although the default setting, indicate intent to interpret Y/N OGR String fields as Boolean
            GlobalSettings gs = new GlobalSettings();

            gs.OgrInterpretYNStringAsBoolean = true;  // setting to false results in exception reading boolField below

            // open as OGRLayer
            OgrDatasource _datasource = new OgrDatasource();

            _datasource.GlobalCallback = this;

            if (_datasource.Open(tempFilename)) // "ESRI Shapefile:" +
            {
                // read layer through OGR library
                IOgrLayer ogrLayer = _datasource.GetLayer(0);
                sf = ogrLayer.GetBuffer();
                for (int idx = 0; idx < sf.NumShapes; idx++)
                {
                    int iField = (int)sf.CellValue[sf.FieldIndexByName["intField"], idx];
                    Assert.AreEqual(iField, 99, "intField value of 99 was not returned");
                    DateTime dField = (DateTime)sf.CellValue[sf.FieldIndexByName["dateField"], idx];
                    Assert.IsTrue(DateTime.Now.DayOfYear.Equals(((DateTime)dField).DayOfYear), "dateField value of Now was not returned");
                    bool bField = (bool)sf.CellValue[sf.FieldIndexByName["boolField"], idx];
                    Assert.AreEqual(bField, true, "boolField value of True was not returned");
                }
                sf.Close();
            }

            // open and read a Shapefile created by ESRI MapObjects, including a Boolean and Date field
            // table has a Boolean 'Inspected' field, and a Date 'InspDate' field
            Assert.IsTrue(sf.Open(esriShapefilePath, this));
            for (int fld = 0; fld < sf.NumFields; fld++)
            {
                Console.WriteLine(string.Format("Field({0}): Name = '{1}', Fieldtype = {2}", fld, sf.Field[fld].Name, sf.Field[fld].Type));
            }
            for (int idx = 0; idx < sf.NumShapes; idx++)
            {
                // read 'Inspected' value as object
                object inspected = sf.CellValue[sf.FieldIndexByName["Inspected"], idx];
                // verify that it's a bool
                Assert.IsTrue(inspected is bool);
                // watch for Inspected rows (there aren't many)
                if ((bool)inspected == true)
                {
                    // read 'InspDate' value as object
                    object dt = sf.CellValue[sf.FieldIndexByName["InspDate"], idx];
                    // verify that it's a Date
                    Assert.IsTrue(dt is DateTime);
                    Console.WriteLine(string.Format("idx = {0}, Inspected = true, Inspection Date = {1}", idx, (DateTime)dt));
                }
            }
            sf.Close();
        }