public void ReadSchemaNamesFromPostGIS()
        {
            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");

                var stopwatch = new Stopwatch();

                stopwatch.Start();
                Console.WriteLine("Using GetLayer:");
                for (var i = 0; i < ogrDatasource.LayerCount; i++)
                {
                    var layer = ogrDatasource.GetLayer(i);
                    Console.WriteLine(layer.Name);
                }
                stopwatch.Stop();
                Console.WriteLine("GetLayer took " + stopwatch.Elapsed);

                // TODO Get layername with schema name
                Assert.Fail("TODO");
            }
            finally
            {
                ogrDatasource.Close();
            }
        }
Beispiel #2
0
        private static void ListLayers()
        {
            var ds = new OgrDatasource();

            if (!ds.Open(CONNECTION_STRING))
            {
                Debug.Print("Failed to establish connection: " + ds.GdalLastErrorMsg);
            }
            else
            {
                int count = ds.LayerCount;
                Debug.Print("Number of layers: " + count);

                Debug.Print("List of layers by name:");
                for (int i = 0; i < count; i++)
                {
                    var lyr = ds.GetLayer(i);
                    Debug.Print("Layer name: " + lyr.Name);
                    Debug.Print("Projection: " + lyr.GeoProjection.ExportToProj4());
                    Debug.Print("Shape type: " + lyr.ShapeType);
                    lyr.Close();
                }
                ds.Close();
            }
        }
        public void ImportShapefileTest()
        {
            var ds = new OgrDatasource();

            try
            {
                if (!ds.Open(CONNECTION_STRING))
                {
                    Assert.Fail("Failed to establish connection: " + ds.GdalLastErrorMsg);
                }

                // Point shapefile:
                ImportShapefile(ds, @"D:\dev\GIS-Data\MapWindow-Projects\UnitedStates\Shapefiles\cities.shp", "cities_points");

                // Polygon shapefile:
                ImportShapefile(ds, @"D:\dev\GIS-Data\MapWindow-Projects\UnitedStates\Shapefiles\states.shp", "states_polygon");

                // Linestring shapefile:
                //ImportShapefile(ds, @"D:\dev\GIS-Data\MapWindow-Projects\UnitedStates\Shapefiles\roads.shp", "roads_linestring");
            }
            finally
            {
                ds.Close();
            }
        }
Beispiel #4
0
        public void OpenSQLiteTest()
        {
            var ogrDatasource = new OgrDatasource();

            try
            {
                var result = ogrDatasource.Open2(@"sqlite\onepoint.sqlite", true);
                Assert.IsTrue(result, "Cannot open SQLite file: " + ogrDatasource.GdalLastErrorMsg);
                var settings = new GlobalSettings {
                    OgrLayerForceUpdateMode = true
                };

                var capability = ogrDatasource.TestCapability(tkOgrDSCapability.odcCreateLayer);
                Debug.WriteLine("odcCreateLayer: " + capability);
                Assert.IsTrue(capability, "Cannot create layer");
                capability = ogrDatasource.TestCapability(tkOgrDSCapability.odcDeleteLayer);
                Debug.WriteLine("odcDeleteLayer: " + capability);
                Assert.IsTrue(capability, "Cannot delete layer");
                capability = ogrDatasource.TestCapability(tkOgrDSCapability.odcCreateDataSource);
                Debug.WriteLine("odcCreateDataSource: " + capability);
                //Assert.IsTrue(capability), "Cannot create datasource");
                capability = ogrDatasource.TestCapability(tkOgrDSCapability.odcDeleteDataSource);
                Debug.WriteLine("odcDeleteDataSource: " + capability);
                //Assert.IsTrue(capability, "Cannot delete datasource");
                capability = ogrDatasource.TestCapability(tkOgrDSCapability.odcCreateGeomFieldAfterCreateLayer);
                Debug.WriteLine("odcCreateGeomFieldAfterCreateLayer: " + capability);
                Assert.IsTrue(capability, "Cannot create GeomField After CreateLayer");

                TestSQLiteLayers(ogrDatasource);
            }
            finally
            {
                ogrDatasource.Close();
            }
        }
