-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathGeometricNetworkUtility.cs
1793 lines (1591 loc) · 86 KB
/
GeometricNetworkUtility.cs
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 file="GeometricNetworkUtility.cs" company="Studio A&T s.r.l.">
// Copyright (c) Studio A&T s.r.l. All rights reserved.
// </copyright>
// <author>Nicogis</author>
//-----------------------------------------------------------------------
namespace Studioat.ArcGis.Soe.Rest
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.NetworkAnalysis;
using ESRI.ArcGIS.Server;
using ESRI.ArcGIS.SOESupport;
/// <summary>
/// Class SOE GeometryNetworkUtility
/// </summary>
[ComVisible(true)]
[Guid("3de75f06-31f0-4fa2-8322-df8965bb3d68")]
[ClassInterface(ClassInterfaceType.None)]
[ServerObjectExtension("MapServer",
AllCapabilities = "Trace network,Isolate valve,Position along",
DefaultCapabilities = "Trace network,Isolate valve,Position along",
Description = "Geometric Network Utility",
DisplayName = "Geometric Network Utility",
Properties = "",
SupportsREST = true,
SupportsSOAP = false)]
[SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1306:FieldNamesMustBeginWithLowerCaseLetter", Justification = "Warning FxCop - Error Code ESRI - Capabilities")]
[SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Warning FxCop - Error Code ESRI - pSOH")]
[SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes", Justification = "-")]
public class GeometricNetworkUtility : IServerObjectExtension, IObjectConstruct, IRESTRequestHandler
{
/// <summary>
/// name of soe
/// </summary>
private string soeName;
/// <summary>
/// object serverObjectHelper
/// </summary>
private IServerObjectHelper serverObjectHelper;
/// <summary>
/// object logger
/// </summary>
private ServerLogger logger;
/// <summary>
/// request Handler
/// </summary>
private IRESTRequestHandler requestHandler;
/// <summary>
/// List of GeometricNetworkInfo
/// </summary>
private List<GeometricNetworkInfo> geometricNetworkInfos;
/// <summary>
/// separator string for Weight Ranges
/// </summary>
private string separatorWeightRanges;
/// <summary>
/// Initializes a new instance of the GeometricNetworkUtility class.
/// </summary>
public GeometricNetworkUtility()
{
this.soeName = this.GetType().Name;
this.logger = new ServerLogger();
this.requestHandler = new SoeRestImpl(this.soeName, this.CreateRestSchema()) as IRESTRequestHandler;
}
#region IServerObjectExtension Members
/// <summary>
/// Event Init SOE
/// </summary>
/// <param name="pSOH">object IServerObjectHelper</param>
public void Init(IServerObjectHelper pSOH)
{
this.serverObjectHelper = pSOH;
}
/// <summary>
/// Event Shutdown SOE
/// </summary>
public void Shutdown()
{
}
#endregion
#region IObjectConstruct Members
/// <summary>
/// Event Construct SOE
/// </summary>
/// <param name="props">properties of SOE</param>
public void Construct(IPropertySet props)
{
AutoTimer timer = new AutoTimer();
this.logger.LogMessage(ServerLogger.msgType.infoSimple, "Construct", -1, this.soeName + " Construct has started.");
this.GetGeometricNetworkInfos();
NumberFormatInfo numericFormatInfo = CultureInfo.CurrentCulture.NumberFormat;
this.separatorWeightRanges = (numericFormatInfo.NumberDecimalSeparator == ".") ? "," : ";";
this.logger.LogMessage(ServerLogger.msgType.infoSimple, "Construct", -1, timer.Elapsed, this.soeName + " Construct has completed.");
}
#endregion
#region IRESTRequestHandler Members
/// <summary>
/// Get schema of SOE
/// </summary>
/// <returns>schema of SOE</returns>
public string GetSchema()
{
return this.requestHandler.GetSchema();
}
/// <summary>
/// Handle REST Request
/// </summary>
/// <param name="Capabilities">capabilities soe</param>
/// <param name="resourceName">name of resource</param>
/// <param name="operationName">name of operation</param>
/// <param name="operationInput">operation Input</param>
/// <param name="outputFormat">output Format</param>
/// <param name="requestProperties">request Properties</param>
/// <param name="responseProperties">response Properties</param>
/// <returns>object byte[]</returns>
public byte[] HandleRESTRequest(string Capabilities, string resourceName, string operationName, string operationInput, string outputFormat, string requestProperties, out string responseProperties)
{
return this.requestHandler.HandleRESTRequest(Capabilities, resourceName, operationName, operationInput, outputFormat, requestProperties, out responseProperties);
}
#endregion
/// <summary>
/// Create schema SOE
/// </summary>
/// <returns>Rest Resource</returns>
private RestResource CreateRestSchema()
{
////resource root
RestResource rootResource = new RestResource(this.soeName, false, this.RootResourceHandler);
RestResource infoResource = new RestResource("Info", false, this.InfoResHandler);
rootResource.resources.Add(infoResource);
RestResource helpResource = new RestResource("Help", false, this.HelpResHandler);
rootResource.resources.Add(helpResource);
////resource geometricNetworks
RestResource geometricNetworksResource = new RestResource("GeometricNetworks", true, new ResourceHandler(this.GeometricNeworkFeatureClass));
////operation TraceNetwork
RestOperation traceNetworkOperation = new RestOperation("TraceNetwork", new string[] { "traceSolverType", "flowMethod", "flowElements", "edgeFlags", "junctionFlags", "edgeBarriers", "junctionBarriers", "outFields", "maxTracedFeatures", "tolerance", "traceIndeterminateFlow", "shortestPathObjFn", "disableLayers", "junctionWeight", "fromToEdgeWeight", "toFromEdgeWeight", "junctionFilterWeight", "junctionFilterRanges", "junctionFilterNotOperator", "fromToEdgeFilterWeight", "toFromEdgeFilterWeight", "edgeFilterRanges", "edgeFilterNotOperator" }, new string[] { "json" }, this.TraceGeometryNetwork, "Trace network");
////operation IsolateValve
RestOperation isolateValveOperation = new RestOperation("IsolateValve", new string[] { "stationLayerId", "valveLayerId", "flowElements", "edgeFlags", "junctionFlags", "edgeBarriers", "junctionBarriers", "outFields", "maxTracedFeatures", "tolerance" }, new string[] { "json" }, this.IsolateValve, "Isolate valve");
////operation PosAlong
RestOperation traceNetworkPosAlongOperation = new RestOperation("TraceNetworkPosAlong", new string[] { "edgeFlags", "length", "fieldLevel", "offset", "tolerance", "sameOrder" }, new string[] { "json" }, this.TraceGeometryNetworkPosAlong, "Position along");
geometricNetworksResource.operations.Add(traceNetworkOperation);
geometricNetworksResource.operations.Add(isolateValveOperation);
geometricNetworksResource.operations.Add(traceNetworkPosAlongOperation);
rootResource.resources.Add(geometricNetworksResource);
return rootResource;
}
/// <summary>
/// Handler Root Resource
/// </summary>
/// <param name="boundVariables">bound Variables</param>
/// <param name="outputFormat">output Format</param>
/// <param name="requestProperties">request Properties</param>
/// <param name="responseProperties">response Properties</param>
/// <returns>object byte[]</returns>
private byte[] RootResourceHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
{
responseProperties = null;
List<GeometricNetworkInfo> layerInfos = this.geometricNetworkInfos;
JsonObject[] objectArray = System.Array.ConvertAll(layerInfos.ToArray(), i => i.ToJsonObject());
JsonObject jsonObject = new JsonObject();
jsonObject.AddArray("GeometricNetworks", objectArray);
return Encoding.UTF8.GetBytes(jsonObject.ToJson());
}
/// <summary>
/// Returns JSON representation of Help resource. This resource is not a collection.
/// </summary>
/// <param name="boundVariables">list of variables bound</param>
/// <param name="outputFormat">format of output</param>
/// <param name="requestProperties">list of request properties</param>
/// <param name="responseProperties">list of response properties </param>
/// <returns>String JSON representation of Help resource.</returns>
private byte[] HelpResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
{
responseProperties = "{\"Content-Type\" : \"application/json\"}";
JsonObject result = new JsonObject();
JsonObject soeResources = new JsonObject();
soeResources.AddString("GeometricNetworks", "A list of geometric network in the map. Operations return 'hasError' = true and 'errorDescription' (string) if there is an error.");
result.AddJsonObject("Resources", soeResources);
JsonObject getTraceNetworkInputs = new JsonObject();
getTraceNetworkInputs.AddString("traceSolverType", "(string) FindAccumulation or FindCircuits or FindCommonAncestors or FindFlowElements or FindFlowEndElements or FindFlowUnreachedElements or FindPath or FindSource or FindLongest");
getTraceNetworkInputs.AddString("flowMethod", "(string) enum arcobjects esriFlowMethod");
getTraceNetworkInputs.AddString("flowElements", "(string) enum arcobjects esriFlowElements");
getTraceNetworkInputs.AddString("edgeFlags", "array of geometries(point) (see rest esri point)");
getTraceNetworkInputs.AddString("junctionFlags", "array of geometries(point) (see rest esri point)");
getTraceNetworkInputs.AddString("edgeBarriers", "array of geometries(point) (see rest esri point)");
getTraceNetworkInputs.AddString("junctionBarriers", "array of geometries(point) (see rest esri point)");
getTraceNetworkInputs.AddString("maxTracedFeatures", "max number of edge or junction that can be returned");
getTraceNetworkInputs.AddString("tolerance", "in map units to search for flag or barrier");
getTraceNetworkInputs.AddString("traceIndeterminateFlow", "booleran (optional)");
getTraceNetworkInputs.AddString("shortestPathObjFn", "required only for FindPath or FindSource (optional)");
getTraceNetworkInputs.AddString("disableLayers", "array of int. Id of layers (optional)");
getTraceNetworkInputs.AddString("outFields", "list of fields in result ('*' for all fields). This list is common for all feature class in geometric network.");
getTraceNetworkInputs.AddString("junctionWeight", "(optional)");
getTraceNetworkInputs.AddString("fromToEdgeWeight", "(optional)");
getTraceNetworkInputs.AddString("toFromEdgeWeight", "(optional)");
getTraceNetworkInputs.AddString("junctionFilterWeight", "(optional)");
getTraceNetworkInputs.AddString("junctionFilterRanges", "(optional)");
getTraceNetworkInputs.AddString("junctionFilterNotOperator", "boolean (optional)");
getTraceNetworkInputs.AddString("fromToEdgeFilterWeight", "(optional)");
getTraceNetworkInputs.AddString("toFromEdgeFilterWeight", "(optional)");
getTraceNetworkInputs.AddString("edgeFilterRanges", "(optional)");
getTraceNetworkInputs.AddString("edgeFilterNotOperator", "boolean (optional)");
JsonObject getTraceNetworkOutput = new JsonObject();
getTraceNetworkOutput.AddString("barriersNotFound", "array of geometries(point) (see rest esri point)");
getTraceNetworkOutput.AddString("flagsNotFound", "array of geometries(point) (see rest esri point)");
getTraceNetworkOutput.AddString("edges", "array of feature (see rest esri feature)");
getTraceNetworkOutput.AddString("junctions", "array of feature (see rest esri feature)");
JsonObject getTraceNetworkParams = new JsonObject();
getTraceNetworkParams.AddString("Info", "Trace Network. To learn more about formatting the input geometries, input geometry, please visit the 'Geometry Objects' section of the ArcGIS Server REST documentation.");
getTraceNetworkParams.AddJsonObject("Inputs", getTraceNetworkInputs);
getTraceNetworkParams.AddJsonObject("Outputs", getTraceNetworkOutput);
JsonObject getIsolateValveInputs = new JsonObject();
getIsolateValveInputs.AddString("stationLayerId", "(int) Id of station layer");
getIsolateValveInputs.AddString("valveLayerId", "(int) Id of valve layer");
getIsolateValveInputs.AddString("flowElements", "enum arcobjects esriFlowElements");
getIsolateValveInputs.AddString("edgeFlags", "array of geometries(point) (see rest esri point)");
getIsolateValveInputs.AddString("junctionFlags", "array of geometries(point) (see rest esri point)");
getIsolateValveInputs.AddString("edgeBarriers", "not used");
getIsolateValveInputs.AddString("junctionBarriers", "not used");
getIsolateValveInputs.AddString("maxTracedFeatures", "max number of edge or junction that can be returned");
getIsolateValveInputs.AddString("tolerance", "in map units to search for flag");
getIsolateValveInputs.AddString("outFields", "list of fields in result ('*' for all fields). This list is common for all feature class in geometric network.");
JsonObject getIsolateValveOutput = new JsonObject();
getIsolateValveOutput.AddString("flagsNotFound", "array of geometries(point) (see rest esri point)");
getIsolateValveOutput.AddString("edges", "array of feature (see rest esri feature)");
getIsolateValveOutput.AddString("junctions", "array of feature (see rest esri feature)");
getIsolateValveOutput.AddString("valves", "array of feature (see rest esri feature)");
JsonObject getIsolateValveParams = new JsonObject();
getIsolateValveParams.AddString("Info", "Isolate valve. To learn more about formatting the input geometries, input geometry, please visit the 'Geometry Objects' section of the ArcGIS Server REST documentation.");
getIsolateValveParams.AddJsonObject("Inputs", getIsolateValveInputs);
getIsolateValveParams.AddJsonObject("Outputs", getIsolateValveOutput);
JsonObject getTraceNetworkPosAlongInputs = new JsonObject();
getTraceNetworkPosAlongInputs.AddString("edgeFlags", "array of geometries(point) (see rest esri point). For now used only the first edge flag.");
getTraceNetworkPosAlongInputs.AddString("length", "(double) distance from edgeFlags along geometric network. Negative value along upstream, positive value along downstream");
getTraceNetworkPosAlongInputs.AddString("fieldLevel", "(string) field with Strahler stream order. It is read in edge. Used if you set parameter sameOrder = true");
getTraceNetworkPosAlongInputs.AddString("offset", "double (optional) offset from geometric network");
getTraceNetworkPosAlongInputs.AddString("tolerance", "in map units to search for flag");
getTraceNetworkPosAlongInputs.AddString("sameOrder", "(bool) optional default = false. If you set true the trace stop when the start Strahler stream order change.");
JsonObject getTraceNetworkPosAlongOutput = new JsonObject();
getTraceNetworkPosAlongOutput.AddString("geometry", "(geometry) polyline or point (see rest esri polyline or point)");
getTraceNetworkPosAlongOutput.AddString("message", "(string) message if length exceed stream");
JsonObject getTraceNetworkPosAlongParams = new JsonObject();
getTraceNetworkPosAlongParams.AddString("Info", "Position along geometric network. Requirements: simple egde, flow defined and digitalized in same direction of flow");
getTraceNetworkPosAlongParams.AddJsonObject("Inputs", getTraceNetworkPosAlongInputs);
getTraceNetworkPosAlongParams.AddJsonObject("Outputs", getTraceNetworkPosAlongOutput);
JsonObject soeOperations = new JsonObject();
soeOperations.AddJsonObject("TraceNetwork", getTraceNetworkParams);
soeOperations.AddJsonObject("IsolateValve", getIsolateValveParams);
soeOperations.AddJsonObject("TraceNetworkPosAlong", getTraceNetworkPosAlongParams);
result.AddJsonObject("Operations", soeOperations);
return result.JsonByte();
}
/// <summary>
/// Returns JSON representation of Info resource. This resource is not a collection.
/// </summary>
/// <param name="boundVariables">list of variables bound</param>
/// <param name="outputFormat">format of output</param>
/// <param name="requestProperties">list of request properties</param>
/// <param name="responseProperties">list of response properties </param>
/// <returns>String JSON representation of Info resource.</returns>
private byte[] InfoResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
{
responseProperties = "{\"Content-Type\" : \"application/json\"}";
JsonObject result = new JsonObject();
AddInPackageAttribute addInPackage = (AddInPackageAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AddInPackageAttribute), false)[0];
result.AddString("agsVersion", addInPackage.TargetVersion);
result.AddString("soeVersion", addInPackage.Version);
result.AddString("author", addInPackage.Author);
result.AddString("company", addInPackage.Company);
return Encoding.UTF8.GetBytes(result.ToJson());
}
/// <summary>
/// resource Geometry Network
/// </summary>
/// <param name="boundVariables">list of variables bound</param>
/// <param name="outputFormat">format of output</param>
/// <param name="requestProperties">list of request properties</param>
/// <param name="responseProperties">list of response properties </param>
/// <returns>resource in byte</returns>
private byte[] GeometricNeworkFeatureClass(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
{
responseProperties = null;
if (boundVariables["GeometricNetworksID"] == null)
{
List<GeometricNetworkInfo> layerInfos = this.geometricNetworkInfos;
JsonObject[] objectArray = System.Array.ConvertAll(layerInfos.ToArray(), i => i.ToJsonObject());
JsonObject jsonObject = new JsonObject();
jsonObject.AddArray("GeometricNetworks", objectArray);
return Encoding.UTF8.GetBytes(jsonObject.ToJson());
}
else
{
int id = Convert.ToInt32(boundVariables["GeometricNetworksID"], CultureInfo.InvariantCulture);
string s = this.geometricNetworkInfos.Find(i => i.ID == id).ToJsonObject().ToJson();
return Encoding.UTF8.GetBytes(s);
}
}
/// <summary>
/// From service return list of layer with Geometry Network
/// </summary>
private void GetGeometricNetworkInfos()
{
IMapServer3 serverObject = this.GetMapServer();
IMapLayerInfos mapLayerInfos = serverObject.GetServerInfo(serverObject.DefaultMapName).MapLayerInfos;
this.geometricNetworkInfos = new List<GeometricNetworkInfo>();
for (int i = 0; i < mapLayerInfos.Count; i++)
{
IMapLayerInfo mapLayerInfo = mapLayerInfos.get_Element(i);
if (mapLayerInfo.IsFeatureLayer)
{
IFeatureClass featureClass = this.GetFeatureClass(mapLayerInfo.ID);
IFeatureDataset featureDataset = featureClass.FeatureDataset;
if ((featureDataset != null) && ((featureClass.FeatureType == esriFeatureType.esriFTSimpleJunction) || (featureClass.FeatureType == esriFeatureType.esriFTSimpleEdge) || (featureClass.FeatureType == esriFeatureType.esriFTComplexJunction) || (featureClass.FeatureType == esriFeatureType.esriFTComplexEdge)))
{
INetworkCollection networkCollection = featureDataset as INetworkCollection;
if (networkCollection != null && networkCollection.GeometricNetworkCount > 0)
{
for (int j = 0; j < networkCollection.GeometricNetworkCount; j++)
{
ESRI.ArcGIS.Geodatabase.IGeometricNetwork geometricNetwork = networkCollection.GeometricNetwork[j];
IFeatureClassContainer featureClassContainer = geometricNetwork as IFeatureClassContainer;
if (featureClassContainer.get_ClassByID(featureClass.FeatureClassID) != null)
{
if (!this.geometricNetworkInfos.Exists(gn => gn.GeometricNetwork == geometricNetwork))
{
IDataset dataset = geometricNetwork as IDataset;
this.geometricNetworkInfos.Add(new GeometricNetworkInfo(this.geometricNetworkInfos.Count + 1, dataset.Name, geometricNetwork));
}
break;
}
}
}
}
}
}
}
/// <summary>
/// Operation Isolate Valve
/// </summary>
/// <param name="boundVariables">bound Variables</param>
/// <param name="operationInput">operation Input</param>
/// <param name="outputFormat">output Format</param>
/// <param name="requestProperties">request Properties</param>
/// <param name="responseProperties">response Properties</param>
/// <returns>Isolate Valve</returns>
private byte[] IsolateValve(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties)
{
responseProperties = null;
string methodName = MethodBase.GetCurrentMethod().Name;
////geometric Network id
int id;
try
{
id = Convert.ToInt32(boundVariables["GeometricNetworksID"], CultureInfo.InvariantCulture);
}
catch
{
throw new ArgumentException("geometric Network id not valid", methodName);
}
GeometricNetworkInfo geometricNetworkInfo = this.geometricNetworkInfos.Find(i => i.ID == id);
if (geometricNetworkInfo == null)
{
throw new ArgumentException("geometric Network id not found", methodName);
}
ESRI.ArcGIS.Geodatabase.IGeometricNetwork geometricNetwork = geometricNetworkInfo.GeometricNetwork;
////station id
long? stationId;
bool found = operationInput.TryGetAsLong("stationLayerId", out stationId);
if (!found || !stationId.HasValue)
{
throw new ArgumentException("stationLayerId not specified", methodName);
}
if (stationId.Value > int.MaxValue)
{
throw new ArgumentException("stationLayerId not valid", methodName);
}
////valve id
long? valveId;
found = operationInput.TryGetAsLong("valveLayerId", out valveId);
if (!found || !valveId.HasValue)
{
throw new ArgumentException("valveLayerId not specified", methodName);
}
if (valveId.Value > int.MaxValue)
{
throw new ArgumentException("valveLayerId not valid", methodName);
}
////flowElements
string flowElementsString;
found = operationInput.TryGetString("flowElements", out flowElementsString);
if (!found || string.IsNullOrEmpty(flowElementsString))
{
throw new ArgumentException("flowElements not specified", methodName);
}
esriFlowElements flowElements;
try
{
flowElements = (esriFlowElements)Enum.Parse(typeof(esriFlowElements), flowElementsString);
}
catch
{
throw new ArgumentException("flowElements not valid", methodName);
}
////edge flags
object[] jsonEdgeFlags;
List<IPoint> edgeFlags = new List<IPoint>();
if (operationInput.TryGetArray("edgeFlags", out jsonEdgeFlags))
{
JsonObject[] joEdgeFlags = null;
try
{
joEdgeFlags = jsonEdgeFlags.Cast<JsonObject>().ToArray();
}
catch
{
throw new ArgumentException("invalid edge flag", methodName);
}
foreach (JsonObject jo in joEdgeFlags)
{
IPoint location = Conversion.ToGeometry(jo, esriGeometryType.esriGeometryPoint) as IPoint;
if (location == null)
{
throw new ArgumentException("invalid edgeFlags", methodName);
}
edgeFlags.Add(location);
}
}
//// junction Flags
object[] jsonJunctionFlags;
List<IPoint> junctionFlags = new List<IPoint>();
if (operationInput.TryGetArray("junctionFlags", out jsonJunctionFlags))
{
JsonObject[] joJunctionFlags = null;
try
{
joJunctionFlags = jsonJunctionFlags.Cast<JsonObject>().ToArray();
}
catch
{
throw new ArgumentException("invalid junctionFlags", methodName);
}
foreach (JsonObject jo in joJunctionFlags)
{
IPoint location = Conversion.ToGeometry(jo, esriGeometryType.esriGeometryPoint) as IPoint;
if (location == null)
{
throw new ArgumentException("invalid junctionFlags", methodName);
}
junctionFlags.Add(location);
}
}
if ((edgeFlags.Count == 0) && (junctionFlags.Count == 0))
{
throw new ArgumentException("edgeFlags and/or junctionFlags not found", methodName);
}
//// edge Barriers
object[] jsonEdgeBarriers;
List<IPoint> edgeBarriers = new List<IPoint>();
if (operationInput.TryGetArray("edgeBarriers", out jsonEdgeBarriers))
{
JsonObject[] joEdgeBarriers = null;
try
{
joEdgeBarriers = jsonEdgeBarriers.Cast<JsonObject>().ToArray();
}
catch
{
throw new ArgumentException("invalid edgeBarriers", methodName);
}
foreach (JsonObject jo in joEdgeBarriers)
{
IPoint location = Conversion.ToGeometry(jo, esriGeometryType.esriGeometryPoint) as IPoint;
if (location == null)
{
throw new ArgumentException("invalid edgeBarriers", methodName);
}
edgeBarriers.Add(location);
}
}
//// junction Barriers
object[] jsonJunctionBarriers;
List<IPoint> junctionBarriers = new List<IPoint>();
if (operationInput.TryGetArray("junctionBarriers", out jsonJunctionBarriers))
{
JsonObject[] joJunctionBarriers = null;
try
{
joJunctionBarriers = jsonJunctionBarriers.Cast<JsonObject>().ToArray();
}
catch
{
throw new ArgumentException("invalid junctionBarriers", methodName);
}
foreach (JsonObject jo in joJunctionBarriers)
{
IPoint location = Conversion.ToGeometry(jo, esriGeometryType.esriGeometryPoint) as IPoint;
if (location == null)
{
throw new ArgumentException("invalid junctionBarriers", methodName);
}
junctionBarriers.Add(location);
}
}
////outFields
string outFields;
found = operationInput.TryGetString("outFields", out outFields);
if (!found || string.IsNullOrEmpty(outFields))
{
throw new ArgumentException("invalid outFields", methodName);
}
string[] fields = outFields.Split(',');
////maxFeatures
long? maxFeatures;
found = operationInput.TryGetAsLong("maxTracedFeatures", out maxFeatures);
if (!found || !maxFeatures.HasValue)
{
throw new ArgumentException("invalid maxTracedFeatures", methodName);
}
if (maxFeatures.Value > int.MaxValue)
{
throw new ArgumentException("invalid maxTracedFeatures", methodName);
}
////tolerance
double? tolerance;
found = operationInput.TryGetAsDouble("tolerance", out tolerance);
if (!found || !tolerance.HasValue)
{
throw new ArgumentException("invalid tolerance", methodName);
}
if (tolerance.Value < 0)
{
throw new ArgumentException("invalid tolerance", methodName);
}
return this.GetIsolateValve(geometricNetwork, (int)stationId.Value, (int)valveId.Value, flowElements, edgeFlags, junctionFlags, edgeBarriers, junctionBarriers, fields, (int)maxFeatures.Value, tolerance.Value);
}
/// <summary>
/// operation Trace Geometry Network Position Along
/// </summary>
/// <param name="boundVariables">bound Variables</param>
/// <param name="operationInput">operation Input</param>
/// <param name="outputFormat">output Format</param>
/// <param name="requestProperties">request Properties</param>
/// <param name="responseProperties">response Properties</param>
/// <returns>Trace Geometry Network</returns>
private byte[] TraceGeometryNetworkPosAlong(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties)
{
responseProperties = null;
string methodName = MethodBase.GetCurrentMethod().Name;
// geometric Network id
int id;
try
{
id = Convert.ToInt32(boundVariables["GeometricNetworksID"], CultureInfo.InvariantCulture);
}
catch
{
throw new ArgumentException("geometric Network id not valid", methodName);
}
GeometricNetworkInfo geometricNetworkInfo = this.geometricNetworkInfos.Find(i => i.ID == id);
if (geometricNetworkInfo == null)
{
throw new ArgumentException("geometric Network id not found", methodName);
}
ESRI.ArcGIS.Geodatabase.IGeometricNetwork geometricNetwork = geometricNetworkInfo.GeometricNetwork;
// edge flags
object[] jsonEdgeFlags;
List<IPoint> edgeFlags = new List<IPoint>();
if (operationInput.TryGetArray("edgeFlags", out jsonEdgeFlags))
{
JsonObject[] joEdgeFlags = null;
try
{
joEdgeFlags = jsonEdgeFlags.Cast<JsonObject>().ToArray();
}
catch
{
throw new ArgumentException("invalid edge flag", methodName);
}
foreach (JsonObject jo in joEdgeFlags)
{
IPoint location = Conversion.ToGeometry(jo, esriGeometryType.esriGeometryPoint) as IPoint;
if (location == null)
{
throw new ArgumentException("invalid edgeFlags", methodName);
}
edgeFlags.Add(location);
}
}
//// junction Flags
//// object[] jsonJunctionFlags;
//// List<IPoint> junctionFlags = new List<IPoint>();
//// if (operationInput.TryGetArray("junctionFlags", out jsonJunctionFlags))
//// {
//// JsonObject[] joJunctionFlags = null;
//// try
//// {
//// joJunctionFlags = jsonJunctionFlags.Cast<JsonObject>().ToArray();
//// }
//// catch
//// {
//// throw new ArgumentException("invalid junctionFlags", methodName);
//// }
//// foreach (JsonObject jo in joJunctionFlags)
//// {
//// IPoint location = Conversion.ToGeometry(jo, esriGeometryType.esriGeometryPoint) as IPoint;
//// if (location == null)
//// {
//// throw new ArgumentException("invalid junctionFlags", methodName);
//// }
//// junctionFlags.Add(location);
//// }
////}
////if ((edgeFlags.Count == 0) && (junctionFlags.Count == 0))
////{
//// throw new ArgumentException("edgeFlags and/or junctionFlags not found", methodName);
////}
if (edgeFlags.Count != 1)
{
throw new ArgumentException("edgeFlags != 1", methodName);
}
// length (downstream positive value - upstream negative value)
double? lengthValue;
bool found = operationInput.TryGetAsDouble("length", out lengthValue);
if (!found || !lengthValue.HasValue)
{
throw new ArgumentException("distance not specified", methodName);
}
double length = lengthValue.Value;
if (length == 0)
{
throw new ArgumentException("distance not valid", methodName);
}
bool sameStream = false;
bool? sameStreamValue;
found = operationInput.TryGetAsBoolean("sameOrder", out sameStreamValue);
if (found)
{
sameStream = sameStreamValue.Value;
}
string fieldLevel = null;
if ((lengthValue.Value < 0) || ((lengthValue.Value > 0) && sameStream))
{
found = operationInput.TryGetString("fieldLevel", out fieldLevel);
if (!found || string.IsNullOrEmpty(fieldLevel))
{
throw new ArgumentException("fieldLevel not specified", methodName);
}
}
// offset
double? offsetValue = double.NaN;
operationInput.TryGetAsDouble("offset", out offsetValue);
// tolerance
double? toleranceValue;
found = operationInput.TryGetAsDouble("tolerance", out toleranceValue);
if (!found || !toleranceValue.HasValue)
{
throw new ArgumentException("invalid tolerance", methodName);
}
if (toleranceValue.Value < 0)
{
throw new ArgumentException("invalid tolerance", methodName);
}
double tolerance = toleranceValue.Value;
try
{
List<IGeometry> flagNotFound = new List<IGeometry>();
IPoint point = edgeFlags[0];
int eid = Helper.GetEIDFromPoint(geometricNetwork, tolerance, point, esriElementType.esriETEdge);
if (eid < 1)
{
flagNotFound.Add(point);
JsonObject result = new JsonObject();
result.AddArray("flagsNotFound", Helper.GetListJsonObjects(flagNotFound));
return result.JsonByte();
}
INetElements networkElements = (INetElements)geometricNetwork.Network;
esriFlowElements flowElements = esriFlowElements.esriFEEdges;
ITraceFlowSolverGEN traceFlowSolver = new TraceFlowSolverClass() as ITraceFlowSolverGEN;
INetSolver netSolver = traceFlowSolver as INetSolver;
netSolver.SourceNetwork = geometricNetwork.Network;
traceFlowSolver.TraceIndeterminateFlow = false;
IFeatureDataset featureDataset = geometricNetwork.FeatureDataset;
IGeometry geometry = null;
string messageInfo = null;
//// downstream
if (length > 0)
{
//// edge Flags
////if (edgeFlags.Count == 1)
////{
INetElements netElements = geometricNetwork.Network as INetElements;
int featureClassID, featureID, subID;
netElements.QueryIDs(eid, esriElementType.esriETEdge, out featureClassID, out featureID, out subID);
INetFlag netFlag = new EdgeFlagClass();
netFlag.UserClassID = featureClassID;
netFlag.UserID = featureID;
netFlag.UserSubID = subID;
IEdgeFlag[] efs = new IEdgeFlag[1];
efs[0] = netFlag as IEdgeFlag;
traceFlowSolver.PutEdgeOrigins(ref efs);
if (sameStream)
{
bool error = false;
bool result = false;
IEnumNetEIDBuilderGEN eids = new EnumNetEIDArrayClass();
eids.ElementType = esriElementType.esriETEdge;
eids.Add(eid);
IFeature f = Helper.GetFeatureClassFromID(featureDataset, featureClassID).GetFeature(featureID);
int idxLivello = f.Fields.FindField(fieldLevel);
int livelloCurrent = int.Parse(f.get_Value(idxLivello).ToString());
while (true)
{
int fromEIDJunction, toEIDJunction;
INetTopologyEditGEN netTopology = networkElements as INetTopologyEditGEN;
netTopology.GetFromToJunctionEIDs(eid, out fromEIDJunction, out toEIDJunction);
int edgeCount = netTopology.GetAdjacentEdgeCount(toEIDJunction);
////check if all edges into junction
int inEdges = 0;
int eidCurrent = -1;
for (int i = 0; i < edgeCount; i++)
{
bool reverseOrientation;
int adjacentEdge;
netTopology.GetAdjacentEdge(toEIDJunction, i, out adjacentEdge, out reverseOrientation);
////exit at junction
if (reverseOrientation == false)
{
int userClassId, userId, userSubId;
networkElements.QueryIDs(adjacentEdge, esriElementType.esriETEdge, out userClassId, out userId, out userSubId);
f = Helper.GetFeatureClassFromID(featureDataset, userClassId).GetFeature(userId);
idxLivello = f.Fields.FindField(fieldLevel);
int livello = int.Parse(f.get_Value(idxLivello).ToString());
if (livello <= livelloCurrent)
{
eidCurrent = adjacentEdge;
}
else
{
result = true;
}
////only one exit
break;
}
else
{
++inEdges;
}
}
if ((inEdges == edgeCount) || result)
{
break;
}
if (eidCurrent == -1)
{
error = true;
break;
}
eids.Add(eidCurrent);
eid = eidCurrent;
}
if (error || (eids as IEnumNetEID).Count == 0)
{
throw new GeometricNetworkException("Error in find of downstream. Check level in geometric network");
}
else
{
geometry = Helper.GetPolylinePosAlong(geometricNetwork, eids as IEnumNetEID, length, point, offsetValue, ref messageInfo);
}
}
else
{
IEnumNetEID resultJunctions, resultEdges;
traceFlowSolver.FindFlowElements(esriFlowMethod.esriFMDownstream, flowElements, out resultJunctions, out resultEdges);
if ((resultEdges != null) || (resultEdges.Count != 0))
{
geometry = Helper.GetPolylinePosAlong(geometricNetwork, resultEdges as IEnumNetEID, length, point, offsetValue, ref messageInfo);
}
else
{
throw new GeometricNetworkException("Result not found!");
}
}
////}
}
else if (lengthValue < 0)
{
////if (edgeFlags.Count == 1)
////{
bool error = false;
IEnumNetEIDBuilderGEN eids = new EnumNetEIDArrayClass();
eids.ElementType = esriElementType.esriETEdge;
eids.Add(eid);
int numEdges = geometricNetwork.Network.EdgeCount;
int countLoop = 0;
int levelCurrent = -1;
while (true)
{
int fromEIDJunction, toEIDJunction;
INetTopologyEditGEN netTopology = networkElements as INetTopologyEditGEN;
netTopology.GetFromToJunctionEIDs(eid, out fromEIDJunction, out toEIDJunction);
int edgeCount = netTopology.GetAdjacentEdgeCount(fromEIDJunction);
if (edgeCount == 1)
{
break;
}
if (sameStream)
{
int userClassID, userID, userSubID;
networkElements.QueryIDs(eid, esriElementType.esriETEdge, out userClassID, out userID, out userSubID);
IFeature f = Helper.GetFeatureClassFromID(featureDataset, userClassID).GetFeature(userID);
int idxOrder = f.Fields.FindField(fieldLevel);
levelCurrent = int.Parse(f.get_Value(idxOrder).ToString());
}
int outEdges = 0;
bool reverseOrientation;
int adjacentEdge;
int order = -1;
int eidCurrent = -1;
for (int i = 0; i < edgeCount; i++)
{
netTopology.GetAdjacentEdge(fromEIDJunction, i, out adjacentEdge, out reverseOrientation);
////enter in junction
if (reverseOrientation)
{
int userClassID, userID, userSubID;
networkElements.QueryIDs(adjacentEdge, esriElementType.esriETEdge, out userClassID, out userID, out userSubID);
IFeature f = Helper.GetFeatureClassFromID(featureDataset, userClassID).GetFeature(userID);
int idxOrder = f.Fields.FindField(fieldLevel);
////strahler order of stream
int orderTmp = int.Parse(f.get_Value(idxOrder).ToString());
if (sameStream)
{
if (levelCurrent == orderTmp)
{
eidCurrent = adjacentEdge;
break;
}
}
else
{
if (orderTmp > order)
{
order = orderTmp;
eidCurrent = adjacentEdge;
}
}
}
else
{
++outEdges;
}
}
if (outEdges == edgeCount)
{
break;
}
if (eidCurrent == -1)
{
if (!sameStream)
{
error = true;