DataTableProvider for 0.9

Topics: Data Access, SharpMap v0.9 / v1.x
Jan 25, 2008 at 7:25 AM
I am working on a web mapping app which needs to get vector data from a db via a web service, this has meant writing a new provider class using IProvider which accepts DataSet and DataTable objects, since I couldn't find one.

Hope it's of help to somone, please report back if there is anything wrong with it...

// 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.Text;
using System.Data.SqlClient;
using System.Data;
using SharpMap.Data;
using SharpMap.Data.Providers;
using SharpMap.Converters.WellKnownBinary;

namespace SharpMap.Data.Providers
{
/// <summary>
/// DataTable data provider
/// </summary>
/// <remarks>
/// <para>
/// The SQL data table MUST contain five data columns: A binary or image column (a Geometry Column) for storing WKB formatted geometries,
/// and four real values holding the boundingbox of the geometry. These must be named: EnvelopeMinX, EnvelopeMinY, EnvelopeMaxX and EnvelopeMaxY.
/// Any extra columns will be returns as feature data.
/// </para>
/// <para>For creating a valid MS SQL datatable for SharpMap, see <see cref="CreateDataTable"/>
/// for creating and uploading a datasource to MS SQL Server.</para>
/// <example>
/// Adding a datasource to a layer:
/// <code lang="C#">
/// SharpMap.Layers.VectorLayer myLayer = new SharpMap.Layers.VectorLayer("My layer");
/// myLayer.DataSource = new SharpMap.Data.Providers.DataTableProvider(table, "GeoCol", "OIDCol");
/// </code>
/// </example>
/// </remarks>
Serializable
public class DataTableProvider : IProvider, IDisposable
{
/// <summary>
/// Initializes DataTableProvider
/// </summary>
/// <param name="dt">DataTable</param>
/// <param name="geometryColumnName">Name of geometry column</param>
/// /// <param name="OID_ColumnName">Name of column with unique identifier</param>
public DataTableProvider(DataTable dt, string geometryColumnName, string OID_ColumnName)
{
this.dt = dt;
this.GeometryColumn = geometryColumnName; //Name of column to store geometry
this.ObjectIdColumn = OID_ColumnName; //Name of object ID column
}

/// <summary>
/// Initializes DataTableProvider
/// </summary>
/// <param name="ds">DataSet</param>
/// <param name="geometryColumnName">Name of geometry column</param>
/// /// <param name="OID_ColumnName">Name of column with unique identifier</param>
public DataTableProvider(DataSet ds, string geometryColumnName, string OID_ColumnName)
{
if(ds == null) throw new Exception("DataSet is null.");
if(ds.Tables.Count == 0) throw new Exception("DataSet contains no tables.");

this.dt = ds.Tables0;
this.GeometryColumn = geometryColumnName; //Name of column to store geometry
this.ObjectIdColumn = OID_ColumnName; //Name of object ID column
}

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.
_IsOpen = true;
}
/// <summary>
/// Closes the datasource
/// </summary>
public void Close()
{
//Don't really do anything.
_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>
~DataTableProvider()
{
Dispose();
}
#endregion

private string _ConnectionString;

/// <summary>
/// Connectionstring
/// </summary>
public string ConnectionString
{
get { return _ConnectionString; }
set { _ConnectionString = value; }
}

private DataTable dt;

public DataTable Table
{
get { return dt; }
set { dt = value; }
}

private string _GeometryColumn;

/// <summary>
/// Name of geometry column
/// </summary>
public string GeometryColumn
{
get { return _GeometryColumn; }
set { _GeometryColumn = 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 List<Geometries.Geometry> GetGeometriesInView(SharpMap.Geometries.BoundingBox bbox)
{
List<Geometries.Geometry> features = new List<SharpMap.Geometries.Geometry>();

foreach(DataRow dr in dt.Rows)
{
if (drthis.GeometryColumn != DBNull.Value)
{
SharpMap.Geometries.Geometry geom = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])drthis.GeometryColumn);
if (geom != null)
features.Add(geom);
}
}

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;

DataRow[] rows = dt.Select(this.ObjectIdColumn + "='" + oid.ToString());

if(rows != null)
{
if(rows.Length > 0)
geom = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])rows0this.GeometryColumn);
}