Beispiel #5
0
        private bool TestConnection(bool silent)
        {
            var param = ConnectionParams;

            if (param == null)
            {
                return(false);
            }
            string cs = param.GetPostGisConnection();

            bool result = false;
            var  ds     = new OgrDatasource();

            if (!ds.Open(cs))
            {
                MessageHelper.Warn("Failed to open connection: " + ds.GdalLastErrorMsg);
            }
            else
            {
                if (!silent)
                {
                    MessageHelper.Info("Connected successfully");
                }
                result = true;
            }
            ds.Close();
            return(result);
        }
        public void GetBuffer()
        {
            // MWGIS-67
            var ds = new OgrDatasource();

            try
            {
                if (!ds.Open(CONNECTION_STRING))
                {
                    Assert.Fail("Failed to establish connection: " + ds.GdalLastErrorMsg);
                }

                // Get layer using buffer:
                var layer = ds.GetLayerByName("states_polygon");
                Assert.IsNotNull(layer, "layer is null");
                Console.WriteLine("Layer type is " + layer.ShapeType);

                var sfFromBuffer = layer.GetBuffer();
                Assert.IsNotNull(sfFromBuffer, "sfFromBuffer is null");
                Debug.WriteLine("NumShapes: " + sfFromBuffer.NumShapes);

                var tmpFilename = Path.ChangeExtension(Path.Combine(Path.GetTempPath(), Path.GetTempFileName()), ".shp");
                if (!sfFromBuffer.SaveAs(tmpFilename))
                {
                    Assert.Fail("Failed to save shapefile: " + sfFromBuffer.ErrorMsg[sfFromBuffer.LastErrorCode]);
                }
            }
            finally
            {
                ds.Close();
            }
        }
Beispiel #7
0
 internal VectorDatasource(OgrDatasource datasource)
 {
     _datasource = datasource;
     if (datasource == null)
     {
         throw new NullReferenceException("Internal style reference is null.");
     }
 }
        /// <summary>
        ///     The ways to open layer.
        /// </summary>
        private static void WaysToOpenLayer()
        {
            var layer = new OgrLayer();

            string layerName = "waterways";

            // 1) open one of exiting layers in datasource
            if (!layer.OpenFromDatabase(CONNECTION_STRING, layerName, true))
            {
                // waterways = layerName
                Debug.Print("Failed to open layer: " + layer.get_ErrorMsg(layer.LastErrorCode));
            }

            // 2) return temporary layer by a query
            if (!layer.OpenFromQuery(CONNECTION_STRING, "SELECT * FROM " + layerName))
            {
                Debug.Print("Failed to run a query: " + layer.get_ErrorMsg(layer.LastErrorCode));
            }

            // 3) the same using datasource
            var ds = new OgrDatasource();

            if (!ds.Open(CONNECTION_STRING))
            {
                Debug.Print("Failed to open datasource: " + ds.GdalLastErrorMsg);
            }
            else
            {
                layer = ds.GetLayerByName(layerName);
                if (layer == null)
                {
                    Debug.Print("Failed to open layer: " + ds.get_ErrorMsg(ds.LastErrorCode));
                }

                layer = ds.RunQuery("SELECT * FROM " + layerName);
                if (layer == null)
                {
                    Debug.Print("Failed to run a query: " + ds.get_ErrorMsg(ds.LastErrorCode));
                }
            }

            // 4) using FileManager
            var fm = new FileManager();

            layer = fm.OpenFromDatabase(CONNECTION_STRING, layerName); // layer name or query can be passed here
            if (layer == null)
            {
                Debug.WriteLine("Failed to open layer: " + fm.get_ErrorMsg(fm.LastErrorCode));

                // let's check GDAL error as well
                var gs = new GlobalSettings();
                Debug.WriteLine("GDAL error message: " + gs.GdalLastErrorMsg);
            }
        }
Beispiel #9
0
 public static bool OpenDatasource(OgrDatasource ds, ConnectionParams connection)
 {
     if (ds == null)
     {
         return(false);
     }
     if (!ds.Open(connection.GetPostGisConnection()))
     {
         MessageHelper.Warn("Failed to open datasource: " + ds.GdalLastErrorMsg);
         return(false);
     }
     return(true);
 }
