forked from SharpMap/SharpMap
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWmsServer.cs
More file actions
1271 lines (1204 loc) · 64.1 KB
/
WmsServer.cs
File metadata and controls
1271 lines (1204 loc) · 64.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// 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.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Xml;
using GeoAPI.Geometries;
using SharpMap.Data;
using SharpMap.Data.Providers;
using SharpMap.Layers;
using System.Collections.Generic;
using System.Text;
using GeoAPI.CoordinateSystems.Transformations;
namespace SharpMap.Web.Wms
{
/// <summary>
/// This is a helper class designed to make it easy to create a WMS Service
/// </summary>
public static class WmsServer
{
#region Delegates
public delegate FeatureDataTable InterSectDelegate(FeatureDataTable featureDataTable, Envelope box);
#endregion
private static InterSectDelegate _intersectDelegate;
private static int _pixelSensitivity = -1;
private static Encoding _featureInfoResponseEncoding = Encoding.UTF8;
/// <summary>
/// Set the characterset used in FeatureInfo responses
/// </summary>
/// <remarks>
/// To use Windows-1252 set the FeatureInfoResponseEncoding = System.Text.Encoding.GetEncoding(1252);
/// Set to Null to not set any specific encoding in response
/// </remarks>
public static Encoding FeatureInfoResponseEncoding
{
get { return _featureInfoResponseEncoding; }
set { _featureInfoResponseEncoding = value; }
}
/// <summary>
/// Generates a WMS 1.3.0 compliant response based on a <see cref="SharpMap.Map"/> and the current HttpRequest.
/// </summary>
/// <remarks>
/// <para>
/// The Web Map Server implementation in SharpMap requires v1.3.0 compatible clients,
/// and support the basic operations "GetCapabilities" and "GetMap"
/// as required by the WMS v1.3.0 specification. SharpMap does not support the optional
/// GetFeatureInfo operation for querying.
/// </para>
/// <example>
/// Creating a WMS server in ASP.NET is very simple using the classes in the SharpMap.Web.Wms namespace.
/// <code lang="C#">
/// void page_load(object o, EventArgs e)
/// {
/// //Get the path of this page
/// string url = (Request.Url.Query.Length>0?Request.Url.AbsoluteUri.Replace(Request.Url.Query,""):Request.Url.AbsoluteUri);
/// SharpMap.Web.Wms.Capabilities.WmsServiceDescription description =
/// new SharpMap.Web.Wms.Capabilities.WmsServiceDescription("Acme Corp. Map Server", url);
///
/// // The following service descriptions below are not strictly required by the WMS specification.
///
/// // Narrative description and keywords providing additional information
/// description.Abstract = "Map Server maintained by Acme Corporation. Contact: webmaster@wmt.acme.com. High-quality maps showing roadrunner nests and possible ambush locations.";
/// description.Keywords.Add("bird");
/// description.Keywords.Add("roadrunner");
/// description.Keywords.Add("ambush");
///
/// //Contact information
/// description.ContactInformation.PersonPrimary.Person = "John Doe";
/// description.ContactInformation.PersonPrimary.Organisation = "Acme Inc";
/// description.ContactInformation.Address.AddressType = "postal";
/// description.ContactInformation.Address.Country = "Neverland";
/// description.ContactInformation.VoiceTelephone = "1-800-WE DO MAPS";
/// //Impose WMS constraints
/// description.MaxWidth = 1000; //Set image request size width
/// description.MaxHeight = 500; //Set image request size height
///
/// //Call method that sets up the map
/// //We just add a dummy-size, since the wms requests will set the image-size
/// SharpMap.Map myMap = MapHelper.InitializeMap(new System.Drawing.Size(1,1));
///
/// //Parse the request and create a response
/// SharpMap.Web.Wms.WmsServer.ParseQueryString(myMap,description);
/// }
/// </code>
/// </example>
/// </remarks>
/// <param name="map">Map to serve on WMS</param>
/// <param name="description">Description of map service</param>
///<param name="pixelSensitivity"> </param>
///<param name="intersectDelegate">Delegate for GetFeatureInfo intersecting, when null, the WMS will default to <see cref="ICanQueryLayer"/> implementation</param>
public static void ParseQueryString(Map map, Capabilities.WmsServiceDescription description, int pixelSensitivity, InterSectDelegate intersectDelegate)
{
_intersectDelegate = intersectDelegate;
if (pixelSensitivity > 0)
_pixelSensitivity = pixelSensitivity;
ParseQueryString(map, description);
}
/// <summary>
/// Generates a WMS 1.3.0 compliant response based on a <see cref="SharpMap.Map"/> and the current HttpRequest.
/// </summary>
/// <remarks>
/// <para>
/// The Web Map Server implementation in SharpMap requires v1.3.0 compatible clients,
/// and support the basic operations "GetCapabilities" and "GetMap"
/// as required by the WMS v1.3.0 specification. SharpMap does not support the optional
/// GetFeatureInfo operation for querying.
/// </para>
/// <example>
/// Creating a WMS server in ASP.NET is very simple using the classes in the SharpMap.Web.Wms namespace.
/// <code lang="C#">
/// void page_load(object o, EventArgs e)
/// {
/// //Get the path of this page
/// string url = (Request.Url.Query.Length>0?Request.Url.AbsoluteUri.Replace(Request.Url.Query,""):Request.Url.AbsoluteUri);
/// SharpMap.Web.Wms.Capabilities.WmsServiceDescription description =
/// new SharpMap.Web.Wms.Capabilities.WmsServiceDescription("Acme Corp. Map Server", url);
///
/// // The following service descriptions below are not strictly required by the WMS specification.
///
/// // Narrative description and keywords providing additional information
/// description.Abstract = "Map Server maintained by Acme Corporation. Contact: webmaster@wmt.acme.com. High-quality maps showing roadrunner nests and possible ambush locations.";
/// description.Keywords.Add("bird");
/// description.Keywords.Add("roadrunner");
/// description.Keywords.Add("ambush");
///
/// //Contact information
/// description.ContactInformation.PersonPrimary.Person = "John Doe";
/// description.ContactInformation.PersonPrimary.Organisation = "Acme Inc";
/// description.ContactInformation.Address.AddressType = "postal";
/// description.ContactInformation.Address.Country = "Neverland";
/// description.ContactInformation.VoiceTelephone = "1-800-WE DO MAPS";
/// //Impose WMS constraints
/// description.MaxWidth = 1000; //Set image request size width
/// description.MaxHeight = 500; //Set image request size height
///
/// //Call method that sets up the map
/// //We just add a dummy-size, since the wms requests will set the image-size
/// SharpMap.Map myMap = MapHelper.InitializeMap(new System.Drawing.Size(1,1));
///
/// //Parse the request and create a response
/// SharpMap.Web.Wms.WmsServer.ParseQueryString(myMap,description);
/// }
/// </code>
/// </example>
/// </remarks>
/// <param name="map">Map to serve on WMS</param>
/// <param name="description">Description of map service</param>
/// <param name="pixelSensitivity"> </param>
///<param name="intersectDelegate">Delegate for GetFeatureInfo intersecting, when null, the WMS will default to <see cref="ICanQueryLayer"/> implementation</param>
/// <param name="context">The context the <see cref="WmsServer"/> is running in.</param>
public static void ParseQueryString(Map map, Capabilities.WmsServiceDescription description, int pixelSensitivity, InterSectDelegate intersectDelegate, HttpContext context)
{
_intersectDelegate = intersectDelegate;
if (pixelSensitivity > 0)
_pixelSensitivity = pixelSensitivity;
ParseQueryString(map, description);
}
/// <summary>
/// Generates a WMS 1.3.0 compliant response based on a <see cref="SharpMap.Map"/> and the current HttpRequest.
/// </summary>
/// <remarks>
/// <para>
/// The Web Map Server implementation in SharpMap requires v1.3.0 compatible clients,
/// and support the basic operations "GetCapabilities" and "GetMap"
/// as required by the WMS v1.3.0 specification. SharpMap does not support the optional
/// GetFeatureInfo operation for querying.
/// </para>
/// <example>
/// Creating a WMS server in ASP.NET is very simple using the classes in the SharpMap.Web.Wms namespace.
/// <code lang="C#">
/// void page_load(object o, EventArgs e)
/// {
/// //Get the path of this page
/// string url = (Request.Url.Query.Length>0?Request.Url.AbsoluteUri.Replace(Request.Url.Query,""):Request.Url.AbsoluteUri);
/// SharpMap.Web.Wms.Capabilities.WmsServiceDescription description =
/// new SharpMap.Web.Wms.Capabilities.WmsServiceDescription("Acme Corp. Map Server", url);
///
/// // The following service descriptions below are not strictly required by the WMS specification.
///
/// // Narrative description and keywords providing additional information
/// description.Abstract = "Map Server maintained by Acme Corporation. Contact: webmaster@wmt.acme.com. High-quality maps showing roadrunner nests and possible ambush locations.";
/// description.Keywords.Add("bird");
/// description.Keywords.Add("roadrunner");
/// description.Keywords.Add("ambush");
///
/// //Contact information
/// description.ContactInformation.PersonPrimary.Person = "John Doe";
/// description.ContactInformation.PersonPrimary.Organisation = "Acme Inc";
/// description.ContactInformation.Address.AddressType = "postal";
/// description.ContactInformation.Address.Country = "Neverland";
/// description.ContactInformation.VoiceTelephone = "1-800-WE DO MAPS";
/// //Impose WMS constraints
/// description.MaxWidth = 1000; //Set image request size width
/// description.MaxHeight = 500; //Set image request size height
///
/// //Call method that sets up the map
/// //We just add a dummy-size, since the wms requests will set the image-size
/// SharpMap.Map myMap = MapHelper.InitializeMap(new System.Drawing.Size(1,1));
///
/// //Parse the request and create a response
/// SharpMap.Web.Wms.WmsServer.ParseQueryString(myMap,description);
/// }
/// </code>
/// </example>
/// </remarks>
/// <param name="map">Map to serve on WMS</param>
/// <param name="description">Description of map service</param>
public static void ParseQueryString(Map map, Capabilities.WmsServiceDescription description)
{
if (HttpContext.Current == null)
throw (new ApplicationException(
"An attempt was made to access the WMS server outside a valid HttpContext"));
ParseQueryString(map, description, HttpContext.Current);
}
/// <summary>
/// Generates a WMS 1.3.0 compliant response based on a <see cref="SharpMap.Map"/> and the current HttpRequest.
/// </summary>
/// <remarks>
/// <para>
/// The Web Map Server implementation in SharpMap requires v1.3.0 compatible clients,
/// and support the basic operations "GetCapabilities" and "GetMap"
/// as required by the WMS v1.3.0 specification. SharpMap does not support the optional
/// GetFeatureInfo operation for querying.
/// </para>
/// <example>
/// Creating a WMS server in ASP.NET is very simple using the classes in the SharpMap.Web.Wms namespace.
/// <code lang="C#">
/// void page_load(object o, EventArgs e)
/// {
/// //Get the path of this page
/// string url = (Request.Url.Query.Length>0?Request.Url.AbsoluteUri.Replace(Request.Url.Query,""):Request.Url.AbsoluteUri);
/// SharpMap.Web.Wms.Capabilities.WmsServiceDescription description =
/// new SharpMap.Web.Wms.Capabilities.WmsServiceDescription("Acme Corp. Map Server", url);
///
/// // The following service descriptions below are not strictly required by the WMS specification.
///
/// // Narrative description and keywords providing additional information
/// description.Abstract = "Map Server maintained by Acme Corporation. Contact: webmaster@wmt.acme.com. High-quality maps showing roadrunner nests and possible ambush locations.";
/// description.Keywords.Add("bird");
/// description.Keywords.Add("roadrunner");
/// description.Keywords.Add("ambush");
///
/// //Contact information
/// description.ContactInformation.PersonPrimary.Person = "John Doe";
/// description.ContactInformation.PersonPrimary.Organisation = "Acme Inc";
/// description.ContactInformation.Address.AddressType = "postal";
/// description.ContactInformation.Address.Country = "Neverland";
/// description.ContactInformation.VoiceTelephone = "1-800-WE DO MAPS";
/// //Impose WMS constraints
/// description.MaxWidth = 1000; //Set image request size width
/// description.MaxHeight = 500; //Set image request size height
///
/// //Call method that sets up the map
/// //We just add a dummy-size, since the wms requests will set the image-size
/// SharpMap.Map myMap = MapHelper.InitializeMap(new System.Drawing.Size(1,1));
///
/// //Parse the request and create a response
/// SharpMap.Web.Wms.WmsServer.ParseQueryString(myMap,description);
/// }
/// </code>
/// </example>
/// </remarks>
/// <param name="map">Map to serve on WMS</param>
/// <param name="description">Description of map service</param>
/// <param name="context">The context the <see cref="WmsServer"/> is running in.</param>
public static void ParseQueryString(Map map, Capabilities.WmsServiceDescription description, HttpContext context)
{
if (_pixelSensitivity ==-1)
_pixelSensitivity = 1;
if (map == null)
throw (new ArgumentException("Map for WMS is null"));
if (map.Layers.Count == 0)
throw (new ArgumentException("Map doesn't contain any layers for WMS service"));
//IgnoreCase value should be set according to the VERSION parameter
//v1.3.0 is case sensitive, but since it causes a lot of problems with several WMS clients, we ignore casing anyway.
const bool ignoreCase = true;
//Check for required parameters
//Request parameter is mandatory
if (context.Request.Params["REQUEST"] == null)
{
WmsException.ThrowWmsException("Required parameter REQUEST not specified", context);
return;
}
//Check if version is supported
if (context.Request.Params["VERSION"] != null)
{
if (String.Compare(context.Request.Params["VERSION"], "1.3.0", ignoreCase) != 0)
{
WmsException.ThrowWmsException("Only version 1.3.0 supported", context);
return;
}
}
else
//Version is mandatory if REQUEST!=GetCapabilities. Check if this is a capabilities request, since VERSION is null
{
if (String.Compare(context.Request.Params["REQUEST"], "GetCapabilities", ignoreCase) != 0)
{
WmsException.ThrowWmsException("VERSION parameter not supplied", context);
return;
}
}
//If Capabilities was requested
if (String.Compare(context.Request.Params["REQUEST"], "GetCapabilities", ignoreCase) == 0)
{
//Service parameter is mandatory for GetCapabilities request
if (context.Request.Params["SERVICE"] == null)
{
WmsException.ThrowWmsException("Required parameter SERVICE not specified", context);
return;
}
if (String.Compare(context.Request.Params["SERVICE"], "WMS", StringComparison.InvariantCulture/*IgnoreCase*/) != 0)
WmsException.ThrowWmsException(
"Invalid service for GetCapabilities Request. Service parameter must be 'WMS'", context);
XmlDocument capabilities = ServerCapabilities.GetCapabilities(map, description);
context.Response.Clear();
context.Response.ContentType = "text/xml";
XmlWriter writer = XmlWriter.Create(context.Response.OutputStream);
capabilities.WriteTo(writer);
writer.Close();
context.Response.Flush();
context.Response.SuppressContent = true;
context.ApplicationInstance.CompleteRequest();
//context.Response.End();
}
else if (String.Compare(context.Request.Params["REQUEST"], "GetFeatureInfo", ignoreCase) == 0) //FeatureInfo Requested
{
if (context.Request.Params["LAYERS"] == null)
{
WmsException.ThrowWmsException("Required parameter LAYERS not specified", context);
return;
}
if (context.Request.Params["STYLES"] == null)
{
WmsException.ThrowWmsException("Required parameter STYLES not specified", context);
return;
}
if (context.Request.Params["CRS"] == null)
{
WmsException.ThrowWmsException("Required parameter CRS not specified", context);
return;
}
if (context.Request.Params["CRS"] != "EPSG:" + map.Layers[0].TargetSRID)
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidCRS, "CRS not supported", context);
return;
}
if (context.Request.Params["BBOX"] == null)
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue,
"Required parameter BBOX not specified", context);
return;
}
if (context.Request.Params["WIDTH"] == null)
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue,
"Required parameter WIDTH not specified", context);
return;
}
if (context.Request.Params["HEIGHT"] == null)
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue,
"Required parameter HEIGHT not specified", context);
return;
}
if (context.Request.Params["FORMAT"] == null)
{
WmsException.ThrowWmsException("Required parameter FORMAT not specified", context);
return;
}
if (context.Request.Params["QUERY_LAYERS"] == null)
{
WmsException.ThrowWmsException("Required parameter QUERY_LAYERS not specified", context);
return;
}
if (context.Request.Params["INFO_FORMAT"] == null)
{
WmsException.ThrowWmsException("Required parameter INFO_FORMAT not specified", context);
return;
}
//parameters X&Y are not part of the 1.3.0 specification, but are included for backwards compatability with 1.1.1 (OpenLayers likes it when used together with wms1.1.1 services)
if (context.Request.Params["X"] == null && context.Request.Params["I"] == null)
{
WmsException.ThrowWmsException("Required parameter I not specified", context);
return;
}
if (context.Request.Params["Y"] == null && context.Request.Params["J"] == null)
{
WmsException.ThrowWmsException("Required parameter J not specified", context);
return;
}
//sets the map size to the size of the client in order to calculate the coordinates of the projection of the client
try
{
map.Size = new Size(Convert.ToInt16(context.Request.Params["WIDTH"]),
Convert.ToInt16(context.Request.Params["HEIGHT"]));
}
catch
{
WmsException.ThrowWmsException("Invalid parameters for HEIGHT or WITDH", context);
return;
}
//sets the boundingbox to the boundingbox of the client in order to calculate the coordinates of the projection of the client
var bbox = ParseBBOX(context.Request.Params["bbox"], map.Layers[0].TargetSRID == 4326);
if (bbox == null)
{
WmsException.ThrowWmsException("Invalid parameter BBOX", context);
return;
}
map.ZoomToBox(bbox);
//sets the point clicked by the client
Single x = 0f, y = 0f;
//tries to set the x to the Param I, if the client send an X, it will try the X, if both fail, exception is thrown
if (context.Request.Params["X"] != null)
try
{
x = Convert.ToSingle(context.Request.Params["X"]);
}
catch
{
WmsException.ThrowWmsException("Invalid parameters for X", context);
return;
}
if (context.Request.Params["I"] != null)
try
{
x = Convert.ToSingle(context.Request.Params["I"]);
}
catch
{
WmsException.ThrowWmsException("Invalid parameters for I", context);
return;
}
//same procedure for J (Y)
if (context.Request.Params["Y"] != null)
try
{
y = Convert.ToSingle(context.Request.Params["Y"]);
}
catch
{
WmsException.ThrowWmsException("Invalid parameters for Y", context);
return;
}
if (context.Request.Params["J"] != null)
try
{
y = Convert.ToSingle(context.Request.Params["J"]);
}
catch
{
WmsException.ThrowWmsException("Invalid parameters for I", context);
return;
}
//var p = map.ImageToWorld(new PointF(x, y));
int fc;
try
{
fc = Convert.ToInt16(context.Request.Params["FEATURE_COUNT"]);
if (fc < 1)
fc = 1;
}
catch
{
fc = 1;
}
//default to text if an invalid format is requested
var infoFormat = context.Request.Params["INFO_FORMAT"];
string cqlFilter = null;
if (context.Request.Params["CQL_FILTER"] != null)
{
cqlFilter = context.Request.Params["CQL_FILTER"];
}
string vstr;
var requestLayers = context.Request.Params["QUERY_LAYERS"].Split(new[] { ',' });
if (String.Compare(infoFormat, "text/json", ignoreCase) == 0)
{
vstr = CreateFeatureInfoGeoJSON(map, requestLayers, x, y, fc, cqlFilter, context);
//string.Empty is the result if a WmsException.ThrowWmsException(...) has been called
if (vstr == string.Empty) return;
context.Response.ContentType = "text/json";
}
else
{
vstr = CreateFeatureInfoPlain(map, requestLayers, x, y, fc, cqlFilter, context);
//string.Empty is the result if a WmsException.ThrowWmsException(...) has been called
if (vstr == string.Empty) return;
context.Response.ContentType = "text/plain";
}
context.Response.Clear();
if (_featureInfoResponseEncoding != null)
{
context.Response.Charset = _featureInfoResponseEncoding.WebName; //"windows-1252";
}
context.Response.Write(vstr);
context.Response.Flush();
context.Response.SuppressContent = true;
context.ApplicationInstance.CompleteRequest();
//context.Response.End();
}
else if (String.Compare(context.Request.Params["REQUEST"], "GetMap", ignoreCase) == 0) //Map requested
{
//Check for required parameters
if (context.Request.Params["LAYERS"] == null)
{
WmsException.ThrowWmsException("Required parameter LAYERS not specified", context);
return;
}
if (context.Request.Params["STYLES"] == null)
{
WmsException.ThrowWmsException("Required parameter STYLES not specified", context);
return;
}
if (context.Request.Params["CRS"] == null)
{
WmsException.ThrowWmsException("Required parameter CRS not specified", context);
return;
}
if (!ConsideredEqual(context.Request.Params["CRS"], $"EPSG:{map.Layers[0].TargetSRID}"))
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidCRS, "CRS not supported",
context);
return;
}
if (context.Request.Params["BBOX"] == null)
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue,
"Required parameter BBOX not specified", context);
return;
}
if (context.Request.Params["WIDTH"] == null)
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue,
"Required parameter WIDTH not specified", context);
return;
}
if (context.Request.Params["HEIGHT"] == null)
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue,
"Required parameter HEIGHT not specified", context);
return;
}
if (context.Request.Params["FORMAT"] == null)
{
WmsException.ThrowWmsException("Required parameter FORMAT not specified", context);
return;
}
//Set background color of map
if (String.Compare(context.Request.Params["TRANSPARENT"], "TRUE", ignoreCase) == 0)
map.BackColor = Color.Transparent;
else if (context.Request.Params["BGCOLOR"] != null)
{
try
{
map.BackColor = ColorTranslator.FromHtml(context.Request.Params["BGCOLOR"]);
}
catch
{
WmsException.ThrowWmsException("Invalid parameter BGCOLOR", context);
return;
}
}
else
map.BackColor = Color.White;
//Get the image format requested
ImageCodecInfo imageEncoder = GetEncoderInfo(context.Request.Params["FORMAT"]);
if (imageEncoder == null)
{
WmsException.ThrowWmsException("Invalid MimeType specified in FORMAT parameter", context);
return;
}
//Parse map size
int width, height;
if (!int.TryParse(context.Request.Params["WIDTH"], out width))
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue,
"Invalid parameter WIDTH", context);
return;
}
if (description.MaxWidth > 0 && width > description.MaxWidth)
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported,
"Parameter WIDTH too large", context);
return;
}
if (!int.TryParse(context.Request.Params["HEIGHT"], out height))
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue,
"Invalid parameter HEIGHT", context);
return;
}
if (description.MaxHeight > 0 && height > description.MaxHeight)
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported,
"Parameter HEIGHT too large", context);
return;
}
map.Size = new Size(width, height);
var bbox = ParseBBOX(context.Request.Params["bbox"], map.Layers[0].TargetSRID == 4326);
if (bbox == null)
{
WmsException.ThrowWmsException("Invalid parameter BBOX", context);
return;
}
map.PixelAspectRatio = (width/(double) height)/(bbox.Width/bbox.Height);
map.Center = bbox.Centre;
map.Zoom = bbox.Width;
//set Styles for layers
//first, if the request == STYLES=, set all the vectorlayers with Themes not null the Theme to the first theme from Themes
if (String.IsNullOrEmpty(context.Request.Params["STYLES"]))
{
foreach (var layer in map.Layers)
{
var vectorLayer = layer as VectorLayer;
if (vectorLayer != null)
{
if (vectorLayer.Themes != null)
{
foreach (var kvp in vectorLayer.Themes)
{
vectorLayer.Theme = kvp.Value;
break;
}
}
}
}
}
else
{
if (!String.IsNullOrEmpty(context.Request.Params["LAYERS"]))
{
var layerz = context.Request.Params["LAYERS"].Split(new[] {','});
var styles = context.Request.Params["STYLES"].Split(new[] {','});
//test whether the lengt of the layers and the styles is the same. WMS spec is unclear on what to do if there is no one-to-one correspondence
if (layerz.Length == styles.Length)
{
foreach (var layer in map.Layers)
{
//is this a vector layer at all
var vectorLayer = layer as VectorLayer;
if (vectorLayer == null) continue;
//does it have several themes applied
//ToDo -> Refactor VectorLayer.Themes to Rendering.Thematics.ThemeList : ITheme
if (vectorLayer.Themes != null && vectorLayer.Themes.Count > 0)
{
for (int i = 0; i < layerz.Length; i++)
{
if (String.Equals(layer.LayerName, layerz[i],
StringComparison.InvariantCultureIgnoreCase))
{
//take default style if style is empty
if (styles[i] == "")
{
foreach (var kvp in vectorLayer.Themes)
{
vectorLayer.Theme = kvp.Value;
break;
}
}
else
{
if (vectorLayer.Themes.ContainsKey(styles[i]))
{
vectorLayer.Theme = vectorLayer.Themes[styles[i]];
}
else
{
WmsException.ThrowWmsException(
WmsException.WmsExceptionCode.StyleNotDefined,
"Style not advertised for this layer", context);
return;
}
}
}
}
}
}
}
}
}
var cqlFilter = context.Request.Params["CQL_FILTER"];
if (!string.IsNullOrEmpty(cqlFilter))
{
foreach (var layer in map.Layers)
{
var vectorLayer = layer as VectorLayer;
if (vectorLayer != null)
{
PrepareDataSourceForCql(vectorLayer.DataSource, cqlFilter);
continue;
}
var labelLayer = layer as LabelLayer;
if (labelLayer != null)
{
PrepareDataSourceForCql(labelLayer.DataSource, cqlFilter);
continue;
}
}
}
//Set layers on/off
var layersString = context.Request.Params["LAYERS"];
if (!string.IsNullOrEmpty(layersString))
//If LAYERS is empty, use default layer on/off settings
{
var layers = layersString.Split(new[] {','});
if (description.LayerLimit > 0)
{
if (layers.Length == 0 && map.Layers.Count > description.LayerLimit ||
layers.Length > description.LayerLimit)
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported,
"Too many layers requested", context);
return;
}
}
foreach (var layer in map.Layers)
layer.Enabled = false;
foreach (var layer in layers)
{
//SharpMap.Layers.ILayer lay = map.Layers.Find(delegate(SharpMap.Layers.ILayer findlay) { return findlay.LayerName == layer; });
ILayer lay = null;
for (int i = 0; i < map.Layers.Count; i++)
if (String.Equals(map.Layers[i].LayerName, layer,
StringComparison.InvariantCultureIgnoreCase))
lay = map.Layers[i];
if (lay == null)
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined,
"Unknown layer '" + layer + "'", context);
return;
}
lay.Enabled = true;
}
}
//Render map
var img = map.GetMap();
//Png can't stream directly. Going through a MemoryStream instead
byte[] buffer;
using (var ms = new MemoryStream())
{
img.Save(ms, imageEncoder, null);
img.Dispose();
buffer = ms.ToArray();
}
context.Response.Clear();
context.Response.ContentType = imageEncoder.MimeType;
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
context.Response.Flush();
context.Response.SuppressContent = true;
context.ApplicationInstance.CompleteRequest();
//context.Response.End();
}
else
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Invalid request", context);
return;
}
}
private static bool ConsideredEqual(string requestedCrs, string mapCrs)
{
if (string.Equals(requestedCrs, mapCrs, StringComparison.InvariantCultureIgnoreCase))
return true;
if (requestedCrs == "EPSG:900913" && mapCrs == "EPSG:3857")
return true;
if (requestedCrs == "EPSG:3857" && mapCrs == "EPSG:900913")
return true;
return false;
}
private static void PrepareDataSourceForCql(IBaseProvider provider, string cqlFilterString)
{
//for layers with a filterprovider
var filterProvider = provider as FilterProvider;
if (filterProvider != null)
{
filterProvider.FilterDelegate = row => CqlFilter(row, cqlFilterString);
return;
}
//for layers with a SQL datasource with a DefinitionQuery property
var piDefinitionQuery = provider.GetType().GetProperty("DefinitionQuery", BindingFlags.Public | BindingFlags.Instance);
if (piDefinitionQuery != null)
{
string dq = piDefinitionQuery.GetValue(provider, null) as string;
if (string.IsNullOrEmpty(dq))
piDefinitionQuery.SetValue(provider, cqlFilterString, null);
else
piDefinitionQuery.SetValue(provider, "(" + dq + ") AND (" + cqlFilterString + ")", null);
}
}
/// <summary>
/// Used for setting up output format of image file
/// </summary>
public static ImageCodecInfo GetEncoderInfo(String mimeType)
{
foreach (var encoder in ImageCodecInfo.GetImageEncoders())
if (encoder.MimeType == mimeType)
return encoder;
return null;
}
/// <summary>
/// Parses a boundingbox string to a boundingbox geometry from the format minx,miny,maxx,maxy. Returns null if the format is invalid
/// </summary>
/// <param name="boundingBox">string representation of a boundingbox</param>
/// <param name="flipXY">Value indicating that x- and y-ordinates should be changed.</param>
/// <returns>Boundingbox or null if invalid parameter</returns>
// ReSharper disable InconsistentNaming
public static Envelope ParseBBOX(string boundingBox, bool flipXY)
// ReSharper restore InconsistentNaming
{
var strVals = boundingBox.Split(new[] { ',' });
if (strVals.Length != 4)
return null;
double minx, miny, maxx, maxy;
if (!double.TryParse(strVals[0], NumberStyles.Float, Map.NumberFormatEnUs, out minx))
return null;
if (!double.TryParse(strVals[2], NumberStyles.Float, Map.NumberFormatEnUs, out maxx))
return null;
if (maxx < minx)
return null;
if (!double.TryParse(strVals[1], NumberStyles.Float, Map.NumberFormatEnUs, out miny))
return null;
if (!double.TryParse(strVals[3], NumberStyles.Float, Map.NumberFormatEnUs, out maxy))
return null;
if (maxy < miny)
return null;
return flipXY
? new Envelope(miny, maxy, minx, maxx)
: new Envelope(minx, maxx, miny, maxy);
}
/// <summary>
/// Gets FeatureInfo as text/plain
/// </summary>
/// <param name="map">The map</param>
/// <param name="requestedLayers">The requested layers</param>
/// <param name="x">The x-ordinate</param>
/// <param name="y">The y-ordinate</param>
/// <param name="featureCount"></param>
/// <param name="cqlFilter">The code query language</param>
/// <param name="context">The <see cref="HttpContext"/> to use. If not specified or <value>null</value>, <see cref="HttpContext.Current"/> is used.</param>
/// <exception cref="InvalidOperationException">Thrown if this function is used without a valid <see cref="HttpContext"/> at hand</exception>
/// <returns>Plain text string with featureinfo results</returns>
public static string CreateFeatureInfoPlain(Map map, string[] requestedLayers, Single x, Single y, int featureCount, string cqlFilter, HttpContext context = null)
{
if (context == null)
context = HttpContext.Current;
if (context == null)
throw new InvalidOperationException("Cannot use CreateFeatureInfoPlain without a valid HttpContext");
var vstr = "GetFeatureInfo results: \n";
foreach (string requestLayer in requestedLayers)
{
bool found = false;
foreach (var mapLayer in map.Layers)
{
if (String.Equals(mapLayer.LayerName, requestLayer,
StringComparison.InvariantCultureIgnoreCase))
{
found = true;
var queryLayer = mapLayer as ICanQueryLayer;
if (queryLayer == null || !queryLayer.IsQueryEnabled) continue;
var queryBoxMinX = x - (_pixelSensitivity);
var queryBoxMinY = y - (_pixelSensitivity);
var queryBoxMaxX = x + (_pixelSensitivity);
var queryBoxMaxY = y + (_pixelSensitivity);
var minXY = map.ImageToWorld(new PointF(queryBoxMinX, queryBoxMinY));
var maxXY = map.ImageToWorld(new PointF(queryBoxMaxX, queryBoxMaxY));
var queryBox = new Envelope(minXY, maxXY);
var fds = new FeatureDataSet();
queryLayer.ExecuteIntersectionQuery(queryBox, fds);
if (_intersectDelegate != null)
{
var tmp = _intersectDelegate(fds.Tables[0], queryBox);
fds.Tables.RemoveAt(0);
fds.Tables.Add(tmp);
}
if (fds.Tables.Count == 0)
{
vstr = vstr + "\nSearch returned no results on layer: " + requestLayer;
}
else
{
if (fds.Tables[0].Rows.Count == 0)
{
vstr = vstr + "\nSearch returned no results on layer: " + requestLayer + " ";
}
else
{
//filter the rows with the CQLFilter if one is provided
if (cqlFilter != null)
{
for (int i = fds.Tables[0].Rows.Count - 1; i >= 0; i--)
{
if (!CqlFilter((FeatureDataRow)fds.Tables[0].Rows[i], cqlFilter))
{
fds.Tables[0].Rows.RemoveAt(i);
}
}
}
//if featurecount < fds...count, select smallest bbox, because most likely to be clicked
vstr = vstr + "\n Layer: '" + requestLayer + "'\n Featureinfo:\n";
int[] keys = new int[fds.Tables[0].Rows.Count];
double[] area = new double[fds.Tables[0].Rows.Count];
for (int l = 0; l < fds.Tables[0].Rows.Count; l++)
{
var fdr = (FeatureDataRow)fds.Tables[0].Rows[l];
area[l] = fdr.Geometry.EnvelopeInternal.Area;
keys[l] = l;
}
Array.Sort(area, keys);
if (fds.Tables[0].Rows.Count < featureCount)
{
featureCount = fds.Tables[0].Rows.Count;
}
for (int k = 0; k < featureCount; k++)
{
for (int j = 0; j < fds.Tables[0].Rows[keys[k]].ItemArray.Length; j++)
{
vstr = vstr + " '" + fds.Tables[0].Rows[keys[k]].ItemArray[j] + "'";
}
if ((k + 1) < featureCount)
vstr = vstr + ",\n";
}
}
}
}
}
if (found == false)
{
WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined,
"Unknown layer '" + requestLayer + "'", context);