return geom;
}
/// <summary>
/// Returns geometry Object IDs whose bounding box intersects 'bbox'
/// </summary>
/// <param name="bbox"></param>
/// <returns></returns>
public List<uint> GetObjectIDsInView(SharpMap.Geometries.BoundingBox bbox)
{
List<uint> objectlist = new List<uint>();

foreach(DataRow dr in dt.Rows)
{
if (drthis.ObjectIdColumn != DBNull.Value)
{
uint ID = (uint)(int)drthis.ObjectIdColumn;
objectlist.Add(ID);
}
}

return objectlist;
}

/// <summary>
/// Returns the features that intersects with 'geom' NOT IMPLEMENTED
/// </summary>
/// <param name="geom"></param>
/// <param name="ds">FeatureDataSet to fill data into</param>
public void ExecuteIntersectionQuery(SharpMap.Geometries.Geometry geom, FeatureDataSet ds)
{
throw new NotImplementedException();
}

/// <summary>
/// Returns the number of features in the dataset
/// </summary>
/// <returns>number of features</returns>
public int GetFeatureCount()
{
return dt.Rows.Count;
}

private string _defintionQuery;

/// <summary>
/// Definition query used for limiting dataset
/// </summary>
public string DefinitionQuery
{
get { return _defintionQuery; }
set { _defintionQuery = value; }
}

#region IProvider Members

/// <summary>
/// Gets a collection of columns in the dataset
/// </summary>
public System.Data.DataColumnCollection Columns
{
get
{
throw new NotImplementedException();
}
}

private int _srid = -2;

/// <summary>
/// Spacial Reference ID
/// </summary>
public int SRID
{
get { return _srid; }
set { _srid = value; }
}

/// <summary>
/// Returns a datarow based on a RowID
/// </summary>
/// <param name="RowID"></param>
/// <returns>datarow</returns>
public SharpMap.Data.FeatureDataRow GetFeature(uint RowID)
{
DataRow[] rows = this.dt.Select(this.ObjectIdColumn + "='" + RowID.ToString());

FeatureDataTable fdt = new FeatureDataTable(this.dt);
foreach (System.Data.DataColumn col in this.dt.Columns)
if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmaptempgeometry" && !col.ColumnName.StartsWith("Envelope"))
fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);

if (rows.Length > 0)
{
System.Data.DataRow dr = rows0;
SharpMap.Data.FeatureDataRow fdr = fdt.NewRow();

foreach (System.Data.DataColumn col in this.dt.Columns)
if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmaptempgeometry" && !col.ColumnName.StartsWith("Envelope"))
fdrcol.ColumnName = drcol;

fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])drthis.GeometryColumn);

return fdr;
}
else
{
return null;
}

}

/// <summary>
/// Boundingbox of dataset
/// </summary>
/// <returns>boundingbox</returns>
public SharpMap.Geometries.BoundingBox GetExtents()
{
SharpMap.Geometries.BoundingBox box = null;

// Get region limits
double minX = (double)this.dt.Compute("Min(Envelope_MinX", "");
double minY = (double)this.dt.Compute("Min(Envelope_MinY", "");
double maxX = (double)this.dt.Compute("Min(Envelope_MaxX", "");
double maxY = (double)this.dt.Compute("Min(Envelope_MaxY", "");

box = new SharpMap.Geometries.BoundingBox(minX, minY, maxX, maxY);

return box;
}

/// <summary>
/// Gets the connection ID of the datasource
/// </summary>
public string ConnectionID
{
get { return _ConnectionString; }
}

/// <summary>
/// Returns all features with the view box
/// </summary>
/// <param name="bbox