Beispiel #10
0
        public void CreateLayerSQLiteTest()
        {
            var ogrDatasource = new OgrDatasource();

            try
            {
                var result = ogrDatasource.Open2(@"sqlite\onepoint.sqlite", true);
                Assert.IsTrue(result, "Cannot open SQLite file: " + ogrDatasource.GdalLastErrorMsg);
                var settings = new GlobalSettings {
                    OgrLayerForceUpdateMode = true
                };

                var capability = ogrDatasource.TestCapability(tkOgrDSCapability.odcCreateLayer);
                Debug.WriteLine("odcCreateLayer: " + capability);
                Assert.IsTrue(capability, "Cannot create layer");

                var originalLayerCount = ogrDatasource.LayerCount;

                var projection = new GeoProjection();
                Assert.IsTrue(projection.SetWgs84(), "Cannot set projection");

                var layerCreated = ogrDatasource.CreateLayer("Test", ShpfileType.SHP_POINT, projection, "OVERWRITE=YES");
                Assert.IsTrue(layerCreated, "Cannot create layer");
                Debug.WriteLine(ogrDatasource.GdalLastErrorMsg);

                Assert.AreEqual(originalLayerCount + 1, ogrDatasource.LayerCount, "New layer isn't created");
                Debug.WriteLine("GetLayerName: " + ogrDatasource.GetLayerName(ogrDatasource.LayerCount - 1));

                var firstLayer = ogrDatasource.GetLayer(0);
                Assert.IsNotNull(firstLayer, $"Could not get first layer: {ogrDatasource.GdalLastErrorMsg}");

                // Get layer:
                var newLayer = ogrDatasource.GetLayer(ogrDatasource.LayerCount - 1, true);
                // var newLayer = ogrDatasource.GetLayerByName("test", true);
                Assert.IsNotNull(newLayer, $"Could not get new layer: {ogrDatasource.GdalLastErrorMsg}");
                // Add field:
                var numFeatures = newLayer.FeatureCount[true];
                Debug.WriteLine("numFeatures: " + numFeatures);

                TestSQLiteLayers(ogrDatasource);
            }
            finally
            {
                if (ogrDatasource.LayerCount > 1)
                {
                    ogrDatasource.DeleteLayer(ogrDatasource.LayerCount);
                }
                ogrDatasource.Close();
            }
        }
        /// <summary>
        /// The test read layer.
        /// </summary>
        /// <param name="layerName">
        /// The layer name.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        private static bool TestReadLayer(string layerName)
        {
            var ds = new OgrDatasource();

            if (!ds.Open(CONNECTION_STRING))
            {
                Debug.Print("Failed to establish connection: " + ds.GdalLastErrorMsg);
            }
            else
            {
                OgrLayer layer = ds.GetLayerByName(layerName, true);

                if (layer != null)
                {
                    layer.GlobalCallback = form;
                    Debug.Print("Layer opened: " + layer.Name);

                    Extents ext;
                    if (layer.get_Extents(out ext))
                    {
                        Debug.Print(ext.ToDebugString());
                    }

                    Debug.Print("Geometry column name: " + layer.GeometryColumnName);
                    Debug.Print("Feature count: " + layer.FeatureCount);
                    Debug.Print("Supports editing: " + layer.get_SupportsEditing(tkOgrSaveType.ostSaveAll));

                    Map.RemoveAllLayers();
                    Map.Projection = tkMapProjection.PROJECTION_WGS84;

                    int handle = Map.AddLayer(layer, true);
                    Map.Redraw();

                    Debug.Print("Layer connection: " + layer.GetConnectionString());
                    Debug.Print("Layer source query: " + layer.GetSourceQuery());

                    string state = layer.Serialize();
                    Debug.Print("Serialized state: " + state);
                }
                else
                {
                    Debug.Print("Failed to open layer: " + layerName);
                }

                ds.Close();
            }

            return(true);
        }
        public static void ImportOgrLayer()
        {
            int layerHandle = App.Legend.SelectedLayer;

            if (layerHandle == -1)
            {
                return;
            }

            var sf = App.Map.get_Shapefile(layerHandle);

            if (sf == null)
            {
                MessageHelper.Info("Selected layer is not a vector layer.");
                return;
            }

            using (var form = new OgrConnectionForm())
            {
                if (form.ShowDialog(MainForm.Instance) == DialogResult.OK)
                {
                    var ds = new OgrDatasource();
                    if (!OgrHelper.OpenDatasource(ds, form.ConnectionParams))
                    {
                        return;
                    }

                    string layerName = App.Map.get_LayerName(layerHandle);
                    layerName = layerName.Replace(".", "_");

                    using (var importForm = new OgrImportShapefile(layerName))
                    {
                        if (importForm.ShowDialog(MainForm.Instance) == DialogResult.OK)
                        {
                            layerName = importForm.LayerName;
                            if (!ds.ImportShapefile(sf, layerName, "", tkShapeValidationMode.NoValidation))
                            {
                                MessageHelper.Warn("Failed to import shapefile: " + ds.GdalLastErrorMsg);
                            }
                            else
                            {
                                MessageHelper.Info("Layer was imported: " + layerName);
                            }
                        }
                    }
                }
            }
        }
