PostGIS2.cs
上传用户:sex100000
上传日期:2013-11-09
资源大小:1377k
文件大小:29k
源码类别:

GIS编程

开发平台:

C#

  1. // Copyright 2005, 2006 - Christian Gr鋐e (www.sharptools.de)
  2. //
  3. // This file is part of SharpMap.
  4. // SharpMap is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation; either version 2 of the License, or
  7. // (at your option) any later version.
  8. // 
  9. // SharpMap is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12. // GNU Lesser General Public License for more details.
  13. // You should have received a copy of the GNU Lesser General Public License
  14. // along with SharpMap; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Collections.ObjectModel;
  19. using System.ComponentModel;
  20. using System.Runtime;
  21. using System.Text;
  22. // more info at http://sf.net/projects/pgsqlclient
  23. using PostgreSql.Data.PostgreSqlClient;
  24. using PostgreSql.Data.PgTypes;
  25. namespace SharpMap.Data.Providers
  26. {
  27.     /// <summary>
  28.     /// PostGreSQL / PostGIS dataprovider
  29.     /// </summary>
  30.     /// <example>
  31.     /// Adding a datasource to a layer:
  32.     /// <code lang="C#">
  33.     /// SharpMap.Layers.VectorLayer myLayer = new SharpMap.Layers.VectorLayer("My layer");
  34.     /// string ConnStr = "Server=127.0.0.1;Port=5432;User Id=postgres;Password=password;Database=myGisDb;";
  35.     /// myLayer.DataSource = new SharpMap.Data.Providers.PostGIS2(ConnStr, "myTable");
  36.     /// </code>
  37.     /// </example>
  38.     [Serializable]
  39.     public class PostGIS2 : SharpMap.Data.Providers.IProvider, IDisposable
  40.     {
  41.         /// <summary>
  42.         /// Initializes a new connection to PostGIS
  43.         /// </summary>
  44.         /// <param name="ConnectionStr">Connectionstring</param>
  45.         /// <param name="tablename">Name of data table</param>
  46.         /// <param name="geometryColumnName">Name of geometry column</param>
  47.         /// <param name="OID_ColumnName">Name of column with unique identifier</param>
  48.         public PostGIS2(string ConnectionStr, string tablename, string geometryColumnName, string OID_ColumnName)
  49.         {
  50.             this.ConnectionString = ConnectionStr;
  51.             this.Table = tablename;
  52.             this.GeometryColumn = geometryColumnName;
  53.             this.ObjectIdColumn = OID_ColumnName;
  54.         }
  55.         /// <summary>
  56.         /// Initializes a new connection to PostGIS
  57.         /// </summary>
  58.         /// <param name="ConnectionString">Connectionstring</param>
  59.         /// <param name="TableName">Name of data table</param>
  60.         /// <param name="OID_ColumnName">Name of column with unique identifier</param>
  61.         public PostGIS2(string ConnectionString, string TableName, string OIdColumnName)
  62.             : this(ConnectionString, TableName, "", OIdColumnName)
  63.         {
  64.             this.GeometryColumn = this.GetGeometryColumn();
  65.         }
  66.         private bool _IsOpen;
  67.         /// <summary>
  68.         /// Returns true if the datasource is currently open
  69.         /// </summary>
  70.         public bool IsOpen
  71.         {
  72.             get { return _IsOpen; }
  73.         }
  74.         /// <summary>
  75.         /// Opens the datasource
  76.         /// </summary>
  77.         public void Open()
  78.         {
  79.             //Don't really do anything. npgsql's ConnectionPooling takes over here
  80.             _IsOpen = true;
  81.         }
  82.         /// <summary>
  83.         /// Closes the datasource
  84.         /// </summary>
  85.         public void Close()
  86.         {
  87.             //Don't really do anything. npgsql's ConnectionPooling takes over here
  88.             _IsOpen = false;
  89.         }
  90.         #region Disposers and finalizers
  91.         private bool disposed = false;
  92.         /// <summary>
  93.         /// Disposes the object
  94.         /// </summary>
  95.         public void Dispose()
  96.         {
  97.             Dispose(true);
  98.             GC.SuppressFinalize(this);
  99.         }
  100.         internal void Dispose(bool disposing)
  101.         {
  102.             if (!disposed)
  103.             {
  104.                 if (disposing)
  105.                 {
  106.                     //Close();
  107.                 }
  108.                 disposed = true;
  109.             }
  110.         }
  111.         /// <summary>
  112.         /// Finalizer
  113.         /// </summary>
  114.         ~PostGIS2()
  115.         {
  116.             Dispose();
  117.         }
  118.         #endregion
  119.         private string _ConnectionString;
  120.         /// <summary>
  121.         /// Connectionstring
  122.         /// </summary>
  123.         public string ConnectionString
  124.         {
  125.             get { return _ConnectionString; }
  126.             set { _ConnectionString = value; }
  127.         }
  128.         private string _Table;
  129.         /// <summary>
  130.         /// Data table name
  131.         /// </summary>
  132.         public string Table
  133.         {
  134.             get { return _Table; }
  135.             set { _Table = value; }
  136.         }
  137.         private string _GeometryColumn;
  138.         /// <summary>
  139.         /// Name of geometry column
  140.         /// </summary>
  141.         public string GeometryColumn
  142.         {
  143.             get { return _GeometryColumn; }
  144.             set { _GeometryColumn = value; }
  145.         }
  146.         private string _ObjectIdColumn;
  147.         /// <summary>
  148.         /// Name of column that contains the Object ID
  149.         /// </summary>
  150.         public string ObjectIdColumn
  151.         {
  152.             get { return _ObjectIdColumn; }
  153.             set { _ObjectIdColumn = value; }
  154.         }
  155.         /// <summary>
  156.         /// Returns geometries within the specified bounding box
  157.         /// </summary>
  158.         /// <param name="bbox"></param>
  159.         /// <returns></returns>
  160.         public Collection<Geometries.Geometry> GetGeometriesInView(SharpMap.Geometries.BoundingBox bbox)
  161.         {
  162.             Collection<Geometries.Geometry> features = new Collection<SharpMap.Geometries.Geometry>();
  163.             using (PgConnection conn = new PgConnection(_ConnectionString))
  164.             {
  165.                 string strBbox = GetBoundingBoxSql(bbox, this.SRID);
  166.                 String strSql = String.Format("SELECT AsBinary({0}) as geom FROM {1} WHERE ",
  167.                                               this.GeometryColumn,
  168.                                               this.Table);
  169.                 if (!String.IsNullOrEmpty(_defintionQuery))
  170.                     strSql += this.DefinitionQuery + " AND ";
  171.                 strSql += String.Format("{0} && {1}", this.GeometryColumn, strBbox);
  172.                 using (PgCommand command = new PgCommand(strSql, conn))
  173.                 {
  174.                     conn.Open();
  175.                     using (PgDataReader dr = command.ExecuteReader())
  176.                     {
  177.                         while (dr.Read())
  178.                         {
  179.                             //object obj = dr[0];
  180.                             SharpMap.Geometries.Geometry geom = null;
  181.                             // if ( typeof(PgPoint) == obj.GetType() )
  182.                             // geom = new SharpMap.Geometries.Point( ((PgPoint)obj).X, ((PgPoint)obj).Y );
  183.                             // else 
  184.                             if (dr[0] != DBNull.Value)
  185.                                 geom = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr[0]);
  186.                             if (geom != null)
  187.                                 features.Add(geom);
  188.                         }
  189.                     }
  190.                     conn.Close();
  191.                 }
  192.             }
  193.             return features;
  194.         }
  195.         /// <summary>
  196.         /// Returns the geometry corresponding to the Object ID
  197.         /// </summary>
  198.         /// <param name="oid">Object ID</param>
  199.         /// <returns>geometry</returns>
  200.         public SharpMap.Geometries.Geometry GetGeometryByID(uint oid)
  201.         {
  202.             SharpMap.Geometries.Geometry geom = null;
  203.             using (PgConnection conn = new PgConnection(_ConnectionString))
  204.             {
  205.                 String strSql = String.Format("SELECT AsBinary({0}) As Geom FROM {1} WHERE {2} = '{3}'",
  206.                                               this.GeometryColumn,
  207.                                               this.Table,
  208.                                               this.ObjectIdColumn,
  209.                                               oid);
  210.                 conn.Open();
  211.                 using (PgCommand command = new PgCommand(strSql, conn))
  212.                 {
  213.                     using (PgDataReader dr = command.ExecuteReader())
  214.                     {
  215.                         while (dr.Read())
  216.                         {
  217.                             object obj = dr[0];
  218.                             if (typeof(PgPoint) == obj.GetType())
  219.                                 geom = new SharpMap.Geometries.Point(((PgPoint)obj).X, ((PgPoint)obj).Y);
  220.                             else if (obj != DBNull.Value)
  221.                                 geom = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr[0]);
  222.                         }
  223.                     }
  224.                 }
  225.                 conn.Close();
  226.             }
  227.             return geom;
  228.         }
  229.         /// <summary>
  230.         /// Returns geometry Object IDs whose bounding box intersects 'bbox'
  231.         /// </summary>
  232.         /// <param name="bbox"></param>
  233.         /// <returns></returns>
  234.         public Collection<uint> GetObjectIDsInView(SharpMap.Geometries.BoundingBox bbox)
  235.         {
  236.             Collection<uint> objectlist = new Collection<uint>();
  237.             using (PgConnection conn = new PgConnection(_ConnectionString))
  238.             {
  239.                 string strBbox = GetBoundingBoxSql(bbox, this.SRID);
  240.                 String strSql = String.Format("SELECT {0} FROM {1} WHERE ", this.ObjectIdColumn, this.Table);
  241.                 if (!String.IsNullOrEmpty(_defintionQuery))
  242.                     strSql += this.DefinitionQuery + " AND ";
  243.                 strSql += this.GeometryColumn + " && " + strBbox;
  244.                 using (PgCommand command = new PgCommand(strSql, conn))
  245.                 {
  246.                     conn.Open();
  247.                     using (PgDataReader dr = command.ExecuteReader())
  248.                     {
  249.                         while (dr.Read())
  250.                         {
  251.                             if (dr[0] != DBNull.Value)
  252.                             {
  253.                                 uint ID = (uint)(int)dr[0];
  254.                                 objectlist.Add(ID);
  255.                             }
  256.                         }
  257.                     }
  258.                     conn.Close();
  259.                 }
  260.             }
  261.             return objectlist;
  262.         }
  263.         /// <summary>
  264.         /// Returns all objects within a distance of a geometry
  265.         /// </summary>
  266.         /// <param name="geom"></param>
  267.         /// <param name="distance"></param>
  268.         /// <returns></returns>
  269.         [Obsolete("Use ExecuteIntersectionQuery instead")]
  270.         public SharpMap.Data.FeatureDataTable QueryFeatures(SharpMap.Geometries.Geometry geom, double distance)
  271.         {
  272.             Collection<Geometries.Geometry> features = new Collection<SharpMap.Geometries.Geometry>();
  273.             using (PgConnection conn = new PgConnection(_ConnectionString))
  274.             {
  275.                 string strGeom = "GeomFromText('" + geom.AsText() + "')";
  276.                 if (this.SRID > 0)
  277.                     strGeom = "setSRID(" + strGeom + "," + this.SRID.ToString() + ")";
  278.                 string strSQL = "SELECT * , AsBinary(" + this.GeometryColumn + ") As sharpmap_tempgeometry FROM " + this.Table + " WHERE ";
  279.                 if (!String.IsNullOrEmpty(_defintionQuery))
  280.                     strSQL += this.DefinitionQuery + " AND ";
  281.                 strSQL += this.GeometryColumn + " && " + "buffer(" + strGeom + "," + distance.ToString(Map.numberFormat_EnUS) + ")";
  282.                 strSQL += " AND distance(" + this.GeometryColumn + ", " + strGeom + ")<" + distance.ToString(Map.numberFormat_EnUS);
  283.                 using (PgDataAdapter adapter = new PgDataAdapter(strSQL, conn))
  284.                 {
  285.                     System.Data.DataSet ds = new System.Data.DataSet();
  286.                     conn.Open();
  287.                     adapter.Fill(ds);
  288.                     conn.Close();
  289.                     if (ds.Tables.Count > 0)
  290.                     {
  291.                         FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]);
  292.                         foreach (System.Data.DataColumn col in ds.Tables[0].Columns)
  293.                             if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
  294.                                 fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
  295.                         foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
  296.                         {
  297.                             SharpMap.Data.FeatureDataRow fdr = fdt.NewRow();
  298.                             foreach (System.Data.DataColumn col in ds.Tables[0].Columns)
  299.                                 if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
  300.                                     fdr[col.ColumnName] = dr[col];
  301.                             fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]);
  302.                             fdt.AddRow(fdr);
  303.                         }
  304.                         return fdt;
  305.                     }
  306.                     else return null;
  307.                 }
  308.             }
  309.         }
  310.         /// <summary>
  311.         /// Returns the features that intersects with 'geom'
  312.         /// </summary>
  313.         /// <param name="geom"></param>
  314.         /// <param name="ds">FeatureDataSet to fill data into</param>
  315.         public void ExecuteIntersectionQuery(SharpMap.Geometries.Geometry geom, FeatureDataSet ds)
  316.         {
  317.             //List<Geometries.Geometry> features = new List<SharpMap.Geometries.Geometry>();
  318.             using (PgConnection conn = new PgConnection(_ConnectionString))
  319.             {
  320.                 string strGeom = "GeomFromText('" + geom.AsText() + "')";
  321.                 if (this.SRID > 0)
  322.                     strGeom = "setSRID(" + strGeom + "," + this.SRID.ToString() + ")";
  323.                 string strSQL = "SELECT * , AsBinary(" + this.GeometryColumn + ") As sharpmap_tempgeometry FROM " + this.Table + " WHERE ";
  324.                 if (!String.IsNullOrEmpty(_defintionQuery))
  325.                     strSQL += this.DefinitionQuery + " AND ";
  326.                 strSQL += this.GeometryColumn + " && " + strGeom + " AND distance(" + this.GeometryColumn + ", " + strGeom + ")<0";
  327.                 using (PgDataAdapter adapter = new PgDataAdapter(strSQL, conn))
  328.                 {
  329.                     conn.Open();
  330.                     adapter.Fill(ds);
  331.                     conn.Close();
  332.                     if (ds.Tables.Count > 0)
  333.                     {
  334.                         FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]);
  335.                         foreach (System.Data.DataColumn col in ds.Tables[0].Columns)
  336.                             if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
  337.                                 fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
  338.                         foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
  339.                         {
  340.                             SharpMap.Data.FeatureDataRow fdr = fdt.NewRow();
  341.                             foreach (System.Data.DataColumn col in ds.Tables[0].Columns)
  342.                                 if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
  343.                                     fdr[col.ColumnName] = dr[col];
  344.                             fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]);
  345.                             fdt.AddRow(fdr);
  346.                         }
  347.                         ds.Tables.Add(fdt);
  348.                     }
  349.                 }
  350.             }
  351.         }
  352.         /// <summary>
  353.         /// Returns the number of features in the dataset
  354.         /// </summary>
  355.         /// <returns>number of features</returns>
  356.         public int GetFeatureCount()
  357.         {
  358.             int count = 0;
  359.             using (PgConnection conn = new PgConnection(_ConnectionString))
  360.             {
  361.                 string strSQL = "SELECT COUNT(*) FROM " + this.Table;
  362.                 if (!String.IsNullOrEmpty(_defintionQuery))
  363.                     strSQL += " WHERE " + this.DefinitionQuery;
  364.                 using (PgCommand command = new PgCommand(strSQL, conn))
  365.                 {
  366.                     conn.Open();
  367.                     count = (int)command.ExecuteScalar();
  368.                     conn.Close();
  369.                 }
  370.             }
  371.             return count;
  372.         }
  373.         #region IProvider Members
  374.         private string _defintionQuery;
  375.         /// <summary>
  376.         /// Definition query used for limiting dataset
  377.         /// </summary>
  378.         public string DefinitionQuery
  379.         {
  380.             get { return _defintionQuery; }
  381.             set { _defintionQuery = value; }
  382.         }
  383.         /*
  384. /// <summary>
  385. /// Gets a collection of columns in the dataset
  386. /// </summary>
  387. public System.Data.DataColumnCollection Columns1
  388. {
  389. get {
  390. throw new NotImplementedException();
  391. //using (PgConnection conn = new PgConnection(this.ConnectionString))
  392. //{
  393. //    System.Data.DataColumnCollection columns = new System.Data.DataColumnCollection();
  394. //    string strSQL = "SELECT column_name, udt_name FROM information_schema.columns WHERE table_name='" + this.Table + "' ORDER BY ordinal_position";
  395. //    using (PgCommand command = new PgCommand(strSQL, conn))
  396. //    {
  397. //        conn.Open();
  398. //        using (PgDataReader dr = command.ExecuteReader())
  399. //        {
  400. //            while (dr.Read())
  401. //            {
  402. //                System.Data.DataColumn col = new System.Data.DataColumn((string)dr["column_name"]);
  403. //                switch((string)dr["udt_name"])
  404. //                {
  405. //                    case "int4":
  406. //                        col.DataType = typeof(Int32);
  407. //                        break;
  408. //                    case "int8":
  409. //                        col.DataType = typeof(Int64);
  410. //                        break;
  411. //                    case "varchar":
  412. //                        col.DataType = typeof(string);
  413. //                        break;
  414. //                    case "text":
  415. //                        col.DataType = typeof(string);
  416. //                        break;
  417. //                    case "bool":
  418. //                        col.DataType = typeof(bool);
  419. //                        break;
  420. //                    case "geometry":
  421. //                        col.DataType = typeof(SharpMap.Geometries.Geometry);
  422. //                        break;
  423. //                    default:
  424. //                        col.DataType = typeof(object);
  425. //                        break;
  426. //                }
  427. //                columns.Add(col);
  428. //            }
  429. //        }
  430. //    }
  431. //    return columns;
  432. //}
  433. }
  434. }
  435.         */
  436.         private int _srid = -2;
  437.         /// <summary>
  438.         /// Spacial Reference ID
  439.         /// </summary>
  440.         public int SRID
  441.         {
  442.             get
  443.             {
  444.                 if (_srid == -2)
  445.                 {
  446.                     string strSQL = "select srid from geometry_columns WHERE f_table_name = @Table";
  447.                     using (PgConnection conn = new PgConnection(_ConnectionString))
  448.                     using (PgCommand command = new PgCommand(strSQL, conn))
  449.                     {
  450.                         try
  451.                         {
  452.                             conn.Open();
  453.                             command.Parameters.Add(new PgParameter("@Table", PgDbType.VarChar));
  454.                             command.Parameters[0].Value = this._Table;
  455.                             _srid = (int)command.ExecuteScalar();
  456.                             conn.Close();
  457.                         }
  458.                         catch
  459.                         {
  460.                             _srid = -1;
  461.                         }
  462.                     }
  463.                 }
  464.                 return _srid;
  465.             }
  466.             set
  467.             {
  468.                 throw (new ApplicationException("Spatial Reference ID cannot by set on a PostGIS table"));
  469.             }
  470.         }
  471.         /// <summary>
  472.         /// Queries the PostGIS database to get the name of the Geometry Column. This is used if the columnname isn't specified in the constructor
  473.         /// </summary>
  474.         /// <remarks></remarks>
  475.         /// <returns>Name of column containing geometry</returns>
  476.         private string GetGeometryColumn()
  477.         {
  478.             string strSQL = "select f_geometry_column from geometry_columns WHERE f_table_name = @Table'";
  479.             using (PgConnection conn = new PgConnection(_ConnectionString))
  480.             using (PgCommand command = new PgCommand(strSQL, conn))
  481.             {
  482.                 conn.Open();
  483.                 command.Parameters.Add(new PgParameter("@Table", PgDbType.VarChar));
  484.                 command.Parameters[0].Value = this._Table;
  485.                 object columnname = command.ExecuteScalar();
  486.                 conn.Close();
  487.                 if (columnname == System.DBNull.Value)
  488.                     throw new ApplicationException("Table '" + this.Table + "' does not contain a geometry column");
  489.                 return (string)columnname;
  490.             }
  491.         }
  492.         /// <summary>
  493.         /// Returns a datarow based on a RowID
  494.         /// </summary>
  495.         /// <param name="RowID"></param>
  496.         /// <returns>datarow</returns>
  497.         public SharpMap.Data.FeatureDataRow GetFeature(uint RowID)
  498.         {
  499.             using (PgConnection conn = new PgConnection(_ConnectionString))
  500.             {
  501.                 string strSQL = String.Format("select * , AsBinary({0}) As sharpmap_tempgeometry from {1} WHERE {2} = '{3}'",
  502.                                               this.GeometryColumn, this.Table, this.ObjectIdColumn, RowID);
  503.                 using (PgDataAdapter adapter = new PgDataAdapter(strSQL, conn))
  504.                 {
  505.                     FeatureDataSet ds = new FeatureDataSet();
  506.                     conn.Open();
  507.                     adapter.Fill(ds);
  508.                     conn.Close();
  509.                     if (ds.Tables.Count > 0)
  510.                     {
  511.                         FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]);
  512.                         foreach (System.Data.DataColumn col in ds.Tables[0].Columns)
  513.                             if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
  514.                                 fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
  515.                         if (ds.Tables[0].Rows.Count > 0)
  516.                         {
  517.                             System.Data.DataRow dr = ds.Tables[0].Rows[0];
  518.                             SharpMap.Data.FeatureDataRow fdr = fdt.NewRow();
  519.                             foreach (System.Data.DataColumn col in ds.Tables[0].Columns)
  520.                                 if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
  521.                                     fdr[col.ColumnName] = dr[col];
  522.                             fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]);
  523.                             return fdr;
  524.                         }
  525.                         else
  526.                             return null;
  527.                     }
  528.                     else
  529.                         return null;
  530.                 }
  531.             }
  532.         }
  533.         /// <summary>
  534.         /// Boundingbox of dataset
  535.         /// </summary>
  536.         /// <returns>boundingbox</returns>
  537.         public SharpMap.Geometries.BoundingBox GetExtents()
  538.         {
  539.             using (PgConnection conn = new PgConnection(_ConnectionString))
  540.             {
  541.                 string strSQL = String.Format("SELECT EXTENT({0}) FROM {1}",
  542.                                               this.GeometryColumn,
  543.                                               this.Table);
  544.                 if (!String.IsNullOrEmpty(_defintionQuery))
  545.                     strSQL += " WHERE " + this.DefinitionQuery;
  546.                 strSQL += ";";
  547.                 using (PgCommand command = new PgCommand(strSQL, conn))
  548.                 {
  549.                     conn.Open();
  550.                     SharpMap.Geometries.BoundingBox bbox = null;
  551.                     try
  552.                     {
  553.                         PostgreSql.Data.PgTypes.PgBox2D result = (PostgreSql.Data.PgTypes.PgBox2D)command.ExecuteScalar();
  554.                         bbox = new SharpMap.Geometries.BoundingBox(result.LowerLeft.X, result.LowerLeft.Y, result.UpperRight.X, result.UpperRight.Y);
  555.                     }
  556.                     catch (System.Exception ex)
  557.                     {
  558.                         throw new Exception("Box2d couldn't fetched from table. " + ex.Message);
  559.                     }
  560.                     finally
  561.                     {
  562.                         conn.Close();
  563.                     }
  564.                     return bbox;
  565.                 }
  566.             }
  567.         }
  568.         /// <summary>
  569.         /// Gets the connection ID of the datasource
  570.         /// </summary>
  571.         public string ConnectionID
  572.         {
  573.             get { return _ConnectionString; }
  574.         }
  575.         /// <summary>
  576.         /// Returns all features with the view box
  577.         /// </summary>
  578.         /// <param name="bbox">view box</param>
  579.         /// <param name="ds">FeatureDataSet to fill data into</param>
  580.         [Obsolete("Use ExecuteIntersectionQuery")]
  581.         public void GetFeaturesInView(SharpMap.Geometries.BoundingBox bbox, SharpMap.Data.FeatureDataSet ds)
  582.         {
  583.             ExecuteIntersectionQuery(bbox, ds);
  584.         }
  585.         /// <summary>
  586.         /// Returns all features with the view box
  587.         /// </summary>
  588.         /// <param name="bbox">view box</param>
  589.         /// <param name="ds">FeatureDataSet to fill data into</param>
  590.         public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox bbox, SharpMap.Data.FeatureDataSet ds)
  591.         {
  592.             using (PgConnection conn = new PgConnection(_ConnectionString))
  593.             {
  594.                 string strBbox = GetBoundingBoxSql(bbox, this.SRID);
  595.                 string strSQL = String.Format("SELECT *, AsBinary({0}) AS sharpmap_tempgeometry FROM {1} WHERE ",
  596.                                               this.GeometryColumn,
  597.                                               this.Table);
  598.                 if (!String.IsNullOrEmpty(_defintionQuery))
  599.                     strSQL += this.DefinitionQuery + " AND ";
  600.                 strSQL += this.GeometryColumn + " && " + strBbox;
  601.                 using (PgDataAdapter adapter = new PgDataAdapter(strSQL, conn))
  602.                 {
  603.                     conn.Open();
  604.                     System.Data.DataSet ds2 = new System.Data.DataSet();
  605.                     adapter.Fill(ds2);
  606.                     conn.Close();
  607.                     if (ds2.Tables.Count > 0)
  608.                     {
  609.                         FeatureDataTable fdt = new FeatureDataTable(ds2.Tables[0]);
  610.                         foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
  611.                             if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
  612.                                 fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
  613.                         foreach (System.Data.DataRow dr in ds2.Tables[0].Rows)
  614.                         {
  615.                             SharpMap.Data.FeatureDataRow fdr = fdt.NewRow();
  616.                             foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
  617.                                 if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
  618.                                     fdr[col.ColumnName] = dr[col];
  619.                             fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]);
  620.                             fdt.AddRow(fdr);
  621.                         }
  622.                         ds.Tables.Add(fdt);
  623.                     }
  624.                 }
  625.             }
  626.         }
  627.         #endregion
  628.         #region * Sql builder methods *
  629.         /// <summary>
  630.         /// returns the Bounding Box Sql part for PostGis Extension queries
  631.         /// </summary>
  632.         /// <param name="bbox">Bounding Box</param>
  633.         /// <param name="iSRID">Spatial Reference Id</param>
  634.         /// <returns>String</returns>
  635.         private static string GetBoundingBoxSql(SharpMap.Geometries.BoundingBox bbox, int iSRID)
  636.         {
  637.             string strBbox = String.Format("box2d('BOX3D({0} {1},{2} {3})'::box3d)",
  638.                                 bbox.Min.X.ToString(SharpMap.Map.numberFormat_EnUS),
  639.                                 bbox.Min.Y.ToString(SharpMap.Map.numberFormat_EnUS),
  640.                                 bbox.Max.X.ToString(SharpMap.Map.numberFormat_EnUS),
  641.                                 bbox.Max.Y.ToString(SharpMap.Map.numberFormat_EnUS));
  642.             if (iSRID > 0)
  643.                 strBbox = String.Format(SharpMap.Map.numberFormat_EnUS, "SetSRID({0},{1})", strBbox, iSRID);
  644.             return strBbox;
  645.         }
  646.         #endregion
  647.     }
  648. }