Repository navigation
Expand file tree
/
Copy pathSpatialExtensions.cs
More file actions
1332 lines (1172 loc) · 52.3 KB
/
Copy pathSpatialExtensions.cs
File metadata and controls
1332 lines (1172 loc) · 52.3 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 (c) 2019 Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
using System;
using System.Data.SqlTypes;
using System.Linq;
using Microsoft.SqlServer.Types;
using System.Globalization;
using SQLSpatialTools.Sinks.Geometry;
using SQLSpatialTools.Types;
using System.Text.RegularExpressions;
using System.Text;
using System.Collections.Generic;
namespace SQLSpatialTools.Utility
{
public static class SpatialExtensions
{
private const string _geomTypeRegexString = @"^(?<type>\w+)?\s?\(";
private const string _polygonSegmentRegex = @"POLYGON\s*?\((?<segments>.*)\)";
private const string _multipolygonSegmentRegex = @"MULTIPOLYGON\s*?\((?<segments>.*)\)";
private const string _segmentMatchRegex = @"\(.*?\)";
#region OGC Type Checks
/// <summary>
/// Check if Geometry is of type point,
/// it returns true, if the geometry is of type point
/// Instead of checking the STGeometryType directly, this utility method parses the points of the geometry, which make sure it returns true, even if the geometry contains invalid co-ordinates
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns></returns>
public static bool CheckGeomPoint(this SqlGeometry sqlGeometry)
{
try
{
return GetPoint(sqlGeometry).STGeometryType().Compare(OGCType.Point.GetString());
}
catch (SqlNullValueException)
{
return false;
}
}
/// <summary>
/// Check if Geometry is Point
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns></returns>
public static bool IsPoint(this SqlGeometry sqlGeometry)
{
return sqlGeometry.STGeometryType().Compare(OGCType.Point.GetString());
}
/// <summary>
/// Check if Geometry is Point; Works on invalid types too.
/// </summary>
/// <param name="wktGeometry">Geometry in WKT format</param>
/// <returns></returns>
public static bool IsPoint(this string wktGeometry)
{
return Regex.IsMatch(wktGeometry, @"^POINT\s*\(.*\)", RegexOptions.IgnoreCase);
}
/// <summary>
/// Check if Geography type is Point
/// </summary>
/// <param name="sqlGeography">SQL Geography</param>
/// <returns></returns>
public static bool IsPoint(this SqlGeography sqlGeography)
{
return sqlGeography.STGeometryType().Compare(OGCType.Point.GetString());
}
/// <summary>
/// Check if Geometry is LineString
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns>true; false</returns>
public static bool IsLineString(this SqlGeometry sqlGeometry)
{
return sqlGeometry.STGeometryType().Compare(OGCType.LineString.GetString());
}
/// <summary>
/// Check if Geometry is CircularString
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns>true; false</returns>
public static bool IsCircularString(this SqlGeometry sqlGeometry)
{
return sqlGeometry.STGeometryType().Compare(OGCType.CircularString.GetString());
}
/// <summary>
/// Check if Geometry is CompoundCurve
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns>true; false</returns>
public static bool IsCompoundCurve(this SqlGeometry sqlGeometry)
{
return sqlGeometry.STGeometryType().Compare(OGCType.CompoundCurve.GetString());
}
/// <summary>
/// Check if Geometry is Polygon
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns>true; false</returns>
public static bool IsPolygon(this SqlGeometry sqlGeometry)
{
return sqlGeometry.STGeometryType().Compare(OGCType.Polygon.GetString());
}
/// <summary>
/// Check if Geometry is Polygon
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns>true; false</returns>
public static bool IsPolygon(this SqlGeometry sqlGeometry, bool checkValid = true)
{
if (checkValid)
return sqlGeometry.IsPolygon();
return GetGeomText(sqlGeometry.ToString()).Equals("POLYGON");
}
/// <summary>
/// Check if Geometry is CurvePolygon
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns>true; false</returns>
public static bool IsCurvePolygon(this SqlGeometry sqlGeometry)
{
return sqlGeometry.STGeometryType().Compare(OGCType.CurvePolygon.GetString());
}
/// <summary>
/// Check if Geometry is CurvePolygon
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns>true; false</returns>
public static bool IsCurvePolygon(this SqlGeometry sqlGeometry, bool checkValid = true)
{
if (checkValid)
return sqlGeometry.IsCurvePolygon();
return GetGeomText(sqlGeometry.ToString()).Equals("CURVEPOLYGON");
}
/// <summary>
/// Check if Geometry is GeometryCollection
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns>true; false</returns>
public static bool IsGeometryCollection(this SqlGeometry sqlGeometry)
{
return sqlGeometry.STGeometryType().Compare(OGCType.GeometryCollection.GetString());
}
/// <summary>
/// Check if Geometry is MultiPoint
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns>true; false</returns>
public static bool IsMultiPoint(this SqlGeometry sqlGeometry)
{
return sqlGeometry.STGeometryType().Compare(OGCType.MultiPoint.GetString());
}
/// <summary>
/// Check if Geometry is MultiLineString
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns>true; false</returns>
public static bool IsMultiLineString(this SqlGeometry sqlGeometry)
{
return sqlGeometry.STGeometryType().Compare(OGCType.MultiLineString.GetString());
}
/// <summary>
/// Check if Geometry is MultiPolygon
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns>true; false</returns>
public static bool IsMultiPolygon(this SqlGeometry sqlGeometry)
{
return sqlGeometry.STGeometryType().Compare(OGCType.MultiPolygon.GetString());
}
/// <summary>
/// Check if Geometry is MultiPolygon
/// </summary>
/// <param name="sqlGeometry"></param>
/// <returns>true; false</returns>
public static bool IsMultiPolygon(this SqlGeometry sqlGeometry, bool checkValid = true)
{
if (checkValid)
return sqlGeometry.IsMultiPolygon();
return GetGeomText(sqlGeometry.ToString()).Equals("MULTIPOLYGON");
}
/// <summary>
/// Get geometry type.
/// </summary>
/// <param name="geomText">Geometry text</param>
/// <returns>Geometry type</returns>
public static string GetGeomText(this string geomText)
{
var match = Regex.Match(geomText, _geomTypeRegexString);
return match.Groups["type"].Value.ToUpper();
}
#endregion
#region Measures Tolerance
/// <summary>
/// Get start point measure of Geometry
/// </summary>
/// <param name="sqlGeometry">Input Geometry</param>
/// <returns></returns>
public static double GetStartPointMeasure(this SqlGeometry sqlGeometry)
{
return sqlGeometry.STStartPoint().M.IsNull
? 0
: sqlGeometry.STStartPoint().M.Value;
}
/// <summary>
/// Get end point measure of Geometry
/// </summary>
/// <param name="sqlGeometry">Input Geometry</param>
/// <returns></returns>
public static double GetEndPointMeasure(this SqlGeometry sqlGeometry)
{
return sqlGeometry.STEndPoint().M.IsNull
? sqlGeometry.STLength().Value
: sqlGeometry.STEndPoint().M.Value;
}
/// <summary>
/// Determines whether the geometry segment is not null or empty.
/// </summary>
/// <param name="sqlGeometry">The SQL geometry.</param>
/// <returns>
/// <c>true</c> if [is not null or empty] [the specified SQL geometry]; otherwise, <c>false</c>.
/// </returns>
public static bool IsNotNullOrEmpty(this SqlGeometry sqlGeometry)
{
return !sqlGeometry.IsNullOrEmpty();
}
/// <summary>
/// Determines whether the geometry segment is null or empty.
/// </summary>
/// <param name="sqlGeometry">The SQL geometry.</param>
/// <returns>
/// <c>true</c> if [is null or empty] [the specified SQL geometry]; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmpty(this SqlGeometry sqlGeometry)
{
if (sqlGeometry == null)
return true;
return (bool)(sqlGeometry.IsNull || sqlGeometry.STIsEmpty());
}
/// <summary>
/// for checking whether geometry measure is increasing or decreasing
/// </summary>
/// <param name="geometry"></param>
/// <returns></returns>
public static bool STHasLinearMeasure(this SqlGeometry geometry)
{
if (geometry.IsNullOrEmpty() || !geometry.STIsValid())
return false;
var numPoints = geometry.STNumPoints();
var measureProgress = geometry.STLinearMeasureProgress();
var previousM = 0.0;
for (var iterator = 1; iterator <= numPoints; iterator++)
{
var currentPoint = geometry.STPointN(iterator);
if (!currentPoint.HasM)
return false;
if (iterator == 1)
{
previousM = currentPoint.M.Value;
continue;
}
switch (measureProgress)
{
case LinearMeasureProgress.Increasing when previousM > currentPoint.M:
case LinearMeasureProgress.Decreasing when previousM < currentPoint.M:
return false;
default:
previousM = currentPoint.M.Value;
break;
}
}
return true;
}
/// <summary>
/// To check whether start measure value is equal to End Measure value
/// </summary>
/// <param name="geometry"></param>
/// <returns>equal measure value</returns>
public static bool STHasEqualStartAndEndMeasure(this SqlGeometry geometry)
{
return Math.Abs(geometry.GetStartPointMeasure() - geometry.GetEndPointMeasure()) < 0.0000001;
}
/// <summary>
/// Get the linear progression of the geometry based on measure value; whether increasing or decreasing.
/// </summary>
/// <param name="geometry">The input SqlGeometry.</param>
/// <returns>Increasing or Decreasing</returns>
public static LinearMeasureProgress STLinearMeasureProgress(this SqlGeometry geometry)
{
if (geometry.IsNullOrEmpty())
return LinearMeasureProgress.None;
if (geometry.IsPoint())
return LinearMeasureProgress.Increasing;
var startPoint = geometry.STStartPoint();
var endPoint = geometry.STEndPoint();
if (!geometry.STStartPoint().HasM || !geometry.STEndPoint().HasM)
return LinearMeasureProgress.None;
return (endPoint.M - startPoint.M > 0 ? LinearMeasureProgress.Increasing : LinearMeasureProgress.Decreasing);
}
/// <summary>
/// Gets the distance between two x,y co-ordinates.
/// </summary>
/// <param name="x1">The x1.</param>
/// <param name="y1">The y1.</param>
/// <param name="x2">The x2.</param>
/// <param name="y2">The y2.</param>
/// <returns></returns>
public static double GetDistance(double x1, double y1, double x2, double y2)
{
var xCoordinateDiff = Math.Pow(Math.Abs(x2 - x1), 2);
var yCoordinateDiff = Math.Pow(Math.Abs(y2 - y1), 2);
return Math.Sqrt(xCoordinateDiff + yCoordinateDiff);
}
/// <summary>
/// Determines whether the specified distance is within tolerance.
/// </summary>
/// <param name="distance">The distance.</param>
/// <param name="tolerance">The tolerance.</param>
/// <returns>
/// <c>true</c> if the specified distance is tolerable; otherwise, <c>false</c>.
/// </returns>
public static bool IsTolerable(this double distance, double tolerance)
{
var digitToCompare = distance;
var decDigits = tolerance.GetPrecisionLength();
if (decDigits > 0)
digitToCompare = Math.Round(distance, decDigits);
return digitToCompare <= tolerance;
}
/// <summary>
/// Gets the precision length
/// </summary>
/// <param name="decimalDigit">The decimal digit.</param>
/// <returns></returns>
public static int GetPrecisionLength(this double decimalDigit)
{
var decimalStr = decimalDigit.ToString(CultureInfo.CurrentCulture);
var decimalIndex = decimalStr.IndexOf(".", StringComparison.CurrentCulture);
return decimalIndex > 0 ? decimalStr.Substring(decimalIndex).Length : 0;
}
/// <summary>
/// Determines whether the x y distance between start and point is tolerable.
/// </summary>
/// <param name="startPoint">The start point.</param>
/// <param name="endPoint">The end point.</param>
/// <param name="tolerance">The tolerance.</param>
/// <returns>
/// <c>true</c> if the specified start and end point distance is tolerable; otherwise, <c>false</c>.
/// </returns>
public static bool IsWithinTolerance(this SqlGeometry startPoint, SqlGeometry endPoint, double tolerance)
{
return IsXYWithinRange(startPoint, endPoint, tolerance);
}
/// <summary>
/// Determines whether the x y distance between 2 x,y points is within tolerance
/// </summary>
/// <param name="x1">The x1.</param>
/// <param name="y1">The y1.</param>
/// <param name="x2">The x2.</param>
/// <param name="y2">The y2.</param>
/// <param name="tolerance">The tolerance.</param>
/// <returns>
/// <c>true</c> if distance between 2 points are within tolerance; otherwise, <c>false</c>.
/// </returns>
public static bool IsWithinTolerance(double x1, double y1, double x2, double y2, double tolerance)
{
return IsXYWithinRange(x1, y1, x2, y2, tolerance);
}
#endregion
#region Range Validations
/// <summary>
/// Check whether the measure falls withing the start and end measure.
/// </summary>
/// <param name="currentMeasure"></param>
/// <param name="startMeasure"></param>
/// <param name="endMeasure"></param>
/// <returns></returns>
public static bool IsWithinRange(this double? currentMeasure, double? startMeasure, double? endMeasure)
{
if (currentMeasure.HasValue && startMeasure.HasValue && endMeasure.HasValue)
return IsWithinRange(currentMeasure.Value, startMeasure.Value, endMeasure.Value);
return false;
}
/// <summary>
/// Check whether the measure falls withing the start and end measure.
/// </summary>
/// <param name="currentMeasure"></param>
/// <param name="startMeasure"></param>
/// <param name="endMeasure"></param>
/// <returns></returns>
public static bool IsWithinRange(this double currentMeasure, double startMeasure, double endMeasure)
{
return (
// if line segment measure is increasing start ----> end
(currentMeasure >= startMeasure && currentMeasure <= endMeasure)
||
// if line segment measure is increasing start <---- end
(currentMeasure >= endMeasure && currentMeasure <= startMeasure)
);
}
/// <summary>
/// Check whether the measure falls withing the start and end measure of geometry.
/// </summary>
/// <param name="currentMeasure"></param>
/// <param name="sqlGeometry"></param>
/// <returns></returns>
public static bool IsWithinRange(this double currentMeasure, SqlGeometry sqlGeometry)
{
var startMeasure = sqlGeometry.GetStartPointMeasure();
var endMeasure = sqlGeometry.GetEndPointMeasure();
return IsWithinRange(currentMeasure, startMeasure, endMeasure);
}
/// <summary>
/// Check whether the measure falls between start and end geometry points
/// </summary>
/// <param name="currentMeasure"></param>
/// <param name="startPoint"></param>
/// <param name="endPoint"></param>
/// <returns></returns>
public static bool IsWithinRange(this double currentMeasure, SqlGeometry startPoint, SqlGeometry endPoint)
{
var startMeasure = startPoint.GetStartPointMeasure();
var endMeasure = endPoint.GetEndPointMeasure();
return IsWithinRange(currentMeasure, startMeasure, endMeasure);
}
/// <summary>
/// Checks whether difference of X and Y point between source and point to compare is within tolerable range
/// </summary>
/// <param name="sourcePoint"></param>
/// <param name="pointToCompare"></param>
/// <param name="tolerance"></param>
/// <returns></returns>
public static bool IsXYWithinRange(this SqlGeometry sourcePoint, SqlGeometry pointToCompare, double tolerance = 0.0F)
{
return Math.Abs(sourcePoint.STX.Value - pointToCompare.STX.Value) <= tolerance &&
Math.Abs(sourcePoint.STY.Value - pointToCompare.STY.Value) <= tolerance;
}
/// <summary>
/// Determines whether [is x y within range] [the specified x1].
/// </summary>
/// <param name="x1">The x1.</param>
/// <param name="y1">The y1.</param>
/// <param name="x2">The x2.</param>
/// <param name="y2">The y2.</param>
/// <param name="tolerance">The tolerance.</param>
/// <returns>
/// <c>true</c> if [is x y within range] [the specified x1]; otherwise, <c>false</c>.
/// </returns>
public static bool IsXYWithinRange(double x1, double y1, double x2, double y2, double tolerance = 0.0F)
{
return Math.Abs(x1 - x2) <= tolerance &&
Math.Abs(y1 - y2) <= tolerance;
}
/// <summary>
/// Determines whether the input start or end measure matches the start or end point measure of geometry.
/// </summary>
/// <param name="geomStartMeasure">The geom start measure.</param>
/// <param name="geomEndMeasure">The geom end measure.</param>
/// <param name="inputStartMeasure">The input start measure.</param>
/// <param name="inputEndMeasure">The input end measure.</param>
/// <returns>
/// <c>true</c> if input measure matches end or start point measure of geometry; otherwise, <c>false</c>.
/// </returns>
public static bool IsExtremeMeasuresMatch(double geomStartMeasure, double geomEndMeasure, double inputStartMeasure, double inputEndMeasure)
{
var inputStartCheck1 = inputStartMeasure.Equals(geomStartMeasure);
var inputStartCheck2 = inputStartMeasure.Equals(geomEndMeasure);
var inputEndCheck1 = inputEndMeasure.Equals(geomStartMeasure);
var inputEndCheck2 = inputEndMeasure.Equals(geomEndMeasure);
return (inputStartCheck1 || inputStartCheck2) || (inputEndCheck1 || inputEndCheck2);
}
/// <summary>
/// <para>
/// Get offset measure between the two geometry.
/// </para>
/// <para>Subtracts end measure of first geometry against the first measure of second geometry.
/// </para>
/// </summary>
/// <param name="sqlGeometry1">First Geometry</param>
/// <param name="sqlGeometry2">Second Geometry</param>
/// <returns>Difference in measure</returns>
public static double? GetOffset(this SqlGeometry sqlGeometry1, SqlGeometry sqlGeometry2)
{
return sqlGeometry1.GetEndPointMeasure() - sqlGeometry2.GetStartPointMeasure();
}
/// <summary>
/// Get offset measure between the two point geometry.
/// Subtracts end measure of first point and second point.
/// </summary>
/// <param name="point1">First Point</param>
/// <param name="point2">Second Point</param>
/// <returns>Difference in measure</returns>
public static double GetPointOffset(this SqlGeometry point1, SqlGeometry point2)
{
return point1.M.Value - point2.M.Value;
}
#endregion
#region Sql Types Comparison
/// <summary>
/// Compares sql string for equality.
/// </summary>
/// <param name="sqlString">SQL string</param>
/// <param name="targetString">Target OGC type string to compare</param>
/// <returns></returns>
public static bool Compare(this SqlString sqlString, string targetString)
{
if (string.IsNullOrEmpty(targetString))
return false;
var convertString = sqlString.ToString();
return !string.IsNullOrEmpty(convertString) && convertString.ToLowerInvariant().Equals(targetString.ToLowerInvariant(), StringComparison.CurrentCulture);
}
#endregion
#region Enum Attribute Extension
/// <summary>
/// Will get the string value for a given enums value, this will
/// only work if you assign the StringValue attribute to
/// the items in your enum.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string GetString(this OGCType value)
{
return GetStringAttributeValue(value);
}
/// <summary>
/// Will get the string value for a given enums value, this will
/// only work if you assign the StringValue attribute to
/// the items in your enum.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string GetString(this DimensionalInfo value)
{
return GetStringAttributeValue(value);
}
/// <summary>
/// Will get the string value for a given enums value, this will
/// only work if you assign the StringValue attribute to
/// the items in your enum.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string GetString(this LRSErrorCodes value)
{
return GetStringAttributeValue(value);
}
/// <summary>
/// Gets the string attribute value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns></returns>
private static string GetStringAttributeValue<T>(this T value)
{
// Get the type
var type = value.GetType();
// Get field info for this type
var fieldInfo = type.GetField(value.ToString());
// Get the string value attributes
// Return the first if there was a match.
return fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false)
is StringValueAttribute[] attributes && attributes.Length > 0 ? attributes[0].StringValue : null;
}
/// <summary>
/// Get the int value of enum
/// </summary>
/// <param name="linearMeasureProgress">The linear measure progress.</param>
/// <returns>Returns the implicit integer value of respective enum</returns>
public static short Value(this LinearMeasureProgress linearMeasureProgress)
{
return (short)linearMeasureProgress;
}
/// <summary>
/// Get the string value for the specified LRS Error Code.
/// </summary>
/// <param name="lrsErrorCodes">The LRS error codes.</param>
/// <returns>String Value of LRS Error Code.</returns>
public static string Value(this LRSErrorCodes lrsErrorCodes)
{
return lrsErrorCodes == LRSErrorCodes.ValidLRS ? "TRUE" : ((short)lrsErrorCodes).ToString(CultureInfo.CurrentCulture);
}
#endregion
#region Exception Handling
/// <summary>
/// Throws Argument Exception if the element index to be extracted is greater than the input geometry.
/// </summary>
internal static void ThrowInvalidElementIndex()
{
throw new ArgumentException(ErrorMessage.InvalidElementIndex);
}
/// <summary>
/// Throws Argument Exception if the sub-element index to be extracted is greater than the input geometry.
/// </summary>
internal static void ThrowInvalidSubElementIndex()
{
throw new ArgumentException(ErrorMessage.InvalidSubElementIndex);
}
/// <summary>
/// Throws Argument Exception if the geometry is not valid
/// </summary>
internal static void ThrowIfInvalidGeometry()
{
throw new ArgumentException(ErrorMessage.InvalidGeometry);
}
/// <summary>
/// Throw if input geometry is not a LRS Geometry collection POINT, LINESTRING or MULTILINESTRING.
/// </summary>
/// <param name="sqlGeometries">Input Sql Geometry</param>
internal static void ThrowIfNotLRSType(params SqlGeometry[] sqlGeometries)
{
if (sqlGeometries.Any(geom => !geom.IsLRSType()))
throw new ArgumentException(ErrorMessage.LRSCompatible);
}
/// <summary>
/// Throw if input geometry is not a Point.
/// </summary>
/// <param name="sqlGeometry">Input Sql Geometry</param>
/// <param name="sqlGeometries">Sql Geometries</param>
internal static void ThrowIfNotPoint(SqlGeometry sqlGeometry, params SqlGeometry[] sqlGeometries)
{
var geometries = (new[] { sqlGeometry }).Concat(sqlGeometries);
if (geometries.Any(geom => !geom.IsOfSupportedTypes(OpenGisGeometryType.Point)))
throw new ArgumentException(ErrorMessage.PointCompatible);
}
/// <summary>
/// Throw if input geometry is not a line string.
/// </summary>
/// <param name="sqlGeometry">Input Sql Geometry</param>
/// <param name="sqlGeometries">Sql Geometries</param>
internal static void ThrowIfNotLine(SqlGeometry sqlGeometry, params SqlGeometry[] sqlGeometries)
{
var geometries = (new[] { sqlGeometry }).Concat(sqlGeometries);
if (geometries.Any(geom => !geom.IsOfSupportedTypes(OpenGisGeometryType.LineString)))
throw new ArgumentException(ErrorMessage.LineStringCompatible);
}
/// <summary>
/// Throw if input geometry is not a line string or multiline string.
/// </summary>
/// <param name="sqlGeometry">Input Sql Geometry</param>
/// <param name="sqlGeometries">Sql Geometries</param>
internal static void ThrowIfNotLineOrMultiLine(SqlGeometry sqlGeometry, params SqlGeometry[] sqlGeometries)
{
var geometries = (new[] { sqlGeometry }).Concat(sqlGeometries);
if (geometries.Any(geom => !geom.IsOfSupportedTypes(OpenGisGeometryType.LineString, OpenGisGeometryType.MultiLineString)))
throw new ArgumentException(ErrorMessage.LineOrMultiLineStringCompatible);
}
/// <summary>
/// Throw if SRIDs of two geometries doesn't match.
/// </summary>
/// <param name="sourceGeometry">Source Sql Geometry</param>
/// <param name="targetGeometry">Target Sql Geometry</param>
internal static void ThrowIfSRIDDoesNotMatch(SqlGeometry sourceGeometry, SqlGeometry targetGeometry)
{
if (!sourceGeometry.STSrid.Equals(targetGeometry.STSrid))
throw new ArgumentException(ErrorMessage.SRIDCompatible);
}
/// <summary>
/// Throw if measure is not withing the range of two geometries.
/// </summary>
/// <param name="measure">Measure</param>
/// <param name="startPoint">Start Point Sql Geometry</param>
/// <param name="endPoint">End Point Sql Geometry</param>
internal static void ThrowIfMeasureIsNotInRange(double measure, SqlGeometry startPoint, SqlGeometry endPoint)
{
if (!measure.IsWithinRange(startPoint, endPoint))
throw new ArgumentException(ErrorMessage.MeasureRange);
}
/// <summary>
/// Throw if measure is not linear for LRS System.
/// </summary>
/// <param name="inputGeometry">SQL Geometry</param>
internal static void ThrowIfMeasureNotLinear(SqlGeometry inputGeometry)
{
if (!inputGeometry.STHasLinearMeasure())
throw new ArgumentException(ErrorMessage.LinearMeasureRange);
}
/// <summary>
/// Throw if measure is not withing the range of two geometries.
/// </summary>
/// <param name="measure">Measure</param>
/// <param name="sqlGeometry">Input Sql Geometry</param>
internal static void ThrowIfMeasureIsNotInRange(double measure, SqlGeometry sqlGeometry)
{
if (!measure.IsWithinRange(sqlGeometry))
ThrowLRSError(LRSErrorCodes.InvalidLRSMeasure);
}
/// <summary>
/// Check if the geometry collection is of POINT, LINESTRING, MULTILINESTRING.
/// </summary>
/// <param name="geometry"></param>
/// <returns></returns>
public static bool IsLRSType(this SqlGeometry geometry)
{
return geometry.IsOfSupportedTypes(OpenGisGeometryType.Point, OpenGisGeometryType.LineString, OpenGisGeometryType.MultiLineString);
}
/// <summary>
/// Check if the input geometry is of the supported specified type
/// </summary>
/// <param name="geometry"></param>
/// <param name="supportedType"></param>
/// <param name="additionalSupportedTypes"></param>
/// <returns></returns>
public static bool IsOfSupportedTypes(this SqlGeometry geometry, OpenGisGeometryType supportedType, params OpenGisGeometryType[] additionalSupportedTypes)
{
var geomSink = new GISTypeCheckGeometrySink((new[] { supportedType }).Concat(additionalSupportedTypes).ToArray());
geometry.Populate(geomSink);
return geomSink.IsCompatible();
}
/// <summary>
/// Throws ArgumentException based on message format and parameters
/// </summary>
/// <param name="messageFormat">Message format</param>
/// <param name="args">Arguments to be appended with format</param>
public static void ThrowException(string messageFormat, params object[] args)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, messageFormat, args));
}
/// <summary>
/// Throws LRS Error based on error code.
/// </summary>
/// <param name="lrsErrorCode">LRS Error Code</param>
public static void ThrowLRSError(LRSErrorCodes lrsErrorCode)
{
var message = string.Format(CultureInfo.CurrentCulture, "{0} - {1}", (int)lrsErrorCode, lrsErrorCode.GetString());
throw new ArgumentException(message);
}
#endregion
#region Dimensions
/// <summary>
/// Returns true if the input type is in the list of supported types.
/// </summary>
/// <param name="type"></param>
/// <param name="geometryTypes"></param>
/// <returns></returns>
public static bool Contains(this OpenGisGeometryType type, OpenGisGeometryType[] geometryTypes)
{
foreach (var geom in geometryTypes)
{
if (type.Equals(geom))
return true;
}
return false;
}
/// <summary>
/// Checks if both the segments are in same direction. either increasing or decrease based on measures.
/// </summary>
/// <param name="geometrySegment1">Geometry 1</param>
/// <param name="geometrySegment2">Geometry 2</param>
/// <returns>Returns true if both Geom Segments are in same direction</returns>
public static bool STSameDirection(this SqlGeometry geometrySegment1, SqlGeometry geometrySegment2)
{
return geometrySegment1.STLinearMeasureProgress() == geometrySegment2.STLinearMeasureProgress();
}
/// <summary>
/// Gets the dimension info of input geometry
/// </summary>
/// <param name="sqlGeometry">The SQL geometry.</param>
/// <returns>Dimensional Info 2D, 2DM, 3D or 3DM</returns>
public static DimensionalInfo STGetDimension(this SqlGeometry sqlGeometry)
{
// return object
var dmDimensionalInfo = DimensionalInfo.None;
// STNumPoint can be performed only on valid geometries.
if (!sqlGeometry.STIsValid() || sqlGeometry.STNumPoints() <= 0)
{
dmDimensionalInfo = DimensionalInfo.None;
}
else
{
var firstPoint = sqlGeometry.STPointN(1);
if (firstPoint.Z.IsNull && firstPoint.M.IsNull)
dmDimensionalInfo = DimensionalInfo.Dim2D;
else if (firstPoint.Z.IsNull && !firstPoint.M.IsNull)
dmDimensionalInfo = DimensionalInfo.Dim2DWithMeasure;
else if (!firstPoint.Z.IsNull && firstPoint.M.IsNull)
dmDimensionalInfo = DimensionalInfo.Dim3D;
else if (!firstPoint.Z.IsNull && !firstPoint.M.IsNull)
dmDimensionalInfo = DimensionalInfo.Dim3DWithMeasure;
}
return dmDimensionalInfo;
}
// <summary>
/// Gets the dimension info of input geometry
/// Here no way to infer 2D with measure value
/// </summary>
/// <param name="wktGeometry">The SQL geometry in wkt format.</param>
/// <returns>Dimensional Info 2D, 2DM, 3D or 3DM</returns>
public static DimensionalInfo GetDimension(this string wktGeometry)
{
if (string.IsNullOrEmpty(wktGeometry))
return DimensionalInfo.None;
var match = Regex.Match(wktGeometry, @"\w+.*?\((?<content>.*?)[\,\)]");
if(match.Success)
{
var dimensions = match.Groups["content"].Value.Split(' ');
switch(dimensions.Count())
{
case 2:
return DimensionalInfo.Dim2D;
case 3:
return DimensionalInfo.Dim3D;
case 4:
return DimensionalInfo.Dim3DWithMeasure;
default:
return DimensionalInfo.None;
}
}
return DimensionalInfo.None;
}
/// <summary>
/// Validate and convert to LRS dimension
/// </summary>
/// <param name="sqlGeometry">Input SQL Geometry</param>
internal static void ValidateLRSDimensions(ref SqlGeometry sqlGeometry)
{
var dimension = sqlGeometry.STGetDimension();
switch (dimension)
{
case DimensionalInfo.Dim3DWithMeasure:
case DimensionalInfo.Dim2DWithMeasure:
return;
// if dimension is of x, y and z
// need to convert third z co-ordinate to M for LRS
case DimensionalInfo.Dim3D:
sqlGeometry = sqlGeometry.ConvertTo2DimensionWithMeasure();
break;
case DimensionalInfo.Dim2D:
throw new ArgumentException(ErrorMessage.TwoDimensionalCoordinates);
// skip for invalid types where Dimensional information can't be inferred
default:
return;
}
}
#endregion
#region Others
/// <summary>
/// Checks if two double values are equal.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns></returns>
public static bool EqualsTo(this double left, double right)
{
return Math.Abs(left - right) < double.Epsilon;
}
/// <summary>
/// Checks if two double values are equal.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns></returns>
public static bool EqualsTo(this double? left, double right)
{
var leftValue = left ?? 0.0;
return EqualsTo(leftValue, right);
}
/// <summary>
/// Checks if two double values are equal.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns></returns>
public static bool EqualsTo(this double left, double? right)
{
var rightValue = right ?? 0.0;
return EqualsTo(left, rightValue);
}
/// <summary>
/// Checks if two double values are equal.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns></returns>
public static bool EqualsTo(this double? left, double? right)
{
var leftValue = left ?? 0.0;
var rightValue = right ?? 0.0;
return EqualsTo(leftValue, rightValue);
}
/// <summary>
/// Checks if two double values are not equal.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns></returns>
public static bool NotEqualsTo(this double left, double right)
{
return !EqualsTo(left, right);