Beispiel #13
0
        /// <summary>
        /// Run non execute query, like create database and drop database
        /// </summary>
        /// <param name="textfileLocation">
        /// The textfile location.
        /// </param>
        /// <param name="theForm">
        /// The  form.
        /// </param>
        /// <returns>
        /// The number of errors
        /// </returns>
        private static int RunNonExecuteQuery(string textfileLocation, Form1 theForm)
        {
            var numErrors = 0;

            // Read testfile:
            string        connectionString;
            List <string> queryList;

            if (!ReadTextfile(textfileLocation, out connectionString, out queryList))
            {
                throw new Exception("Cannot read text file");
            }

            // Connect to data source:
            var ds = new OgrDatasource {
                GlobalCallback = theForm
            };

            if (!ds.Open(connectionString))
            {
                throw new Exception("Failed to open datasource: " + ds.GdalLastErrorMsg);
            }

            // Get queries:
            foreach (var query in queryList)
            {
                string errorMsg;
                if (ds.ExecuteSQL(query, out errorMsg))
                {
                    theForm.Progress("Executed query: " + query);
                    continue;
                }

                if (ds.GdalLastErrorMsg.Contains("cannot run inside a transaction block"))
                {
                    errorMsg += " You're probably using a too old version of GDAL v2, please update.";
                }

                theForm.WriteError(string.Format("Error executing query [{0}]: {1}", query, errorMsg));
                numErrors++;
            }

            // Close database connection:
            ds.Close();

            return(numErrors);
        }
Beispiel #14
0
        private void CreatTreeView(ListLayerView listLayerView)
        {
            int nodeL = 0;

            foreach (LayerView layerview in listLayerView.LayerViews)
            {
                MaptTreeView.Nodes.Add(layerview.Label);
                MaptTreeView.Nodes[nodeL].Checked = true;
                MaptTreeView.Nodes[nodeL].Name    = layerview.IdTree;

                if (layerview.ShowNodesProjectViews)
                {
                    int nodeP = 0;
                    foreach (ProjectView projectView in layerview.ProjectViews)
                    {
                        MaptTreeView.Nodes[nodeL].Nodes.Add(projectView.Label);
                        MaptTreeView.Nodes[nodeL].Nodes[nodeP].Checked = true;
                        MaptTreeView.Nodes[nodeL].Nodes[nodeP].Name    = projectView.IdTree;

                        var ds = new OgrDatasource();
                        ds.Open(projectView.Connection.StringConexao());

                        int nodeQ = 0;
                        foreach (QueryView queryView in projectView.QueryViews)
                        {
                            MaptTreeView.Nodes[nodeL].Nodes[nodeP].Nodes.Add(queryView.Label);
                            MaptTreeView.Nodes[nodeL].Nodes[nodeP].Nodes[nodeQ].Checked = true;
                            MaptTreeView.Nodes[nodeL].Nodes[nodeP].Nodes[nodeQ].Name    = queryView.IdTree;

                            var buffer = ds.RunQuery(queryView.Query);
                            MapTAxMap.AddLayer(buffer, true);
                            buffer.GetBuffer().DefaultDrawingOptions.FillColor = queryView.Color;

                            nodeQ++;
                        }
                        nodeP++;

                        ds.Close();
                    }
                }
                nodeL++;
            }
            MaptTreeView.ExpandAll();
            MapTAxMap.ZoomToMaxVisibleExtents();
        }
Beispiel #15
0
        /// <summary>
        /// Test setting PostGIS privileges.
        /// </summary>
        /// <param name="textfileLocation">
        /// The textfile location.
        /// </param>
        /// <param name="theForm">
        /// The form.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        internal static bool RunPostGisPostGisPrivileges(string textfileLocation, Form1 theForm)
        {
            var numErrors = 0;

            theForm.Progress(
                "-----------------------The setting of the grants and privileges has started." + Environment.NewLine);

            // Read testfile:
            string        connectionString;
            List <string> queryList;

            if (!ReadTextfile(textfileLocation, out connectionString, out queryList))
            {
                throw new Exception("Cannot read text file");
            }

            // Connect to data source:
            var ds = new OgrDatasource {
                GlobalCallback = theForm
            };

            if (!ds.Open(connectionString))
            {
                throw new Exception("Failed to open datasource: " + ds.GdalLastErrorMsg);
            }

            // Get every first and second line:
            foreach (var query in queryList)
            {
                string errorMsg;
                if (!ds.ExecuteSQL(query, out errorMsg))
                {
                    theForm.WriteError(string.Format("Error executing query [{0}]: {1}", query, errorMsg));
                    numErrors++;
                }
            }

            // Close database connection:
            ds.Close();

            theForm.Progress(
                string.Format("The setting of the grants and privileges test has finished, with {0} errors", numErrors));

            return(numErrors == 0);
        }
        public void MWGIS61Test()
        {
            var ds = new OgrDatasource();

            try
            {
                if (!ds.Open(CONNECTION_STRING))
                {
                    Assert.Fail("Failed to establish connection: " + ds.GdalLastErrorMsg);
                }

                // Provided by Olivier:
                ImportShapefile(ds, @"D:\dev\GIS-Data\Issues\MWGIS-61\t_cheminement.shp", "Olivier_lines");
            }
            finally
            {
                ds.Close();
            }
        }
