예제 #1
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();
        }
예제 #2
0
        public bool Open(string connectionString)
        {
            var opened = _datasource.Open(connectionString);

            return(opened);
        }
예제 #3
0
        public void ReadAttributesFromPostGISLayer()
        {
            var ogrDatasource = new OgrDatasource();

            try
            {
                var result = ogrDatasource.Open("PG:host=127.0.0.1 port=5432 dbname=mw_test user=mapwindow password=test123");
                Assert.IsTrue(result, "Cannot open PostGIS Connectie: " + ogrDatasource.GdalLastErrorMsg);
                Assert.IsTrue(ogrDatasource.LayerCount > 1, "No layers found");

                OgrLayer attributeLayer = null;
                for (var i = 0; i < ogrDatasource.LayerCount; i++)
                {
                    var layer = ogrDatasource.GetLayer(i);
                    Console.WriteLine(layer.Name);
                    if (layer.Name == "attributes")
                    {
                        attributeLayer = layer;
                    }
                }

                Assert.IsNotNull(attributeLayer, "Couldn't find the attribute layer");
                Console.WriteLine("Working with attributes layer");

                var sf = attributeLayer.GetBuffer();
                Assert.IsNotNull(sf, "Could not get buffer");

                var numShapes = sf.NumShapes;
                Assert.AreEqual(3, numShapes);

                var numFields = sf.NumFields;
                Assert.IsTrue(numFields > 0, "No fields found");

                var fidColumn = attributeLayer.FIDColumnName;
                Console.WriteLine("fidColumn: " + fidColumn);

                // First shape has all attributes filled:
                Console.WriteLine("Testing first shape, all filled");
                for (var fieldIndex = 0; fieldIndex < numFields; fieldIndex++)
                {
                    var value = sf.CellValue[fieldIndex, 0];
                    Console.WriteLine($"{sf.Field[fieldIndex].Name}: {value}");
                    Assert.IsNotNull(value, $"{sf.Field[fieldIndex].Name} should not be null");
                }

                // Second shape has only the geometry filled and the rest default values (which should be NULL):
                Console.WriteLine("Testing second shape, default values");
                var numNonNulls = 0;
                for (var fieldIndex = 0; fieldIndex < numFields; fieldIndex++)
                {
                    var value = sf.CellValue[fieldIndex, 1];
                    Console.WriteLine($"{sf.Field[fieldIndex].Name}: {value}");
                    // Skip FID because it always has a value:
                    if (sf.Field[fieldIndex].Name == fidColumn)
                    {
                        continue;
                    }
                    if (value != null)
                    {
                        numNonNulls++;
                    }
                }
                if (numNonNulls > 0)
                {
                    // No assert, need to check the third shape as well:
                    Console.WriteLine($"Error! Second shape has {numNonNulls} non NULL fields!");
                }

                // Third shape has all fields explicitly NULL:
                Console.WriteLine("Testing third shape, all null");
                numNonNulls = 0;
                for (var fieldIndex = 0; fieldIndex < numFields; fieldIndex++)
                {
                    var value = sf.CellValue[fieldIndex, 2];
                    Console.WriteLine($"{sf.Field[fieldIndex].Name}: {value}");
                    // Skip FID because it always has a value:
                    if (sf.Field[fieldIndex].Name == fidColumn)
                    {
                        continue;
                    }
                    if (value != null)
                    {
                        numNonNulls++;
                    }
                }
                Assert.AreEqual(0, numNonNulls, $"Third shape has {numNonNulls} non NULL fields!");
            }
            finally
            {
                ogrDatasource.Close();
            }
        }
