Esempio n. 1
0
        /// <summary>
        /// Method to get the number of features in the datasource
        /// </summary>
        /// <returns>The number of features</returns>
        protected virtual int GetFeatureCountInternal()
        {
            using (var conn = CreateOpenDbConnection())
            {
                using (var command = conn.CreateCommand())
                {
                    var sql = new StringBuilder();
                    sql.AppendFormat("SELECT COUNT(*) FROM {0}", _dbUtility.DecorateTable(Schema, Table));
#pragma warning disable 612,618
                    if (!String.IsNullOrEmpty(DefinitionQuery))
                    {
                        sql.AppendFormat(" WHERE {0}", DefinitionQuery);
                    }
#pragma warning restore 612,618
                    else
                    {
                        sql.Append(FeatureColumns.GetWhereClause());
                    }

                    sql.Append(";");

                    command.CommandText = sql.ToString();
                    return((int)command.ExecuteScalar());
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Function to generate a spatial where clause for the intersection queries.
        /// </summary>
        /// <param name="bbox">The geometry</param>
        /// <param name="command">The command object, that is supposed to execute the query.</param>
        /// <returns>The spatial component of a SQL where clause</returns>
        protected override string GetSpatialWhere(IGeometry bbox, DbCommand command)
        {
            var sqlCommand = (SqlCommand)command;

#pragma warning disable 612,618
            var pwhere = new SqlParameter("@PWhere", !string.IsNullOrEmpty(DefinitionQuery)
                                                         ? DefinitionQuery
                                                         : FeatureColumns.GetWhereClause(null));
#pragma warning restore 612,618
            sqlCommand.Parameters.Add(pwhere);

            return(string.Format("{3} IN (SELECT _tmp_.{3} FROM ST.RelateQueryWhere('{0}', '{1}', {2}, 'Intersects', @PWhere) AS _tmp_)",
                                 Table, GeometryColumn, BuildGeometry(bbox, sqlCommand), DbUtility.DecorateColumn(ObjectIdColumn)));
        }
Esempio n. 3
0
        ///// <summary>
        ///// Returns geometries within the specified bounding box
        ///// </summary>
        ///// <param name="bbox"></param>
        ///// <returns></returns>
        //protected override Collection<IGeometry> GetGeometriesInViewInternal(Envelope bbox)
        //{
        //    var features = new Collection<IGeometry>();
        //    using (var conn = CreateOpenDbConnection())
        //    {
        //        var strSQL = "SELECT ST.AsBinary(" + BuildGeometryExpression() + ") ";
        //        strSQL += "FROM ST.FilterQuery" + BuildSpatialQuerySuffix() + "(" + BuildEnvelope(bbox) + ")";

        //        if (!String.IsNullOrEmpty(DefinitionQuery))
        //            strSQL += " WHERE " + DefinitionQuery;

        //        if (!String.IsNullOrEmpty(OrderQuery))
        //            strSQL += " ORDER BY " + OrderQuery;

        //        using (var command = new SqlCommand(strSQL, conn))
        //        {
        //            conn.Open();
        //            using (var dr = command.ExecuteReader())
        //            {
        //                while (dr.Read())
        //                {
        //                    if (dr[0] != DBNull.Value)
        //                    {
        //                        var geom = GeometryFromWKB.Parse((byte[]) dr[0], Factory);
        //                        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>
        //protected override IGeometry GetGeometryByIDInternal(uint oid)
        //{
        //    using (var conn = CreateOpenDbConnection())
        //    {
        //        var strSQL = "SELECT ST.AsBinary(" + BuildGeometryExpression() + ") AS Geom FROM " + Table +
        //                     " WHERE " + ObjectIdColumn + "='" + oid.ToString() + "'";

        //        using (var command = new SqlCommand(strSQL, conn))
        //        {
        //            using (var dr = command.ExecuteReader())
        //            {
        //                while (dr.Read())
        //                {
        //                    if (dr[0] != DBNull.Value)
        //                        return GeometryFromWKB.Parse((byte[]) dr[0], Factory);
        //                }
        //            }
        //        }
        //    }
        //    return null;
        //}


        /// <summary>
        /// Gets the object of features that lie within the specified <see cref="GeoAPI.Geometries.Envelope"/>
        /// </summary>
        /// <param name="bbox">The bounding box</param>
        /// <returns>A collection of object ids</returns>
        protected override Collection <uint> GetObjectIDsInViewInternal(Envelope bbox)
        {
            var objectlist = new Collection <uint>();

            using (var conn = CreateOpenDbConnection())
            {
                using (var command = (SqlCommand)conn.CreateCommand())
                {
#pragma warning disable 612,618
                    var @where = !string.IsNullOrEmpty(DefinitionQuery)
                        ? DefinitionQuery
                        : FeatureColumns.GetWhereClause(null);
#pragma warning restore 612,618
                    var strSQL = string.Format("SELECT _sm_.{4} FROM ST.FilterQueryWhere('{0}','{1}',{3},'{2}') AS _sm_;",
                                               Table, GeometryColumn, @where, BuildEnvelope(bbox, command), ObjectIdColumn);

#pragma warning disable 612, 618
                    if (!String.IsNullOrEmpty(OrderQuery))
                    {
                        strSQL += " ORDER BY " + OrderQuery;
                    }
#pragma warning restore 612, 618

                    command.CommandText = strSQL;

                    using (var dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            if (!dr.IsDBNull(0))
                            {
                                var id = Convert.ToUInt32(dr[0]);
                                objectlist.Add(id);
                            }
                        }
                    }
                    conn.Close();
                }
            }
            return(objectlist);
        }
Esempio n. 4
0
        ///// <summary>
        ///// Returns the features that intersects with 'geom'
        ///// </summary>
        ///// <param name="geom"></param>
        ///// <param name="ds">FeatureDataSet to fill data into</param>
        //protected override void OnExecuteIntersectionQuery(IGeometry geom, FeatureDataSet ds)
        //{
        //    var features = new List<IGeometry>();
        //    using (var conn = CreateOpenDbConnection())
        //    {
        //        string strGeom;
        //        if (TargetSRID > 0 && SRID > 0 && SRID != TargetSRID)
        //            strGeom = "ST.Transform(ST.GeomFromText('" + geom.AsText() + "'," + TargetSRID.ToString(Map.NumberFormatEnUs) + ")," +
        //                      SRID.ToString(Map.NumberFormatEnUs) + ")";
        //        else
        //            strGeom = "ST.GeomFromText('" + geom.AsText() + "', " + SRID.ToString(Map.NumberFormatEnUs) + ")";

        //        string strSQL = "SELECT " + FeatureColumns + ", ST.AsBinary(" + BuildGeometryExpression() +
        //                        ") As sharpmap_tempgeometry ";
        //        strSQL += "FROM ST.RelateQuery" + BuildSpatialQuerySuffix() + "(" + strGeom + ", 'intersects')";

        //        if (!String.IsNullOrEmpty(DefinitionQuery))
        //            strSQL += " WHERE " + DefinitionQuery;

        //        if (!String.IsNullOrEmpty(OrderQuery))
        //            strSQL += " ORDER BY " + OrderQuery;

        //        using (var adapter = new SqlDataAdapter(strSQL, conn))
        //        {
        //            conn.Open();
        //            adapter.Fill(ds);
        //            conn.Close();
        //            if (ds.Tables.Count > 0)
        //            {
        //                FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]);
        //                foreach (DataColumn col in ds.Tables[0].Columns)
        //                    if (col.ColumnName != GeometryColumn &&
        //                        !col.ColumnName.StartsWith(GeometryColumn + "_Envelope_") &&
        //                        col.ColumnName != "sharpmap_tempgeometry")
        //                        fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
        //                foreach (DataRow dr in ds.Tables[0].Rows)
        //                {
        //                    FeatureDataRow fdr = fdt.NewRow();
        //                    foreach (DataColumn col in ds.Tables[0].Columns)
        //                        if (col.ColumnName != GeometryColumn &&
        //                            !col.ColumnName.StartsWith(GeometryColumn + "_Envelope_") &&
        //                            col.ColumnName != "sharpmap_tempgeometry")
        //                            fdr[col.ColumnName] = dr[col];
        //                    if (dr["sharpmap_tempgeometry"] != DBNull.Value)
        //                        fdr.Geometry = GeometryFromWKB.Parse((byte[]) dr["sharpmap_tempgeometry"], Factory);
        //                    fdt.AddRow(fdr);
        //                }
        //                ds.Tables.Add(fdt);
        //            }
        //        }
        //    }
        //}

        ///// <summary>
        ///// Spacial Reference ID handling
        ///// </summary>
        //protected override int SRID
        //{
        //    get { return base.SRID; }
        //    set
        //    {

        //        if (SRID == -2)
        //        return;
        //        {
        //            int dotPos = Table.IndexOf(".");
        //            string strSQL = "";
        //            if (dotPos == -1)
        //                strSQL = "select SRID from ST.GEOMETRY_COLUMNS WHERE F_TABLE_NAME='" + Table + "'";
        //            else
        //            {
        //                var schema = Table.Substring(0, dotPos);
        //                var table = Table.Substring(dotPos + 1);
        //                strSQL = "select SRID from ST.GEOMETRY_COLUMNS WHERE F_TABLE_SCHEMA='" + schema +
        //                         "' AND F_TABLE_NAME='" + table + "'";
        //            }

        //            using (var conn = (SqlConnection)CreateOpenDbConnection())
        //            {
        //                using (var command = new SqlCommand(strSQL, conn))
        //                {
        //                    try
        //                    {
        //                        conn.Open();
        //                        base.SRID = (int) command.ExecuteScalar();
        //                        conn.Close();
        //                    }
        //                    catch
        //                    {
        //                        base.SRID = -1;
        //                    }
        //                }
        //            }
        //        }
        //    }
        //}


        ///// <summary>
        ///// Returns a datarow based on a RowID
        ///// </summary>
        ///// <param name="rowId"></param>
        ///// <returns>datarow</returns>
        //protected override FeatureDataRow GetFeatureInternal(uint rowId)
        //{
        //    using (var conn = (SqlConnection)CreateOpenDbConnection())
        //    {
        //        string strSQL = "select " + FeatureColumns + ", ST.AsBinary(" + BuildGeometryExpression() +
        //                        ") As sharpmap_tempgeometry from " + Table + " WHERE " + ObjectIdColumn + "='" +
        //                        rowId.ToString() + "'";
        //        using (var adapter = new SqlDataAdapter(strSQL, conn))
        //        {
        //            FeatureDataSet ds = new FeatureDataSet();
        //            conn.Open();
        //            adapter.Fill(ds);
        //            conn.Close();
        //            if (ds.Tables.Count > 0)
        //            {
        //                FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]);
        //                foreach (DataColumn col in ds.Tables[0].Columns)
        //                    if (col.ColumnName != GeometryColumn &&
        //                        !col.ColumnName.StartsWith(GeometryColumn + "_Envelope_") &&
        //                        col.ColumnName != "sharpmap_tempgeometry")
        //                        fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
        //                if (ds.Tables[0].Rows.Count > 0)
        //                {
        //                    DataRow dr = ds.Tables[0].Rows[0];
        //                    FeatureDataRow fdr = fdt.NewRow();
        //                    foreach (DataColumn col in ds.Tables[0].Columns)
        //                        if (col.ColumnName != GeometryColumn &&
        //                            !col.ColumnName.StartsWith(GeometryColumn + "_Envelope_") &&
        //                            col.ColumnName != "sharpmap_tempgeometry")
        //                            fdr[col.ColumnName] = dr[col];
        //                    if (dr["sharpmap_tempgeometry"] != DBNull.Value)
        //                        fdr.Geometry = GeometryFromWKB.Parse((byte[]) dr["sharpmap_tempgeometry"]);
        //                    return fdr;
        //                }
        //                else
        //                    return null;
        //            }
        //            else
        //                return null;
        //        }
        //    }
        //}

        /// <summary>
        /// Boundingbox of dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        protected override Envelope GetExtentsInternal()
        {
            using (var conn = (SqlConnection)CreateOpenDbConnection())
            {
#pragma warning disable 612,618
                var where = (String.IsNullOrEmpty(DefinitionQuery)
                                 ? FeatureColumns.GetWhereClause()
                                 : DefinitionQuery).Replace(" WHERE ", "").Replace("'", "''");
#pragma warning restore 612,618

                var strSQL = string.Format("SELECT ST.AsBinary(ST.EnvelopeQueryWhere('{0}', '{1}', '{2}'))", /*DbUtility.DecorateTable(Schema, Table)*/ /* Schema, */ Table,
                                           GeometryColumn, where);

                using (var command = new SqlCommand(strSQL, conn))
                {
                    var result = command.ExecuteScalar();
                    return(result == DBNull.Value
                        ? null :
                           GeometryFromWKB.Parse((byte[])result, Factory).EnvelopeInternal);
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Returns the data associated with all the geometries that are intersected by 'geom'
        /// </summary>
        /// <param name="spatialWhere">Geometry to intersect with</param>
        /// <param name="fds">FeatureDataSet to fill data into</param>
        protected virtual void ExecuteIntersectionQueryInternal(object spatialWhere, FeatureDataSet fds)
        {
            var fdt = CreateNewTable(true);

            fdt.BeginLoadData();

            using (var cn = CreateOpenDbConnection())
            {
                using (var cmd = cn.CreateCommand())
                {
                    string from = null;

                    var spatialWhereString = string.Empty;
                    var env = spatialWhere as Envelope;

                    if (env != null)
                    {
                        from = GetFrom(env, cmd);
                        spatialWhereString = GetSpatialWhere(env, cmd);
                    }
                    else
                    {
                        var geom = spatialWhere as IGeometry;
                        if (geom != null)
                        {
                            from = GetFrom(geom, cmd);
                            spatialWhereString = GetSpatialWhere(geom, cmd);
                        }
                    }

                    cmd.CommandText = FeatureColumns.GetSelectClause(from)
#pragma warning disable 612,618
                                      + (string.IsNullOrEmpty(DefinitionQuery)
#pragma warning restore 612,618
                               ? FeatureColumns.GetWhereClause(spatialWhereString)
                               : (" WHERE " + _definitionQuery +
                                  (string.IsNullOrEmpty(spatialWhereString)
                                            ? ""
                                            : " AND " + spatialWhereString)))

                                      + FeatureColumns.GetGroupByClause()
                                      + FeatureColumns.GetOrderByClause();

                    var numColumns = fdt.Columns.Count;
                    var geomIndex  = numColumns;

                    Logger.Debug(t => t("Executing query:\n{0}", PrintCommand(cmd)));
                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var data = new object[numColumns + 1];
                            if (dr.GetValues(data) > 0)
                            {
                                var loadData = new object[geomIndex];
                                Array.Copy(data, 0, loadData, 0, geomIndex);
                                var row = (FeatureDataRow)fdt.LoadDataRow(loadData, true);
                                row.Geometry = GeometryFromWKB.Parse((byte[])data[geomIndex], Factory);
                            }
                        }
                    }
                }
            }

            fdt.EndLoadData();

            fds.Tables.Add(fdt);
        }