Exemplo n.º 1
0
        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();
            }
        }
Exemplo n.º 2
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();
            }
        }
Exemplo n.º 3
0
        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();
            }
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
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();
            }
        }
Exemplo n.º 6
0
        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();
            }
        }
Exemplo n.º 7
0
 private void OpenDatasource()
 {
     _datasource.Close();
     if (!OgrHelper.OpenDatasource(_datasource, _connection))
     {
         return;
     }
     PopulateList();
 }
Exemplo n.º 8
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();
            }
        }
Exemplo n.º 9
0
        /// <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);
        }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
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);
        }
Exemplo n.º 12
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();
        }
Exemplo n.º 13
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();
            }
        }
Exemplo n.º 14
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);
        }
Exemplo n.º 15
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();
            }
        }
Exemplo n.º 16
0
        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();
            }
        }
Exemplo n.º 17
0
        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();
            }
        }
Exemplo n.º 18
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);
        }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
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);
        }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
0
 public void Close()
 {
     _datasource.Close();
 }
Exemplo n.º 24
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();
            }
        }