예제 #4
0
 public bool Open(string connectionString)
 {
     return(_datasource.Open(connectionString));
 }
        public bool StartEditingLayer(string name, bool saveAndStopWhenFinish = false, FeatureType featureType = FeatureType.Any)
        {
            ILayer editLayer = MapControlTools.Layers.Where(m => m.Name == name).FirstOrDefault();

            if (editLayer == null)
            {
                return(false);
            }

            this.saveAndCloseWhenFinish = saveAndStopWhenFinish;

            Shapefile sf;

            var ogrLayer = AxMap.get_OgrLayer(editLayer.Handle);

            sf = AxMap.get_Shapefile(editLayer.Handle);

            _currentEditingLayer = editLayer;

            if (ogrLayer != null)
            {
                // Add the editing layer
                DBConnectionTool dBConnection = new DBConnectionTool(AxMap, MapControlTools);
                OgrDatasource    ds           = new OgrDatasource();
                if (!ds.Open(dBConnection.GetGdalConnectionString()))
                {
                    Events.MapControl_Error error = new Events.MapControl_Error()
                    {
                        ErrorCode = Events.ErrorCodes.CouldNotConnectDatabase, InMethod = "AddPostGISLayer", AxMapError = ds.GdalLastErrorMsg
                    };
                    On_Error(error);
                    return(false);
                }
                OgrLayer editlayer = null;
                if (featureType == FeatureType.Point)
                {
                    editlayer = ds.GetLayerByName(((ResTBPostGISLayer)editLayer).SQL_Layer + "(point)", true);
                    if (editLayer.GetType() == typeof(ResTBDamagePotentialLayer))
                    {
                        editLayer.Handle = ((ResTBDamagePotentialLayer)editLayer).PointHandle;
                    }
                }
                else if (featureType == FeatureType.Line)
                {
                    editlayer = ds.GetLayerByName(((ResTBPostGISLayer)editLayer).SQL_Layer + "(line)", true);
                    if (editLayer.GetType() == typeof(ResTBDamagePotentialLayer))
                    {
                        editLayer.Handle = ((ResTBDamagePotentialLayer)editLayer).LineHandle;
                    }
                }
                else if (featureType == FeatureType.Polygon)
                {
                    editlayer = ds.GetLayerByName(((ResTBPostGISLayer)editLayer).SQL_Layer + "(polygon)", true);
                    if (editLayer.GetType() == typeof(ResTBDamagePotentialLayer))
                    {
                        editLayer.Handle = ((ResTBDamagePotentialLayer)editLayer).PolygonHandle;
                    }
                }
                else
                {
                    editlayer = ds.GetLayerByName(((ResTBPostGISLayer)editLayer).SQL_Layer, true);
                }

                int editinghandle = AxMap.AddLayer(editlayer, false);
                ((ResTBPostGISLayer)editLayer).EditingLayer       = editlayer;
                ((ResTBPostGISLayer)editLayer).EditingLayerHandle = editinghandle;

                _currentEditingLayer = editLayer;

                OgrLayer ogrLayer2 = ((ResTBPostGISLayer)editLayer).EditingLayer;
                if (ogrLayer2.DynamicLoading)
                {
                    Events.MapControl_Error error = new Events.MapControl_Error()
                    {
                        ErrorCode = Events.ErrorCodes.EditingNotAllowed, InMethod = "StartEditingLayer", AxMapError = ""
                    };
                    On_Error(error);
                    return(false);
                }
                if (!ogrLayer2.SupportsEditing[tkOgrSaveType.ostSaveAll])
                {
                    Events.MapControl_Error error = new Events.MapControl_Error()
                    {
                        ErrorCode = Events.ErrorCodes.EditingNotSupported, InMethod = "StartEditingLayer", AxMapError = ogrLayer2.ErrorMsg[ogrLayer.LastErrorCode]
                    };
                    On_Error(error);
                    return(false);
                }

                AxMap.set_LayerVisible(editLayer.Handle, false);

                AxMap.set_LayerVisible(((ResTBPostGISLayer)editLayer).EditingLayerHandle, true);
                sf = AxMap.get_Shapefile(((ResTBPostGISLayer)editLayer).EditingLayerHandle);

                Utils utils = new Utils();
                if (featureType == FeatureType.Point)
                {
                    sf.DefaultDrawingOptions.PointSize = 15;
                    sf.DefaultDrawingOptions.FillColor = utils.ColorByName(tkMapColor.Blue);
                }
                else
                {
                    sf.DefaultDrawingOptions.LineWidth = 7;
                    sf.DefaultDrawingOptions.FillColor = utils.ColorByName(tkMapColor.Blue);
                    sf.DefaultDrawingOptions.LineColor = utils.ColorByName(tkMapColor.Blue);
                    AxMap.ShapeEditor.FillColor        = utils.ColorByName(tkMapColor.Blue);
                }

                //AxMap.ShapeEditor.LineWidth = 20;
                AxMap.ShapeEditor.LineColor = utils.ColorByName(tkMapColor.Blue);
                sf.VisibilityExpression     = ((ResTBPostGISLayer)editLayer).VisibilityExpression;
            }

            AxMap.SendMouseDown = true;
            AxMap.SendMouseUp   = true;

            AxMap.ChooseLayer           += AxMap_ChooseLayer;
            AxMap.AfterShapeEdit        += _map_AfterShapeEdit;
            AxMap.BeforeDeleteShape     += _map_BeforeDeleteShape;
            AxMap.BeforeShapeEdit       += _map_BeforeShapeEdit;
            AxMap.ShapeValidationFailed += _map_ShapeValidationFailed;
            AxMap.ValidateShape         += _map_ValidateShape;

            AxMap.ShapeEditor.IndicesVisible = false;
            AxMap.ShapeEditor.ShowLength     = false;
            AxMap.ShapeEditor.ShowArea       = false;
            AxMap.ShapeEditor.ValidationMode = tkEditorValidation.evFixWithGeos;

            if ((featureType == FeatureType.Point) || (featureType == FeatureType.Line))
            {
                AxMap.ShapeEditor.SnapBehavior = tkLayerSelection.lsNoLayer;
            }
            else
            {
                AxMap.ShapeEditor.SnapBehavior = tkLayerSelection.lsAllLayers;
            }

            sf.InteractiveEditing = true;
            Events.MapControl_EditingStateChange editingStateChange = new Events.MapControl_EditingStateChange()
            {
                EditingState = Events.EditingState.StartEditing, EditingLayer = editLayer
            };
            On_EditingStateChange(editingStateChange);



            return(true);
        }