Beispiel #17
0
        private static bool ImportShapefilesFromFolder()
        {
            var ds = new OgrDatasource();

            if (!ds.Open(CONNECTION_STRING))
            {
                Debug.Print("Failed to establish connection: " + ds.GdalLastErrorMsg);
            }
            else
            {
                string path  = @"d:\data\sf\london";
                var    files = Directory.GetFiles(path, "*.shp");
                foreach (var file in files)
                {
                    var sf = new Shapefile();
                    if (!sf.Open(file))
                    {
                        Debug.Print("Failed to open shapefile: {0}\n{1}", file, sf.ErrorMsg[sf.LastErrorCode]);
                    }
                    else
                    {
                        string name = Path.GetFileNameWithoutExtension(file);
                        if (!ds.ImportShapefile(sf, name, "OVERWRITE=YES", tkShapeValidationMode.NoValidation))
                        {
                            Debug.Print("Failed to import shapefile: " + name);
                        }
                        else
                        {
                            Debug.Print("Layer was imported: " + name);
                            var layer = ds.GetLayerByName(name);
                            if (layer != null)
                            {
                                Debug.Print("Imported features count: " + layer.FeatureCount);
                                layer.Close();
                            }
                        }
                    }
                }
                ds.Close();
            }
            return(true);
        }
Beispiel #18
0
        private static bool TestSpatialQuery()
        {
            var ds = new OgrDatasource();

            if (!ds.Open(CONNECTION_STRING))
            {
                Debug.WriteLine("Failed to establish connection: " + ds.GdalLastErrorMsg);
            }
            else
            {
                map.RemoveAllLayers();
                map.Projection = tkMapProjection.PROJECTION_WGS84;

                string sql    = "SELECT st_buffer(wkb_geometry, 0.01) AS buffer, * FROM waterways;";
                var    buffer = ds.RunQuery(sql);
                if (buffer == null)
                {
                    Debug.WriteLine("Failed to build buffer: " + ds.GdalLastErrorMsg);
                }
                else
                {
                    Debug.WriteLine("Number of features in a buffer: " + buffer.FeatureCount);
                    map.AddLayer(buffer, true);
                    buffer.GetBuffer().DefaultDrawingOptions.FillColor = 255;     // red
                }

                //layer
                string sql2  = "SELECT * FROM waterways;";
                var    layer = ds.RunQuery(sql2);
                if (layer == null)
                {
                    Debug.WriteLine("Failed to open layer: " + ds.GdalLastErrorMsg);
                }
                else
                {
                    Debug.WriteLine("Number of features in layer: " + layer.FeatureCount);
                    map.AddLayer(layer, true);
                }
            }
            return(true);
        }
