📄 mssqlspatial.cs
字号:
// Copyright 2006 - Ricardo Stuven (rstuven@gmail.com)
// Copyright 2006 - Morten Nielsen (www.iter.dk)
//
// MsSqlSpatial provider by Ricardo Stuven.
// Based on PostGIS provider by Morten Nielsen.
//
// This file is part of SharpMap.
// SharpMap is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SharpMap is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License
// along with SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Data.SqlClient;
namespace SharpMap.Data.Providers
{
/// <summary>
/// Microsoft SQL Server 2005 / MsSqlSpatial dataprovider
/// </summary>
/// <example>
/// Adding a datasource to a layer:
/// <code lang="C#">
/// SharpMap.Layers.VectorLayer myLayer = new SharpMap.Layers.VectorLayer("My layer");
/// string ConnStr = @"Data Source=localhost\sqlexpress;Initial Catalog=myGisDb;Integrated Security=SSPI;";
/// myLayer.DataSource = new SharpMap.Data.Providers.MsSqlSpatial(ConnStr, "myTable", "myId");
/// </code>
/// </example>
[Serializable]
public class MsSqlSpatial : SharpMap.Data.Providers.IProvider, IDisposable
{
/// <summary>
/// Initializes a new connection to MsSqlSpatial
/// </summary>
/// <param name="ConnectionStr">Connectionstring</param>
/// <param name="tablename">Name of data table</param>
/// <param name="geometryColumnName">Name of geometry column</param>
/// /// <param name="OID_ColumnName">Name of column with unique identifier</param>
public MsSqlSpatial(string ConnectionStr, string tablename, string geometryColumnName, string OID_ColumnName)
{
this.ConnectionString = ConnectionStr;
this.Table = tablename;
this.GeometryColumn = geometryColumnName;
this.ObjectIdColumn = OID_ColumnName;
}
/// <summary>
/// Initializes a new connection to MsSqlSpatial
/// </summary>
/// <param name="ConnectionStr">Connectionstring</param>
/// <param name="tablename">Name of data table</param>
/// <param name="OID_ColumnName">Name of column with unique identifier</param>
public MsSqlSpatial(string ConnectionStr, string tablename, string OID_ColumnName) : this(ConnectionStr,tablename,"",OID_ColumnName)
{
this.GeometryColumn = this.GetGeometryColumn();
}
private bool _IsOpen;
/// <summary>
/// Returns true if the datasource is currently open
/// </summary>
public bool IsOpen
{
get { return _IsOpen; }
}
/// <summary>
/// Opens the datasource
/// </summary>
public void Open()
{
//Don't really do anything. SqlClient's ConnectionPooling takes over here
_IsOpen = true;
}
/// <summary>
/// Closes the datasource
/// </summary>
public void Close()
{
//Don't really do anything. SqlClient's ConnectionPooling takes over here
_IsOpen = false;
}
#region Disposers and finalizers
private bool disposed = false;
/// <summary>
/// Disposes the object
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
internal void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
//Close();
}
disposed = true;
}
}
/// <summary>
/// Finalizer
/// </summary>
~MsSqlSpatial()
{
Dispose();
}
#endregion
private string _ConnectionString;
/// <summary>
/// Connectionstring
/// </summary>
public string ConnectionString
{
get { return _ConnectionString; }
set { _ConnectionString = value; }
}
private string _Table;
/// <summary>
/// Data table name
/// </summary>
public string Table
{
get { return _Table; }
set { _Table = value; }
}
private string _GeometryColumn;
/// <summary>
/// Name of geometry column
/// </summary>
public string GeometryColumn
{
get { return _GeometryColumn; }
set { _GeometryColumn = value; }
}
private string _GeometryExpression = "{0}";
/// <summary>
/// Expression template for geometry column evaluation.
/// </summary>
/// <example>
/// You could, for instance, simplify your geometries before they're displayed.
/// Simplification helps to speed the rendering of big geometries.
/// Here's a sample code to simplify geometries using 100 meters of threshold.
/// <code>
/// datasource.GeometryExpression = "ST.Simplify({0}, 100)";
/// </code>
/// Also you could draw a 20 meters buffer around those little points:
/// <code>
/// datasource.GeometryExpression = "ST.Buffer({0}, 20)";
/// </code>
/// </example>
public string GeometryExpression
{
get { return _GeometryExpression; }
set { _GeometryExpression = value; }
}
private string _ObjectIdColumn;
/// <summary>
/// Name of column that contains the Object ID
/// </summary>
public string ObjectIdColumn
{
get { return _ObjectIdColumn; }
set { _ObjectIdColumn = value; }
}
/// <summary>
/// Returns geometries within the specified bounding box
/// </summary>
/// <param name="bbox"></param>
/// <returns></returns>
public Collection<Geometries.Geometry> GetGeometriesInView(SharpMap.Geometries.BoundingBox bbox)
{
Collection<Geometries.Geometry> features = new Collection<SharpMap.Geometries.Geometry>();
using (SqlConnection conn = new SqlConnection(_ConnectionString))
{
string strSQL = "SELECT ST.AsBinary(" + this.BuildGeometryExpression() + ") ";
strSQL += "FROM ST.FilterQuery" + this.BuildSpatialQuerySuffix() + "(" + this.BuildEnvelope(bbox) + ")";
if (!String.IsNullOrEmpty(_definitionQuery))
strSQL += " WHERE " + this.DefinitionQuery;
using (SqlCommand command = new SqlCommand(strSQL, conn))
{
conn.Open();
using (SqlDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
if (dr[0] != DBNull.Value)
{
SharpMap.Geometries.Geometry geom = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr[0]);
if(geom!=null)
features.Add(geom);
}
}
}
conn.Close();
}
}
return features;
}
/// <summary>
/// Returns the geometry corresponding to the Object ID
/// </summary>
/// <param name="oid">Object ID</param>
/// <returns>geometry</returns>
public SharpMap.Geometries.Geometry GetGeometryByID(uint oid)
{
SharpMap.Geometries.Geometry geom = null;
using (SqlConnection conn = new SqlConnection(_ConnectionString))
{
string strSQL = "SELECT ST.AsBinary(" + this.BuildGeometryExpression() + ") AS Geom FROM " + this.Table + " WHERE " + this.ObjectIdColumn + "='" + oid.ToString() + "'";
conn.Open();
using (SqlCommand command = new SqlCommand(strSQL, conn))
{
using (SqlDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
if (dr[0] != DBNull.Value)
geom = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr[0]);
}
}
}
conn.Close();
}
return geom;
}
/// <summary>
/// Returns geometry Object IDs whose bounding box intersects 'bbox'
/// </summary>
/// <param name="bbox"></param>
/// <returns></returns>
public Collection<uint> GetObjectIDsInView(SharpMap.Geometries.BoundingBox bbox)
{
Collection<uint> objectlist = new Collection<uint>();
using (SqlConnection conn = new SqlConnection(_ConnectionString))
{
string strSQL = "SELECT * FROM ST.FilterQuery('" + this.Table + "', '" + this.GeometryColumn + "', " + this.BuildEnvelope(bbox) + ")";
if (!String.IsNullOrEmpty(_definitionQuery))
strSQL += " WHERE " + this.DefinitionQuery;
using (SqlCommand command = new SqlCommand(strSQL, conn))
{
conn.Open();
using (SqlDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
if (dr[0] != DBNull.Value)
{
uint ID = (uint)(int)dr[0];
objectlist.Add(ID);
}
}
}
conn.Close();
}
}
return objectlist;
}
/// <summary>
/// Returns all objects within a distance of a geometry
/// </summary>
/// <param name="geom"></param>
/// <param name="distance"></param>
/// <returns></returns>
[Obsolete("Use ExecuteIntersectionQuery instead")]
public SharpMap.Data.FeatureDataTable QueryFeatures(SharpMap.Geometries.Geometry geom, double distance)
{
//List<Geometries.Geometry> features = new List<SharpMap.Geometries.Geometry>();
using (SqlConnection conn = new SqlConnection(_ConnectionString))
{
string strGeom = "ST.GeomFromText('" + geom.AsText() + "', " + this.SRID.ToString() + ")";
string strSQL = "SELECT *, ST.AsBinary(" + this.BuildGeometryExpression() + ") As sharpmap_tempgeometry ";
strSQL += "FROM ST.IsWithinDistanceQuery" + this.BuildSpatialQuerySuffix() + "(" + strGeom + ", " + distance.ToString(Map.numberFormat_EnUS) + ")";
if (!String.IsNullOrEmpty(_definitionQuery))
strSQL += " WHERE " + this.DefinitionQuery;
using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn))
{
System.Data.DataSet ds = new System.Data.DataSet();
conn.Open();
adapter.Fill(ds);
conn.Close();
if (ds.Tables.Count > 0)
{
FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]);
foreach (System.Data.DataColumn col in ds.Tables[0].Columns)
if (col.ColumnName != this.GeometryColumn && !col.ColumnName.StartsWith(this.GeometryColumn + "_Envelope_") && col.ColumnName != "sharpmap_tempgeometry")
fdt.Columns.Add(col.ColumnName,col.DataType,col.Expression);
foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
{
SharpMap.Data.FeatureDataRow fdr = fdt.NewRow();
foreach(System.Data.DataColumn col in ds.Tables[0].Columns)
if (col.ColumnName != this.GeometryColumn && !col.ColumnName.StartsWith(this.GeometryColumn + "_Envelope_") && col.ColumnName != "sharpmap_tempgeometry")
fdr[col.ColumnName] = dr[col];
if (dr["sharpmap_tempgeometry"] != DBNull.Value)
fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]);
fdt.AddRow(fdr);
}
return fdt;
}
else return null;
}
}
}
/// <summary>
/// Returns the features that intersects with 'geom'
/// </summary>
/// <param name="geom"></param>
/// <param name="ds">FeatureDataSet to fill data into</param>
public void ExecuteIntersectionQuery(SharpMap.Geometries.Geometry geom, FeatureDataSet ds)
{
List<Geometries.Geometry> features = new List<SharpMap.Geometries.Geometry>();
using (SqlConnection conn = new SqlConnection(_ConnectionString))
{
string strGeom = "ST.GeomFromText('" + geom.AsText() + "', " + this.SRID.ToString() + ")";
string strSQL = "SELECT *, ST.AsBinary(" + this.BuildGeometryExpression() + ") As sharpmap_tempgeometry ";
strSQL += "FROM ST.RelateQuery" + this.BuildSpatialQuerySuffix() + "(" + strGeom + ", 'intersects')";
if (!String.IsNullOrEmpty(_definitionQuery))
strSQL += " WHERE " + this.DefinitionQuery;
using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn))
{
conn.Open();
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -