private string GetGeoJson_BBox(BoundingBoxQuery query, Metrics metrics, string tableName) { string strOut = null; metrics.Start("Init"); LayerStyle style = new LayerStyle(query.FillColor, query.StrokeColor, query.strokeThickness); GeoJSONGeometryWriter writer = null; try { //bool useGeography = rdr.GetFieldType(0).Name == "SqlGeography"; PrecisionReducerCoordinateConverter coordConverter = new PrecisionReducerCoordinateConverter(query.BBox, query.Width, query.Height); writer = new GeoJSONGeometryWriter(); writer.Init(coordConverter, query.Width, query.Height, style, metrics); DataService svc = new DataService(this.UseInMemoryCache, this.MetricsType, this.GeometryReduce, this.GeometryRemoveArtefacts, this.GeometryClip); strOut = svc.GetObjectGeneric_FromCacheBBox <string, double[]>(query, metrics, tableName, writer); } catch (Exception) { throw; } finally { if (writer != null) { writer.Dispose(); writer = null; } } return(strOut); }
private Bitmap GetImage_BBox(BoundingBoxQuery query, Metrics metrics, string tableName) { Bitmap bmpOut = null; metrics.Start("Init"); LayerStyle style = new LayerStyle(query.FillColor, query.StrokeColor, query.strokeThickness); GDIBitmapGeometryWriter writer = null; try { //bool useGeography = rdr.GetFieldType(0).Name == "SqlGeography"; BitmapCoordConverter coordConverter = new BitmapCoordConverter(query.Width, query.Height, query.BBox); writer = new GDIBitmapGeometryWriter(SmoothingMode.AntiAlias, coordConverter); writer.Init(query.Width, query.Height, style, metrics); DataService svc = new DataService(this.UseInMemoryCache, this.MetricsType, this.GeometryReduce, this.GeometryRemoveArtefacts, this.GeometryClip); bmpOut = svc.GetObjectGeneric_FromCacheBBox <Bitmap, System.Drawing.Point>(query, metrics, tableName, writer); } catch (Exception) { throw; } finally { if (writer != null) { writer.Dispose(); writer = null; } } return(bmpOut); }
private List <SqlGeometry> GetGeometries_BBox(BoundingBoxQuery query, Metrics metrics, string tableName) { List <SqlGeometry> outList = null; metrics.Start("Init"); LayerStyle style = new LayerStyle(query.FillColor, query.StrokeColor, query.strokeThickness); SqlGeometryWriter writer = null; try { //bool useGeography = rdr.GetFieldType(0).Name == "SqlGeography"; writer = new SqlGeometryWriter(); DataService svc = new DataService(this.UseInMemoryCache, this.MetricsType, this.GeometryReduce, this.GeometryRemoveArtefacts, this.GeometryClip); outList = svc.GetObjectGeneric_FromCacheBBox(query, metrics, tableName, writer); } catch (Exception) { throw; } finally { if (writer != null) { writer.Dispose(); writer = null; } } return(outList); }
public string GetGeoJson(BingTileQuery query) { int tileX, tileY, zoom; Metrics metrics = new Metrics(this._metricsType); metrics.Start("Global"); BoundingBoxQuery bboxQuery = BoundingBoxQuery.FromBingTileQuery(query); // Get tile coordinates BingMapsTileSystem.QuadKeyToTileXY(query.quadKey, out tileX, out tileY, out zoom); Queue <string> geoJsonQueue = new Queue <string>(); foreach (string table in query.Tables()) { string geojson = null; //bool foundInCache = false; //if (query.CacheMode != enDiskCacheMode.None) //{ // // If cacheMode is Read, see if image exists on disk // bmp = this.LoadTileFromDisc(tileX, tileY, zoom, table); // foundInCache = bmp != null; //} if (geojson == null) { DateTime start = DateTime.Now; geojson = GetGeoJson_BBox(bboxQuery, metrics, table); } //// Save to disc if image not empty and cacheMode is ReadWrite //if (query.CacheMode == enDiskCacheMode.ReadWrite // && !foundInCache // && bmp != null // && bmp.Tag == null) // this.SaveTileToDisc(tileX, tileY, zoom, table, bmp); geoJsonQueue.Enqueue(geojson); } return(geoJsonQueue.Dequeue()); }
/// <summary> /// For each table in the query, return a FeatureCollection. /// </summary> /// <param name="query">query with a bounding box</param> /// <returns>set of GeoJson Features</returns> public Bitmap GetImage(BoundingBoxQuery query) { Bitmap bmp = new Bitmap(query.Width, query.Height); Metrics metrics = new Metrics(this._metricsType); try { metrics.Start("Global"); using (Graphics g = Graphics.FromImage(bmp)) { foreach (string table in query.Tables()) { Bitmap bmpTable = null; #region Preload cache if necessary if (UseInMemoryCache) { metrics.Start("Cache"); if (!GeometryCache.IsCacheLoaded(table)) { while (!GeometryCache.IsCacheLoaded(table)) { GeometryCache.LoadCache(table, this.GetConnectionString()); Trace.WriteLine(string.Format("Thread {0} waiting for cache...", Thread.CurrentThread.ManagedThreadId)); } } metrics.Stop("Cache"); } #endregion if (query.IsBench) { bmpTable = GetBenchImageGeneric(query, metrics, table, UseInMemoryCache); } else if (UseInMemoryCache) { bmpTable = GetImage_BBox(query, metrics, table); } //else // bmpTable = GetImageGeneric_FromDB(query, metrics, table, false); g.DrawImageUnscaled(bmpTable, 0, 0); bmp.Tag = bmpTable.Tag; bmpTable.Dispose(); } } metrics.Stop("Global"); #region Calculate metrics to return. // Calculate metrics to return. switch (_metricsType) { case enMetricsType.OnlyTime: string msg = null; foreach (var kv in metrics.GetTaskTimes()) { msg += string.Format("{0}: {1,6:###,###} ms{2}", kv.Key, kv.Value.TotalMilliseconds, Environment.NewLine); } this.DrawMsgInImage(ref bmp, msg); break; default: break; } #endregion } catch (Exception ex) { #region Write exception in image // Write exception in image using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.FromArgb(128, Color.Red)); using (Font font = new Font(FontFamily.GenericMonospace, 11, FontStyle.Regular, GraphicsUnit.Pixel)) g.DrawString(ex.ToString(), font, Brushes.Black, new RectangleF(0, 0, 256, 256)); } #endregion } return(bmp); }
private Bitmap GetBenchImageGeneric(BoundingBoxQuery query, Metrics metrics, string tableName, bool useCache) { Bitmap bmp = new Bitmap(query.Width, query.Height); try { string strQuery = null; if (useCache) { strQuery = SqlServerModel.GenerateGetGeomIdInBBoxScript(tableName, query.BBox); } else { strQuery = SqlServerModel.GenerateGetGeomInBBoxScript(tableName, query.BBox); } SqlGeometry bboxGeom = SqlServerModel.GeometryFromBoundingBox(query.BBox); //start = DateTime.Now; //IList<int> resultsWithIndex = _spatialIndex.Query(new Envelope(query.BBox.minX, query.BBox.maxX, query.BBox.minY, query.BBox.maxY)); //foreach (int id in resultsWithIndex) //{ // SqlGeometry geom = GetGeomFromCache(tableName, id); //} //metrics.TaskTimesMilliseconds.Add(string.Format("quadTree {0} items", resultsWithIndex.Count), (int)(DateTime.Now - start).TotalMilliseconds); metrics.Start("STR"); IList <int> resultsWithIndexSTR = GeometryCache.Query(tableName, new Envelope(query.BBox.minX, query.BBox.maxX, query.BBox.minY, query.BBox.maxY)); foreach (int id in resultsWithIndexSTR) { SqlGeometry geom = GeometryCache.GetGeometry(tableName, id); } metrics.Stop("STR"); Trace.WriteLine(string.Format("STR {0} items", resultsWithIndexSTR.Count)); //List<SqlGeometry> vlist = ImageryDataService._geomCacheByTableThenId[tableName].Values.Where(g => g.STIntersects(bboxGeom).Value).ToList(); metrics.Start("DB"); int nbRecords = 0; using (var conn = GetOpenConnection()) { using (var cmd = new SqlCommand(strQuery, conn)) { cmd.CommandType = System.Data.CommandType.Text; using (var rdr = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess)) { while (rdr.Read()) { int id = rdr.GetSqlInt32(0).Value; SqlGeometry geom = GeometryCache.GetGeometry(tableName, id); nbRecords++; } rdr.Close(); } } } metrics.Stop("DB"); Trace.WriteLine(string.Format("DB {0} items", nbRecords)); } catch (Exception) { throw; } return(bmp); }
public Bitmap GetImage(BingTileQuery query) { int tileX, tileY, zoom; Metrics metrics = new Metrics(this._metricsType); metrics.Start("Global"); BoundingBoxQuery bboxQuery = BoundingBoxQuery.FromBingTileQuery(query); // Get tile coordinates BingMapsTileSystem.QuadKeyToTileXY(query.quadKey, out tileX, out tileY, out zoom); Queue <Bitmap> bmpQueue = new Queue <Bitmap>(); foreach (string table in query.Tables()) { Bitmap bmp = null; bool foundInCache = false; if (query.CacheMode != enDiskCacheMode.None) { // If cacheMode is Read, see if image exists on disk bmp = this.LoadTileFromDisc(tileX, tileY, zoom, table); foundInCache = bmp != null; } if (bmp == null) { DateTime start = DateTime.Now; if (bboxQuery.IsBench) { bmp = GetBenchImageGeneric(bboxQuery, metrics, table, UseInMemoryCache); } else { //string test = GetGeoJson_BBox(bboxQuery, metrics, table); bmp = GetImage_BBox(bboxQuery, metrics, table); } //else // bmp = GetImageGeneric_FromDB(bboxQuery, metrics, table, false); } // Save to disc if image not empty and cacheMode is ReadWrite if (query.CacheMode == enDiskCacheMode.ReadWrite && !foundInCache && bmp != null && bmp.Tag == null) { this.SaveTileToDisc(tileX, tileY, zoom, table, bmp); } bmpQueue.Enqueue(bmp); } metrics.Stop("Global"); if (bmpQueue.Count <= 1) { Bitmap bmpOut = bmpQueue.Dequeue(); #region Calculate metrics to return. // Calculate metrics to return. switch (_metricsType) { case enMetricsType.OnlyTime: string msg = string.Empty; foreach (var kv in metrics.GetTaskTimes()) { msg += string.Format("{0}: {1,6:###,###} ms{2}", kv.Key, kv.Value.TotalMilliseconds, Environment.NewLine); } this.DrawMsgInImage(ref bmpOut, msg); break; default: break; } #endregion return(bmpOut); } else { Bitmap outBmp = bmpQueue.Dequeue(); using (Graphics g = Graphics.FromImage(outBmp)) { do { Bitmap curBmp = bmpQueue.Dequeue(); if (curBmp.Tag != null) { outBmp.Tag = curBmp.Tag; } g.DrawImageUnscaled(curBmp, 0, 0); curBmp.Dispose(); }while (bmpQueue.Count > 0); } return(outBmp); } }
public Toutput GetObjectGeneric_FromCacheBBox <Toutput, Tpoint>(BoundingBoxQuery query, Metrics metrics, string tableName, GeometryWriterBase <Toutput, Tpoint> writer) { Toutput objOut = default(Toutput); metrics.Start("Init"); try { double reduceTolerance = Math.Min(query.BBox.Width / query.Width, query.BBox.Height / query.Height); // degrees per pixel / 2 double reduceToleranceMeters = reduceTolerance * 6378137; //double pixelArea = Math.Pow(BingMapsTileSystem.GroundResolution(query.BBox.maxY, query.ZoomLevel), 2); // mapResolution * mapResolution double pixelRadiansAreaXY = ((query.BBox.maxX - query.BBox.minX) / query.Width) * ((query.BBox.maxY - query.BBox.minY) / query.Height); int numPixels = 0; #region Get data from cache or open DB if (UseInMemoryCache) { #region From Cache #region Preload cache metrics.Start("Cache"); if (!GeometryCache.IsCacheLoaded(query.Tables()[0])) { while (!GeometryCache.IsCacheLoaded(query.Tables()[0])) { GeometryCache.LoadCache(query.Tables()[0], this.GetConnectionString()); Trace.WriteLine(string.Format("Thread {0} waiting for cache...", System.Threading.Thread.CurrentThread.ManagedThreadId)); } } metrics.Stop("Cache"); #endregion SqlGeometry bboxGeom = SqlServerModel.GeometryFromBoundingBox(query.BBox); IList <int> resultsWithIndexSTR = GeometryCache.Query(tableName, new Envelope(query.BBox.minX, query.BBox.maxX, query.BBox.minY, query.BBox.maxY)); if (resultsWithIndexSTR.Count > 0) { foreach (int id in resultsWithIndexSTR) { SqlGeometry geom = GeometryCache.GetGeometry(tableName, id); double geomArea = GeometryCache.GetGeometryArea(tableName, id); bool geomIsPixel = geomArea > 0 && geomArea <= pixelRadiansAreaXY; metrics.Start("Process"); ProcessGeometry <Toutput, Tpoint>(writer, reduceTolerance, pixelRadiansAreaXY, ref numPixels, ref geom, geomArea); metrics.Stop("Process"); } metrics.Start("GetOutput"); objOut = writer.GetOutput(); metrics.Stop("GetOutput"); } #endregion } else { #region Get data from SQL DB using (SqlConnection conn = GetOpenConnection()) { string strQuery = SqlServerModel.GenerateGetGeomInBBoxScript(tableName, query.BBox); using (var cmd = new SqlCommand(strQuery, conn)) { cmd.CommandType = System.Data.CommandType.Text; using (var rdr = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess)) { if (rdr.HasRows) { while (rdr.Read()) { metrics.Start("Area"); SqlGeometry geom = SqlGeometry.STGeomFromWKB(rdr.GetSqlBytes(0), 4326); double geomArea = geom.STArea().Value; // optimize this by having area field in DB metrics.Stop("Area"); metrics.Start("Process"); ProcessGeometry <Toutput, Tpoint>(writer, reduceTolerance, pixelRadiansAreaXY, ref numPixels, ref geom, geomArea); metrics.Stop("Process"); } metrics.Start("GetOutput"); objOut = writer.GetOutput(); metrics.Stop("GetOutput"); } rdr.Close(); } } } #endregion } #endregion } catch (Exception) { throw; } return(objOut); }
/// <summary> /// For each table in the query, return a FeatureCollection. /// </summary> /// <param name="query">query with a bounding box</param> /// <returns>set of GeoJson Features</returns> public string GetGeoJson(BoundingBoxQuery query) { string geojson = null; Metrics metrics = new Metrics(this._metricsType); try { metrics.Start("Global"); foreach (string table in query.Tables()) { #region Preload cache if necessary if (UseInMemoryCache) { metrics.Start("Cache"); if (!GeometryCache.IsCacheLoaded(table)) { while (!GeometryCache.IsCacheLoaded(table)) { GeometryCache.LoadCache(table, this.GetConnectionString()); Trace.WriteLine(string.Format("Thread {0} waiting for cache...", Thread.CurrentThread.ManagedThreadId)); } } metrics.Stop("Cache"); } #endregion geojson += GetGeoJson_BBox(query, metrics, table); } metrics.Stop("Global"); #region Calculate metrics to return. (TODO) // Calculate metrics to return. switch (_metricsType) { case enMetricsType.OnlyTime: string msg = null; foreach (var kv in metrics.GetTaskTimes()) { msg += string.Format("{0}: {1,6:###,###} ms{2}", kv.Key, kv.Value.TotalMilliseconds, Environment.NewLine); } //this.DrawMsgInImage(ref bmp, msg); break; default: break; } #endregion } catch (Exception ex) { throw; } return(geojson); }
/// <summary> /// For each table in the query, return a FeatureCollection. /// </summary> /// <param name="query">query with a bounding box</param> /// <returns>set of GeoJson Features</returns> public GeoJsonResult GetGeoJsonData(BoundingBoxQuery query) { var data = new GeoJsonResult(); var start = DateTime.Now; try { foreach (string table in query.Tables) { if (query.useGeography) { data.featureSet.Add(table, GetGeoJsonGeneric((SqlGeography)query.Box, query.Resolution, query.NumDigits, table)); } else { data.featureSet.Add(table, GetGeoJsonGeneric((SqlGeometry)query.Box, query.Resolution, query.NumDigits, table)); } } } catch (Exception ex) { data = new GeoJsonResult() { error = "Something went wrong : " + ex.Message }; Debug.WriteLine(data.error); } #region Calculate metrics to return. // Calculate metrics to return. var elapsed = DateTime.Now - start; // This counting of the number of points is based on the simplified geometries being returned. // For example, only the points in the first ring of polygons is counted since we only use the first ring // (which is another name for the outside border). // The number of points is not needed for drawing, it is just being returned in case you are interested. // If you like, you can extend the counting functions below. switch (_metricsType) { case enMetricsType.None: break; default: data.metrics.QueryTimeMilliseconds = (int)elapsed.TotalMilliseconds; break; } switch (_metricsType) { case enMetricsType.TimeAndFeatureCount: data.metrics.NumberOfGemetryCollection = data.featureSet.Values.SelectMany(fc => fc.features).Select(f => f.geometry).OfType <Models.GeoJson.GeometryCollection>().Count(); data.metrics.NumberOfLineString = data.featureSet.Values.SelectMany(fc => fc.features).Select(f => f.geometry).OfType <Models.GeoJson.LineString>().Count(); data.metrics.NumberOfMultiLineString = data.featureSet.Values.SelectMany(fc => fc.features).Select(f => f.geometry).OfType <Models.GeoJson.MultiLineString>().Count(); data.metrics.NumberOfMultiPoint = data.featureSet.Values.SelectMany(fc => fc.features).Select(f => f.geometry).OfType <Models.GeoJson.MultiPoint>().Count(); data.metrics.NumberOfMultiPolygon = data.featureSet.Values.SelectMany(fc => fc.features).Select(f => f.geometry).OfType <Models.GeoJson.MultiPolygon>().Count(); data.metrics.NumberOfPoint = data.featureSet.Values.SelectMany(fc => fc.features).Select(f => f.geometry).OfType <Models.GeoJson.Point>().Count(); data.metrics.NumberOfPolygon = data.featureSet.Values.SelectMany(fc => fc.features).Select(f => f.geometry).OfType <Models.GeoJson.Polygon>().Count(); //data.metrics.NumberOfPoints += data.featureSet.Values.SelectMany(fc => fc.features).Select(f => f.geometry).OfType<Models.GeoJson.Point>().Count(); //data.metrics.NumberOfPoints += data.featureSet.Values.SelectMany(fc => fc.features).Select(f => f.geometry).OfType<Models.GeoJson.MultiPoint>().Select(mp => mp.coordinates.Length).Sum(); //data.metrics.NumberOfPoints += data.featureSet.Values.SelectMany(fc => fc.features).Select(f => f.geometry).OfType<Models.GeoJson.LineString>().Select(ls => ls.coordinates.Length).Sum(); //data.metrics.NumberOfPoints += data.featureSet.Values.SelectMany(fc => fc.features).Select(f => f.geometry).OfType<Models.GeoJson.MultiLineString>().SelectMany(mls => mls.coordinates).Select(a => a.Length).Sum(); //data.metrics.NumberOfPoints += data.featureSet.Values.SelectMany(fc => fc.features).Select(f => f.geometry).OfType<Models.GeoJson.Polygon>().Select(p => p.coordinates[0].Length).Sum(); //data.metrics.NumberOfPoints += data.featureSet.Values.SelectMany(fc => fc.features).Select(f => f.geometry).OfType<Models.GeoJson.MultiPolygon>().SelectMany(p => p.coordinates).Select(pa => pa[0].Length).Sum(); break; default: break; } #endregion return(data); }