Beispiel #19
0
        private static void ListDriverCapability()
        {
            var ds = new OgrDatasource();

            if (!ds.Open(CONNECTION_STRING))
            {
                Debug.Print("Failed to establish connection: " + ds.GdalLastErrorMsg);
            }
            else
            {
                Debug.Print("OGR driver: " + ds.DriverName);

                Debug.Print("\nDriver capabilities:");
                var values = Enum.GetValues(typeof(tkOgrDSCapability));
                foreach (tkOgrDSCapability value in values)
                {
                    Debug.Print(value.ToString() + ": " + ds.TestCapability(value).ToString());
                }
                ds.Close();
            }
        }
        public void OpenPostGISDifferentPortTest()
        {
            var ogrDatasource = new OgrDatasource();

            try
            {
                var result = ogrDatasource.Open("PG:host=127.0.0.1 port=55432 dbname=aw_croppingscheme user=aw_croppingschem password=test123");
                Assert.IsTrue(result, "Cannot open PostGIS Connectie: " + ogrDatasource.GdalLastErrorMsg);
                var settings = new GlobalSettings();

                var capability = ogrDatasource.TestCapability(tkOgrDSCapability.odcCreateLayer);
                Console.WriteLine("odcCreateLayer: " + capability);
                Assert.IsTrue(capability, "Cannot create layer");
                capability = ogrDatasource.TestCapability(tkOgrDSCapability.odcDeleteLayer);
                Console.WriteLine("odcDeleteLayer: " + capability);
                Assert.IsTrue(capability, "Cannot delete layer");
                capability = ogrDatasource.TestCapability(tkOgrDSCapability.odcCreateDataSource);
                Console.WriteLine("odcCreateDataSource: " + capability);
                //Assert.IsTrue(capability), "Cannot create datasource");
                capability = ogrDatasource.TestCapability(tkOgrDSCapability.odcDeleteDataSource);
                Console.WriteLine("odcDeleteDataSource: " + capability);
                //Assert.IsTrue(capability, "Cannot delete datasource");
                capability = ogrDatasource.TestCapability(tkOgrDSCapability.odcCreateGeomFieldAfterCreateLayer);
                Console.WriteLine("odcCreateGeomFieldAfterCreateLayer: " + capability);
                Assert.IsTrue(capability, "Cannot create GeomField After CreateLayer");

                Assert.IsTrue(ogrDatasource.LayerCount > 1, "No layers found");

                for (var i = 0; i < ogrDatasource.LayerCount; i++)
                {
                    var layer = ogrDatasource.GetLayer(i);
                    Console.WriteLine(layer.Name);
                }
            }
            finally
            {
                ogrDatasource.Close();
            }
        }
        public void ListAllLayers()
        {
            var ds = new OgrDatasource();

            try
            {
                if (!ds.Open(CONNECTION_STRING))
                {
                    Assert.Fail("Failed to establish connection: " + ds.GdalLastErrorMsg);
                }
                Debug.WriteLine("ds.LayerCount: " + ds.LayerCount);
                for (var i = 0; i < ds.LayerCount; i++)
                {
                    var layer = ds.GetLayer2(i, false, false);
                    Debug.WriteLine(layer.Name + " has " + layer.FeatureCount + " features. Projection is " + layer.GeoProjection.Name);
                }
            }
            finally
            {
                ds.Close();
            }
        }
Beispiel #22
0
        private static bool TestMetadata()
        {
            var ds = new OgrDatasource();

            if (!ds.Open(CONNECTION_STRING))
            {
                Debug.Print("Failed to establish connection: " + ds.GdalLastErrorMsg);
            }
            else
            {
                Debug.Print("Layer creation options: " +
                            ds.get_DriverMetadata(tkGdalDriverMetadata.dmdLAYER_CREATIONOPTIONLIST));
                Debug.Print("Long name: " + ds.get_DriverMetadata(tkGdalDriverMetadata.dmdLONGNAME));

                Debug.Print("Metadata items: ");
                for (int i = 0; i < ds.DriverMetadataCount; i++)
                {
                    Debug.Print(ds.get_DriverMetadataItem(i));
                }
                ds.Close();
            }
            return(true);
        }
Beispiel #23
0
        private static bool DisplayAllLayers()
        {
            var ds = new OgrDatasource();

            if (!ds.Open(CONNECTION_STRING))
            {
                Debug.WriteLine("Failed to establish connection: " + ds.GdalLastErrorMsg);
            }
            else
            {
                map.RemoveAllLayers();

                // make sure it matches SRID of the layers (4326 in this case)
                map.Projection = tkMapProjection.PROJECTION_WGS84;

                for (int i = 0; i < ds.LayerCount; i++)
                {
                    var layer = ds.GetLayer(i);
                    if (layer != null)
                    {
                        int handle = map.AddLayer(layer, true);
                        if (handle == -1)
                        {
                            Debug.WriteLine("Failed to add layer to the map: " + map.get_ErrorMsg(map.LastErrorCode));
                        }
                        else
                        {
                            Debug.WriteLine("Layer was added the map: " + layer.Name);
                        }
                    }
                }
                map.ZoomToMaxVisibleExtents();
                ds.Close();
            }
            return(true);
        }
