-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprtgshell2.cs
More file actions
1204 lines (987 loc) · 80.2 KB
/
prtgshell2.cs
File metadata and controls
1204 lines (987 loc) · 80.2 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
using System;
using System.Xml;
using System.Xml.Linq;
using System.Web;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.Net.Security;
using System.Linq;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
namespace PrtgShell {
public class ExeXML {
private string Text;
public string text {
get {
return this.Text;
}
set {
if (value.Length < 2000) {
this.Text = value;
} else {
throw new ArgumentOutOfRangeException("Invalid value. Maximum length is 2000 characters.");
}
}
}
public bool error { get; set; }
// should this be read-only?
// does there need to be a RemoveChannel method?
public List<PrtgShell.XmlResult> channels { get; set; }
public void AddChannel (PrtgShell.XmlResult channel) {
this.channels.Add(channel);
}
public ExeXML () {
this.channels = new List<PrtgShell.XmlResult>();
}
public string PrintError (string ErrorText) {
XDocument XmlObject = new XDocument(
new XElement("prtg",
new XElement("error", 1),
new XElement("text", ErrorText)
)
);
return XmlObject.ToString();
}
// i suppose there should also be a method here to generate the XML object out, eh?
// how this will actually function needs to be nailed down
// this is the method that will need to determine what in this object is worthy of spitting out and how
public string PrintOutput () {
// make the root, add the text
XDocument XmlObject = new XDocument(
new XElement("prtg",
new XElement("text",this.Text)
)
);
// loop through the channels
foreach (PrtgShell.XmlResult XmlResult in this.channels) {
// make the result
XElement ThisChannel = new XElement("result",
new XElement("channel", XmlResult.channel),
new XElement("value", XmlResult.resultvalue),
new XElement("unit", XmlResult.unit)
);
if (!String.IsNullOrEmpty(XmlResult.customunit)) {
ThisChannel.Add(
new XElement("customunit", XmlResult.customunit)
);
}
if (XmlResult.valuemode) {
ThisChannel.Add(
new XElement("mode", XmlResult.Mode)
);
}
if (XmlResult.warning) {
ThisChannel.Add(
new XElement("warning", Convert.ToString(Convert.ToInt32(XmlResult.warning)))
);
}
///////////////////////////////////////////
// these both default to true; the usual methods of simply not including the tag when they're
// not set won't work here.
// will it work if we just flip the check? (if false...)
if (!XmlResult.showchart) {
ThisChannel.Add(
new XElement("showchart", Convert.ToString(Convert.ToInt32(XmlResult.showchart)))
);
}
if (!XmlResult.showtable) {
ThisChannel.Add(
new XElement("showtable", Convert.ToString(Convert.ToInt32(XmlResult.showtable)))
);
}
///////////////////////////////////////////
// limits
if (XmlResult.limitmode) {
ThisChannel.Add(
new XElement("limitmode", Convert.ToString(Convert.ToInt32(XmlResult.limitmode)))
);
}
if (XmlResult.limitminwarning > -1) {
ThisChannel.Add(
new XElement("limitminwarning", Convert.ToString(XmlResult.limitminwarning))
);
}
if (XmlResult.limitmaxwarning > -1) {
ThisChannel.Add(
new XElement("limitmaxwarning", Convert.ToString(XmlResult.limitmaxwarning))
);
}
if (XmlResult.limitminerror > -1) {
ThisChannel.Add(
new XElement("limitminwarning", Convert.ToString(XmlResult.limitminwarning))
);
}
if (XmlResult.limitmaxerror > -1) {
ThisChannel.Add(
new XElement("limitmaxwarning", Convert.ToString(XmlResult.limitmaxwarning))
);
}
if (!(String.IsNullOrEmpty(XmlResult.limitwarningmsg))) {
ThisChannel.Add(
new XElement("mode", XmlResult.limitwarningmsg)
);
}
if (!(String.IsNullOrEmpty(XmlResult.limiterrormsg))) {
ThisChannel.Add(
new XElement("mode", XmlResult.limiterrormsg)
);
}
///////////////////////////////////////////
// rates and speeds
if (!(String.IsNullOrEmpty(XmlResult.volumesize))) {
ThisChannel.Add(
new XElement("mode", XmlResult.volumesize)
);
}
if (!(String.IsNullOrEmpty(XmlResult.speedsize))) {
ThisChannel.Add(
new XElement("mode", XmlResult.speedsize)
);
}
if (!(String.IsNullOrEmpty(XmlResult.speedtime))) {
ThisChannel.Add(
new XElement("mode", XmlResult.speedtime)
);
}
if (!(String.IsNullOrEmpty(XmlResult.valuelookup))) {
ThisChannel.Add(
new XElement("mode", XmlResult.valuelookup)
);
}
///////////////////////////////////////////
// decimalmode & floats
// this could use further review as well
// not at all convinced that decimalmode actually works in the API,
// but the way we handle it may also not be correct
// isfloat works properly, but there might be a more elegant way to handle it
if (!(String.IsNullOrEmpty(XmlResult.decimalmode))) {
ThisChannel.Add(
new XElement("mode", XmlResult.decimalmode)
);
}
if (XmlResult.isfloat) {
ThisChannel.Add(
new XElement("float",
Convert.ToString(Convert.ToInt32(XmlResult.isfloat)))
);
}
// add everything we've done here to the root
XmlObject.Element("prtg").Add(ThisChannel);
}
// return beautiful, well-formatted xml
return XmlObject.ToString();
}
}
public class HttpQueryReturnObject {
public HttpStatusCode Statuscode;
public string DetailedError;
public XmlDocument Data;
public string RawData;
public int HttpStatusCode {
get {
return (int)this.Statuscode;
}
}
}
public class NewAggregation : PrtgSensorCreator {
// "aggregationchannel_" = $AggregationChannelDefinition
// "warnonerror_" = 0 # 0 = "Factory sensor shows error state when one or more source sensors are in error state"; 1 = "Factory sensor shows warning state when one or more source sensors are in error state"; 2 = "Use custom formula", uses aggregation status field
// "aggregationstatus_" = 0 # https://prtg.forsyth.k12.ga.us/help/sensor_factory_sensor.htm#sensor_status
// "missingdata_" = 0 # 0 = " Do not calculate factory channels that use the sensor"; 1 = "Calculate the factory channels and use zero as source value"
public string aggregationchannel_ { get; set; }
public int warnonerror_ { get; set; }
public bool aggregationstatus_ { get; set; }
public bool missingdata_ { get; set; }
public NewAggregation () {
this.sensortype = "aggregation";
this.inherittriggers = true;
this.name_ = "Sensor Factory";
this.tags_ = new string[] {"factorysensor"};
this.intervalgroup = true;
this.interval = 60;
this.aggregationchannel_ = @"#1:Sample
Channel(1000,0)
#2:Response Time[ms]
Channel(1001,1)";
this.warnonerror_ = 0;
this.aggregationstatus_ = false;
this.missingdata_ = false;
}
public string QueryString {
get {
NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
queryString["name_"] = this.name_;
queryString["tags_"] = String.Join(" ",this.tags_);
queryString["priority_"] = this.priority_.ToString();
queryString["intervalgroup"] = Convert.ToString(Convert.ToInt32(this.intervalgroup));
queryString["interval_"] = this.interval_;
queryString["inherittriggers"] = Convert.ToString(Convert.ToInt32(this.inherittriggers));
queryString["id"] = this.id.ToString();
queryString["sensortype"] = this.sensortype;
queryString["aggregationchannel_"] = this.aggregationchannel_;
queryString["warnonerror_"] = this.warnonerror_.ToString();
queryString["aggregationstatus_"] = Convert.ToString(Convert.ToInt32(this.aggregationstatus_));
queryString["missingdata_"] = Convert.ToString(Convert.ToInt32(this.missingdata_));
return queryString.ToString();
}
}
}
public class NewExeXml : PrtgSensorCreator {
public string exefile { get; set; }
public string exefile_ {
get {
if (!String.IsNullOrEmpty(this.exefile)) {
return this.exefile + "|" + this.exefile + "||";
} else {
return String.Empty;
}
}
}
public string exefilelabel { get; set; }
public string exeparams_ { get; set; }
public bool environment_ { get; set; }
public bool usewindowsauthentication_ { get; set; }
public string mutexname_ { get; set; }
public int timeout_ { get; set; }
public int writeresult_ { get; set; }
public NewExeXml () {
this.sensortype = "exexml";
this.environment_ = false;
this.usewindowsauthentication_ = false;
this.inherittriggers = true;
this.timeout_ = 60;
this.writeresult_ = 0;
this.name_ = "XML Custom EXE/Script Sensor";
this.tags_ = new string[] {"xmlexesensor"};
this.intervalgroup = true;
this.interval = 60;
}
public string QueryString {
get {
NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
queryString["name_"] = this.name_;
queryString["tags_"] = String.Join(" ",this.tags_);
queryString["priority_"] = this.priority_.ToString();
queryString["intervalgroup"] = Convert.ToString(Convert.ToInt32(this.intervalgroup));
queryString["interval_"] = this.interval_;
queryString["inherittriggers"] = Convert.ToString(Convert.ToInt32(this.inherittriggers));
queryString["id"] = this.id.ToString();
queryString["sensortype"] = this.sensortype;
queryString["exefile_"] = this.exefile_;
queryString["exefilelabel"] = this.exefilelabel;
queryString["exeparams_"] = this.exeparams_;
queryString["environment_"] = Convert.ToString(Convert.ToInt32(this.environment_));
queryString["usewindowsauthentication_"] = Convert.ToString(Convert.ToInt32(this.usewindowsauthentication_));
queryString["mutexname_"] = this.mutexname_;
queryString["timeout_"] = this.timeout_.ToString();
queryString["writeresult_"] = this.writeresult_.ToString();
return queryString.ToString();
}
}
}
public class NewPingSensor : PrtgSensorCreator {
public NewPingSensor () {
this.sensortype = "ping";
this.inherittriggers = true;
this.name_ = "Ping";
this.tags_ = new string[] {"prtgshell","pingsensor"};
this.intervalgroup = true;
this.interval = 30;
}
public string QueryString {
get {
NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
queryString["name_"] = this.name_;
queryString["tags_"] = String.Join(" ",this.tags_);
queryString["priority_"] = this.priority_.ToString();
queryString["intervalgroup"] = Convert.ToString(Convert.ToInt32(this.intervalgroup));
queryString["interval_"] = this.interval_;
queryString["inherittriggers"] = Convert.ToString(Convert.ToInt32(this.inherittriggers));
queryString["id"] = this.id.ToString();
queryString["sensortype"] = this.sensortype;
return queryString.ToString();
}
}
}
public class NewSnmpTrafficSensor : PrtgSensorCreator {
public int interfacenumber_ { get; set; }
public int stack_ { get; set; }
// "interfacenumber__check" = "$InterfaceNumber`:$Name|$Name|Connected|1 GBit/s|Ethernet|1|$Name|1000000000|3|2|" # don't know what the 3|2 are, or if the other bits matter
private string interfacenumber__check {
get {
string interfacenumberlabel = this.interfacenumber_.ToString();
interfacenumberlabel += ":" + this.name_ + "|" + this.name_;
interfacenumberlabel += "Connected|1 GBit/s|Ethernet|1|" + this.name_ + "|1000000000|3|2|";
return interfacenumberlabel;
}
}
//string interfacenumber__check = this.interfacenumber_.ToString();
//interfacenumber__check += ":" + this.name_ + "|" + this.name_;
//interfacenumber__check += "Connected|1 GBit/s|Ethernet|1|" + this.name_ + "|1000000000|3|2|";
public NewSnmpTrafficSensor () {
this.sensortype = "snmptraffic";
this.inherittriggers = true;
this.name_ = "Snmp Traffic Sensor";
this.tags_ = new string[] {"prtgshell","snmptrafficsensor","bandwidthsensor"};
this.intervalgroup = true;
this.interval = 60;
}
public string QueryString {
get {
NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
queryString["name_"] = this.name_;
queryString["tags_"] = String.Join(" ",this.tags_);
queryString["priority_"] = this.priority_.ToString();
queryString["intervalgroup"] = Convert.ToString(Convert.ToInt32(this.intervalgroup));
queryString["interval_"] = this.interval_;
queryString["inherittriggers"] = Convert.ToString(Convert.ToInt32(this.inherittriggers));
queryString["id"] = this.id.ToString();
queryString["sensortype"] = this.sensortype;
queryString["interfacenumber_"] = this.interfacenumber_.ToString();
queryString["interfacenumber__check"] = this.interfacenumber__check;
queryString["namein_"] = "Traffic In";
queryString["nameout_"] = "Traffic Out";
queryString["namesum_"] = "Traffic Total";
queryString["stack_"] = this.stack_.ToString();
return queryString.ToString();
}
}
}
/*
"name_" = $Name
"tags_" = "prtgshell snmptrafficsensor bandwidthsensor $Tags"
"priority_" = $Priority
"intervalgroup" = 1
"interval_" = "$Interval|$Interval seconds"
"inherittriggers" = 1
"id" = $ParentId
"sensortype" = "snmptraffic"
"interfacenumber_" = 1
"interfacenumber__check" = "$InterfaceNumber`:$Name|$Name|Connected|1 GBit/s|Ethernet|1|$Name|1000000000|3|2|" # don't know what the 3|2 are, or if the other bits matter
"namein_" = "Traffic In"
"nameout_" = "Traffic Out"
"namesum_" = "Traffic Total"
"stack_" = 0
*/
public class PrtgBaseObject {
public int objid { get; set; }
public string name { get; set; }
}
public class PrtgObject : PrtgBaseObject {
// all of the properties and methods here are used in
// probes, groups, devices, and sensors
// these datatypes need to be refined
private int priority = 3;
public string type { get; set; }
public string tags { get; set; }
public string active { get; set; }
public string probe { get; set; }
public string notifiesx { get; set; }
public string intervalx { get; set; }
public string access { get; set; }
public string dependency { get; set; }
public string probegroupdevice { get; set; }
public string status { get; set; }
public string message { get; set; }
public int Priority {
get {
return this.priority;
}
set {
if (value >= 0 && value <= 5) {
this.priority = value;
} else {
throw new ArgumentOutOfRangeException("Invalid value. Value must be between 0 and 5");
}
}
}
public string upsens { get; set; }
public string downsens { get; set; }
public string downacksens { get; set; }
public string partialdownsens { get; set; }
public string warnsens { get; set; }
public string pausedsens { get; set; }
public string unusualsens { get; set; }
public string undefinedsens { get; set; }
public string totalsens { get; set; }
public string favorite { get; set; }
public string schedule { get; set; }
public string comments { get; set; }
public string basetype { get; set; }
public string baselink { get; set; }
public string parentid { get; set; }
}
public class PrtgProbe : PrtgObject {
public string condition { get; set; }
public string fold { get; set; }
public string groupnum { get; set; }
public string devicenum { get; set; }
}
public class PrtgGroup : PrtgProbe {
public string group { get; set; }
public string location { get; set; }
}
public class PrtgDevice : PrtgObject {
public string device { get; set; }
public string group { get; set; }
public string grpdev { get; set; }
public string deviceicon { get; set; }
public string host { get; set; }
public string icon { get; set; }
public string location { get; set; }
}
public class PrtgSensor : PrtgObject {
public string device { get; set; }
public string group { get; set; }
public string grpdev { get; set; }
public string downtime { get; set; }
public string downtimetime { get; set; }
public string downtimesince { get; set; }
public string uptime { get; set; }
public string uptimetime { get; set; }
public string uptimesince { get; set; }
public string knowntime { get; set; }
public string cumsince { get; set; }
public string sensor { get; set; }
public string interval { get; set; }
public string lastcheck { get; set; }
public string lastup { get; set; }
public string lastdown { get; set; }
public string lastvalue { get; set; }
public string lastvalue_raw { get; set; }
public string minigraph { get; set; }
}
public class PrtgChannel : PrtgBaseObject {
public string lastvalue { get; set; }
public decimal lastvalue_raw { get; set; }
}
public class PrtgTodo : PrtgBaseObject {
public string datetime { get; set; }
public decimal status { get; set; }
public string priority { get; set; }
public decimal message { get; set; }
public decimal active { get; set; }
}
public class PrtgMessage : PrtgBaseObject {
public string datetime { get; set; }
public decimal parent { get; set; }
public string type { get; set; }
public decimal status { get; set; }
public decimal message { get; set; }
}
public class PrtgValue {
public string datetime { get; set; }
public decimal value_ { get; set; }
public string coverage { get; set; }
}
public class PrtgHistory {
public string datetime { get; set; }
public decimal dateonly { get; set; }
public string timeonly { get; set; }
public string user { get; set; }
public string message { get; set; }
}
public class PrtgStoredReport : PrtgBaseObject {
public string datetime { get; set; }
public decimal size { get; set; }
}
public class PrtgReport : PrtgBaseObject {
public string template { get; set; }
public decimal period { get; set; }
public string schedule { get; set; }
public decimal email { get; set; }
public decimal lastrun { get; set; }
public decimal nextrun { get; set; }
}
public class PrtgDeviceCreator {
public string name_ { get; set; }
public string host_ { get; set; }
public string[] tags_ { get; set; }
public int id { get; set; }
public string deviceicon_ { get; set; }
//public int discoverytype_ = 0;
//public int discoveryschedule_ = 0;
public string discoverytype_ { get; set; }
public string devicetemplate_ { get; set; }
public string devicetemplate__check { get; set; }
public string QueryString {
get {
NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
queryString["id"] = this.id.ToString();
queryString["name_"] = this.name_;
queryString["host_"] = this.host_;
queryString["deviceicon_"] = this.deviceicon_;
queryString["tags_"] = String.Join(" ",this.tags_);
//queryString["discoverytype_"] = Convert.ToString(Convert.ToInt32(this.discoverytype_));
//queryString["discoveryschedule_"] = Convert.ToString(Convert.ToInt32(this.discoveryschedule_));
if (!string.IsNullOrEmpty(this.discoverytype_)) { queryString["discoverytype_"] = this.discoverytype_; }
if (!string.IsNullOrEmpty(this.devicetemplate_)) { queryString["devicetemplate_"] = this.devicetemplate_; }
if (!string.IsNullOrEmpty(this.devicetemplate__check)) { queryString["devicetemplate__check"] = this.devicetemplate__check; }
return queryString.ToString();
}
}
public PrtgDeviceCreator () {
this.deviceicon_ = "a_server_1.png";
this.tags_ = new string[] {""};
}
}
public class PrtgGroupCreator {
public string name_ { get; set; }
public string[] tags_ { get; set; }
public int id { get; set; }
public string QueryString {
get {
NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
queryString["id"] = this.id.ToString();
queryString["name_"] = this.name_;
queryString["tags_"] = String.Join(" ",this.tags_);
return queryString.ToString();
}
}
public PrtgGroupCreator () {
this.tags_ = new string[] {""};
}
}
public class PrtgSensorCreator {
// this is the class that will be created and populated to validate sensor creation
// is there really a point to having these things obfuscate the names
// http://stackoverflow.com/questions/2605268/reverse-function-of-httputility-parsequerystring
// this should have a method that uses the data you've given it to create the query string
// the trick to this is that the main class (this class) will never know what all it should include
// ... but the inherited classes will
// so is it possible to define a method here that somehow uses information defined in the inherited classes
// that then produces the correct, complete query string?
// how this thing should work:
// the creator contains all the base objects that all sensors get
// "name_" = $PrtgObject.Name
// "tags_" = $PrtgObject.Tags
// "priority_" = $PrtgObject.Priority
// "intervalgroup" = 1
// "interval_" = "60|60 seconds"
// "inherittriggers" = 1
// "id" = $PrtgObject.ParentId
// "sensortype" = "exexml"
// it will also include some methods that they will all need
// such as "CreateQueryString" which is what the http post command needs
// there will then be various derived classes that will inherit this down
private int sensor_priority = 3;
private bool inherit_interval = true;
private int polling_interval = 60;
//public Hashtable QueryString = new Hashtable();
public string name_ { get; set; }
public string[] tags_ { get; set; }
public string sensortype { get; set; }
public int id { get; set; }
public int priority_ {
get {
return this.sensor_priority;
}
set {
if (value >= 0 && value <= 5) {
this.sensor_priority = value;
} else {
throw new ArgumentOutOfRangeException("Invalid value. Value must be between 0 and 5");
}
}
}
public bool inherittriggers { get; set; }
public bool intervalgroup {
get {
return this.inherit_interval;
}
set {
this.inherit_interval = value;
}
}
public string interval_ {
get {
return this.polling_interval.ToString() + "|" + ToTimeString(this.polling_interval);
}
}
public int interval {
get {
return this.polling_interval;
}
set {
this.polling_interval = value;
}
}
private string ToTimeString(int InputSeconds) {
if (((InputSeconds % 86400) == 0) && (InputSeconds / 86400 != 1)) {
return (InputSeconds / 86400).ToString() + " days";
} else if (((InputSeconds % 3600) == 0) && (InputSeconds / 3600 != 1)) {
return (InputSeconds / 3600).ToString() + " hours";
} else if (((InputSeconds % 60) == 0) && (InputSeconds / 60 != 1)) {
return (InputSeconds / 60).ToString() + " minutes";
} else {
return InputSeconds.ToString() + " seconds";
}
}
}
public class PrtgServer {
// can we rewrite the helper functions as methods in this class?
private DateTime clock;
private Stack<string> urlhistory = new Stack<string>();
private string prtgshellversion = "2.0";
public string Server { get; set; }
public int Port { get; set; }
public string UserName { get; set; }
public string PassHash { get; set; }
public string Protocol { get; set; }
public string ApiUrl {
get {
if (!string.IsNullOrEmpty(this.Protocol) && !string.IsNullOrEmpty(this.Server) && this.Port > 0) {
return this.Protocol + "://" + this.Server + ":" + this.Port + "/";
} else {
return null;
}
}
}
public string AuthString {
get {
if (!string.IsNullOrEmpty(this.UserName) && !string.IsNullOrEmpty(this.PassHash)) {
return "username=" + this.UserName + "&passhash=" + this.PassHash;
} else {
return null;
}
}
}
public string PrtgShellVersion {
get {
return prtgshellversion;
}
}
public int NewMessages { get; set; }
public int NewAlarms { get; set; }
public int Alarms { get; set; }
public int AckAlarms { get; set; }
public int NewToDos { get; set; }
public string Clock {
get {
return this.clock.ToString();
}
set {
this.clock = DateTime.Parse(value);
}
}
public DateTime ClockasDateTime {
get {
return this.clock;
}
set {
this.clock = value;
}
}
public string ActivationStatusMessage { get; set; }
public int BackgroundTasks { get; set; } // misc background tasks (not autodiscovery, maybe?)
public int CorrelationTasks { get; set; } // similar sensors analysis
public int AutoDiscoTasks { get; set; } // running autodiscoveries
public string Version { get; set; }
public bool PRTGUpdateAvailable { get; set; }
public bool IsAdminUser { get; set; }
public bool IsCluster { get; set; }
public bool ReadOnlyUser { get; set; }
public bool ReadOnlyAllowAcknowledge { get; set; }
public bool RawFormattingError { get; set; }
public string[] UrlHistory {
get {
return this.urlhistory.ToArray();
}
}
public void FlushHistory() {
this.urlhistory.Clear();
}
public string UrlBuilder(string Action) {
if (Action.StartsWith("/")) Action = Action.Substring(1);
string[] Pieces = new string[4];
Pieces[0] = this.ApiUrl;
Pieces[1] = Action;
Pieces[2] = "?";
Pieces[3] = this.AuthString;
string CompletedString = string.Join("", Pieces);
this.urlhistory.Push(CompletedString);
return CompletedString;
}
// i'm not confident that this is actually used anywhere
public string UrlBuilder(string Action, string[] QueryParameters) {
if (Action.StartsWith("/")) Action = Action.Substring(1);
string[] Pieces = new string[4];
Pieces[0] = this.ApiUrl;
Pieces[1] = Action;
Pieces[2] = "?";
Pieces[3] = this.AuthString;
var FullString = new string[Pieces.Length + QueryParameters.Length];
Pieces.CopyTo(FullString, 0);
QueryParameters.CopyTo(FullString, Pieces.Length);
string CompletedString = string.Join("", FullString);
this.urlhistory.Push(CompletedString);
return CompletedString;
}
public string UrlBuilder(string Action, Hashtable QueryParameters) {
if (Action.StartsWith("/")) Action = Action.Substring(1);
string[] Pieces = new string[5];
Pieces[0] = this.ApiUrl;
Pieces[1] = Action;
Pieces[2] = "?";
Pieces[3] = this.AuthString;
// this little bit of awesome handles query string parameters that
// have multiple entries with the same key name, which obviously
// hashtables do not natively support. this detects values that are
// not singleton strings or ints, and blows up the array.
foreach (DictionaryEntry KeyPair in QueryParameters) {
if (KeyPair.Value.GetType() == typeof(string) || KeyPair.Value.GetType() == typeof(int)) {
Pieces[4] += ("&" + KeyPair.Key + "=" + KeyPair.Value);
} else {
string[] ConvertedArray = ((IEnumerable)KeyPair.Value).Cast<object>().Select(x => x.ToString()).ToArray();
foreach (string SubValue in ConvertedArray) {
Pieces[4] += ("&" + KeyPair.Key + "=" + SubValue);
}
}
}
string CompletedString = string.Join("", Pieces);
this.urlhistory.Push(CompletedString);
return CompletedString;
}
private static bool OnValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
return true;
}
public void OverrideValidation() {
ServicePointManager.ServerCertificateValidationCallback = OnValidateCertificate;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
}
private System.Uri prtguri;
// this likely doesn't need to be public
// or exist, this is just for peeking
//public System.Uri PrtgUri {
// get { return this.prtguri; }
//}
private Hashtable parsed_querystring;
public void SetPrtgUri(string serverstring) {
this.prtguri = new System.Uri(serverstring);
this.Server = this.prtguri.Host;
this.Port = this.prtguri.Port;
this.Protocol = this.prtguri.Scheme;
NameValueCollection querystring_nvc = HttpUtility.ParseQueryString(this.prtguri.Query);
this.parsed_querystring = new Hashtable();
foreach (string key in querystring_nvc) {
this.parsed_querystring.Add(key, querystring_nvc[key]);
}
// this syntax is all wrong
// if the hashtable includes these two values, set them
//if (this.parsed_querystring.username) {
// this.UserName = this.parsed_querystring.username;
//}
//if (this.parsed_querystring.passhash) {
// this.PassHash = this.parsed_querystring.passhash;
//}
}
public HttpQueryReturnObject HttpQuery(string Url, bool AsXml = true) {
// this works. there's some logic missing from the original powershell version of this
// that may or may not be important (it was error handling of some flavor)
// also, all requests should not be treated as XML for this to be more generic
// (the powershell version had an "-asxml" flag to handle this)
this.OverrideValidation();
HttpWebResponse Response = null;
HttpStatusCode StatusCode = new HttpStatusCode();
try {
HttpWebRequest Request = WebRequest.Create(Url) as HttpWebRequest;
//if (Response.ContentLength > 0) {
try {
Response = Request.GetResponse() as HttpWebResponse;
StatusCode = Response.StatusCode;
} catch (WebException we) {
StatusCode = ((HttpWebResponse)we.Response).StatusCode;
}
string DetailedError = Response.GetResponseHeader("X-Detailed-Error");
// }
} catch {
throw new HttpException("httperror");
}
if (Response.StatusCode.ToString() == "OK") {
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string Result = Reader.ReadToEnd();
XmlDocument XResult = new XmlDocument();
if (AsXml) {
XResult.LoadXml(Result);
}
Reader.Close();
Response.Close();
HttpQueryReturnObject ReturnObject = new HttpQueryReturnObject();
ReturnObject.Statuscode = StatusCode;
if (AsXml) { ReturnObject.Data = XResult; }
ReturnObject.RawData = Result;
return ReturnObject;
} else {
throw new HttpException("httperror");