Beispiel #24
0
        private static bool TestExecuteSQL()
        {
            var ds = new OgrDatasource();

            if (!ds.Open(CONNECTION_STRING))
            {
                Debug.Print("Failed to establish connection: " + ds.GdalLastErrorMsg);
            }
            else
            {
                string errorMsg;
                bool   result = ds.ExecuteSQL("DELETE FROM tableName WHERE gid > 100", out errorMsg);
                if (!result)
                {
                    Debug.Print("Error on running SQL: " + errorMsg);
                }
                else
                {
                    Debug.Print("SQL was executed successfully.");
                }
                ds.Close();
            }
            return(true);
        }
        public void AddProjectLayersThread(int Project)
        {
            var gdalUtils = new GdalUtils();

            RasterReprojectCallback callback = new RasterReprojectCallback(null, MapControlTools);

            gdalUtils.GlobalCallback = callback;
            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;
            }
            else
            {
                Events.MapControl_BusyStateChange bc = new Events.MapControl_BusyStateChange();
                bc.BusyState   = Events.BusyState.Busy;
                bc.KeyOfSender = "AddProjectLayersThread";
                bc.Percent     = 10;
                bc.Message     = Resources.MapControl_AddedPerimeter;
                MapControlTools.On_BusyStateChange(bc);


                // RiskMap
                if (!AddProjectLayer(Project, ResTBPostGISType.RiskMap))
                {
                    return;
                }
                if (!AddProjectLayer(Project, ResTBPostGISType.RiskMapAfter))
                {
                    return;
                }

                // Perimeter
                if (!AddProjectLayer(Project, ResTBPostGISType.Perimeter))
                {
                    return;
                }
                if (MapControlTools.ShapesCount(MapControlTools.GetLayerNamesFromPostGISType(ResTBPostGISType.Perimeter).First()) > 0)
                {
                    MapControlTools.ZoomToLayer(MapControlTools.GetLayerNamesFromPostGISType(ResTBPostGISType.Perimeter).First());
                }


                // Hazard Maps
                DB.ResTBContext  db         = new DB.ResTBContext();
                List <HazardMap> hazardMaps = db.HazardMaps.Where(m => m.Project.Id == Project).Include(m => m.NatHazard).OrderBy(m => m.Index).ToList();

                double percentadd     = 50.0 / hazardMaps.Count;
                int    currentpercent = 10;

                foreach (HazardMap hazardMap in hazardMaps.OrderByDescending(m => m.BeforeAction))
                {
                    ResTBHazardMapLayer hazardLayer;
                    if (hazardMap.BeforeAction)
                    {
                        hazardLayer = new ResTBHazardMapLayer(Project, true, hazardMap.NatHazard, hazardMap.Index);
                    }
                    else
                    {
                        hazardLayer = new ResTBHazardMapLayer(Project, false, hazardMap.NatHazard, hazardMap.Index);
                    }


                    currentpercent += (int)percentadd;
                    if (!MapControlTools.Layers.Where(m => m.Name == hazardLayer.Name).Any())
                    {
                        AddProjectLayer(hazardLayer, false);
                        bc             = new Events.MapControl_BusyStateChange();
                        bc.BusyState   = Events.BusyState.Busy;
                        bc.KeyOfSender = "AddProjectLayersThread";
                        bc.Percent     = currentpercent;
                        bc.Message     = Resources.MapControl_AddingHazardMaps;
                        MapControlTools.On_BusyStateChange(bc);
                    }
                }


                // Damage Potential
                if (!AddProjectLayer(Project, ResTBPostGISType.DamagePotential))
                {
                    return;
                }

                // Resiliences

                if (!AddProjectLayer(Project, ResTBPostGISType.ResilienceBefore))
                {
                    return;
                }

                if (!AddProjectLayer(Project, ResTBPostGISType.ResilienceAfter))
                {
                    return;
                }

                currentpercent += 30;
                bc              = new Events.MapControl_BusyStateChange();
                bc.BusyState    = Events.BusyState.Busy;
                bc.KeyOfSender  = "AddProjectLayersThread";
                bc.Percent      = currentpercent;
                bc.Message      = Resources.MapControl_AddedDamagePotentials;
                MapControlTools.On_BusyStateChange(bc);

                // Mitigation Measure
                if (!AddProjectLayer(Project, ResTBPostGISType.MitigationMeasure))
                {
                    return;
                }

                currentpercent += 10;
                bc              = new Events.MapControl_BusyStateChange();
                bc.BusyState    = Events.BusyState.Idle;
                bc.KeyOfSender  = "Project";
                bc.Percent      = 100;
                bc.Message      = Resources.MapControl_ProjectLoaded;// "Project loaded";
                MapControlTools.On_BusyStateChange(bc);


                return;
            }
        }
Beispiel #26
0
        /// <summary>
        /// Import shapefiles into the PostGIS database
        /// </summary>
        /// <param name="textfileLocation">
        /// The textfile location.
        /// </param>
        /// <param name="theForm">
        /// The form.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        internal static bool RunPostGisImportSf(string textfileLocation, Form1 theForm)
        {
            var numErrors = 0;

            Map = Fileformats.Map;
            Map.RemoveAllLayers();
            Map.Projection = tkMapProjection.PROJECTION_WGS84;

            Application.DoEvents();

            theForm.Progress("----------------------- Importing of shapefiles has started." + Environment.NewLine);

            // Read testfile:
            string        connectionString;
            List <string> shapefileList;

            if (!ReadTextfile(textfileLocation, out connectionString, out shapefileList))
            {
                throw new Exception("Cannot read text file");
            }

            // Connect to data source:
            var ds = new OgrDatasource {
                GlobalCallback = theForm
            };

            if (!ds.Open(connectionString))
            {
                throw new Exception("Failed to open datasource: " + ds.GdalLastErrorMsg);
            }

            // Get queries:
            foreach (var shapefileLocation in shapefileList)
            {
                var layerName = Path.GetFileNameWithoutExtension(shapefileLocation);
                if (!File.Exists(shapefileLocation))
                {
                    theForm.WriteError(shapefileLocation + " does not exists. Skipping");
                    continue;
                }

                // Open shapefile:
                theForm.Progress(string.Format("Reading {0} shapefile", layerName));
                var fm = new FileManager();
                var sf = fm.OpenShapefile(shapefileLocation, theForm);
                theForm.Progress(string.Format("Importing {0} shapefile", layerName));
                if (!ds.ImportShapefile(sf, layerName, "OVERWRITE=YES", tkShapeValidationMode.NoValidation))
                {
                    var errorMsg = fm.ErrorMsg[fm.LastErrorCode];

                    // let's check GDAL error as well
                    var gs = new GlobalSettings();
                    errorMsg += " GDAL error message: " + gs.GdalLastErrorMsg;

                    theForm.WriteError(
                        string.Format("Error importing shapefile [{0}]: {1}", shapefileLocation, errorMsg));
                    numErrors++;
                }
                else
                {
                    // Read layer and add to map:
                    theForm.Progress(string.Format("Reading {0} layer from db", layerName));
                    var handle = Map.AddLayerFromDatabase(connectionString, layerName, true);
                    if (handle == -1)
                    {
                        theForm.WriteError("Failed to open database layer: " + layerName);
                        numErrors++;
                    }

                    Application.DoEvents();
                }

                // Close shapefile:
                sf.Close();
            }

            // Close database connection:
            ds.Close();

            theForm.Progress(string.Format("Importing of shapefiles test has finished, with {0} errors", numErrors));

            return(numErrors == 0);
        }
Beispiel #27
0
        /// <summary>
        /// Run the open postGIS layers test.
        /// </summary>
        /// <param name="textfileLocation">
        /// The textfile location.
        /// </param>
        /// <param name="theForm">
        /// The form.
        /// </param>
        /// <returns>
        /// True on success
        /// </returns>
        internal static bool RunOpenPostGisLayers(string textfileLocation, Form1 theForm)
        {
            var numErrors = 0;

            Map = Fileformats.Map;
            Map.RemoveAllLayers();

            // TODO: How to switch between these two:
            // Map.Projection = tkMapProjection.PROJECTION_WGS84;
            Map.GrabProjectionFromData = true;

            var gs = new GlobalSettings();

            theForm.Progress("OgrLayerMaxFeatureCount: " + gs.OgrLayerMaxFeatureCount);

            Application.DoEvents();

            theForm.Progress("----------------------- Opening PostGIS layers has started." + Environment.NewLine);

            // Read testfile:
            string        connectionString;
            List <string> layersList;

            if (!ReadTextfile(textfileLocation, out connectionString, out layersList))
            {
                throw new Exception("Cannot read text file");
            }

            // Connect to data source:
            var ds = new OgrDatasource {
                GlobalCallback = theForm
            };

            if (!ds.Open(connectionString))
            {
                throw new Exception("Failed to open datasource: " + ds.GdalLastErrorMsg);
            }

            // Get queries:
            foreach (var layerName in layersList)
            {
                var layer = ds.GetLayerByName(layerName, true);

                if (layer == null)
                {
                    continue;
                }

                layer.MaxFeatureCount = 10000;
                layer.GlobalCallback  = theForm;

                theForm.Progress("Opening " + layerName);
                var handle = Map.AddLayer(layer, true);
                if (handle == -1)
                {
                    theForm.WriteError("Failed to add database layer " + layerName + " to the map.");
                    numErrors++;
                }

                Application.DoEvents();
            }

            // Close database connection:
            ds.Close();

            theForm.Progress(string.Format("Opening PostGIS layers test has finished, with {0} errors", numErrors));

            return(numErrors == 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();
            }
        }
Beispiel #29
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();
        }
Beispiel #30
0
 public VectorDatasource()
 {
     _datasource = new OgrDatasource();
 }