-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathSettingsClass.cs
More file actions
1675 lines (1486 loc) · 70.1 KB
/
SettingsClass.cs
File metadata and controls
1675 lines (1486 loc) · 70.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Xml;
using System.Collections;
using System.Drawing;
using System.ComponentModel;
namespace SpindleTalker2
{
public static class Settings
{
private static Settings4Net _settings = new Settings4Net();
private static string settingsFile;
#region Setup MDI Forms
public static MainWindow spindleTalkerBase = null;
public static MeterControl graphsForm = new MeterControl();
public static TerminalControl terminalForm = new TerminalControl();
public static SettingsControl settingsForm = new SettingsControl();
#endregion
static Settings()
{
string settingsDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SpindleTalker2");
if (!Directory.Exists(settingsDir)) Directory.CreateDirectory(settingsDir);
settingsFile = Path.Combine(settingsDir, "settings.xml");
Console.WriteLine(settingsFile);
if (File.Exists(settingsFile))
_settings.Open(settingsFile);
_VFD_MaxFreq = -1;
_VFD_MinFreq = -1;
_VFD_MaxRPM = -1;
}
public static bool SerialConnected
{
get { return _serialConnected;}
set
{
_serialConnected = value;
if(spindleTalkerBase != null)
{
spindleTalkerBase.COMPortStatus(value);
}
}
}
private static bool _serialConnected;
public static string PortName
{
get { return _settings.GetItemOrDefaultValue("PortName", "COM1").ToString(); }
set { _settings.Settings["PortName"] = value; }
}
public static int BaudRate
{
get { return Convert.ToInt32(_settings.GetItemOrDefaultValue("BaudRate", 9600)); }
set { _settings.Settings["BaudRate"] = value.ToString(); }
}
public static int DataBits
{
get { return Convert.ToInt32(_settings.GetItemOrDefaultValue("DataBits", 8)); }
set { _settings.Settings["DataBits"] = value.ToString(); }
}
public static Parity Parity
{
get { return (Parity)Enum.Parse(typeof(Parity), _settings.GetItemOrDefaultValue("Parity", "None").ToString()); }
set { _settings.Settings["Parity"] = value.ToString(); }
}
public static StopBits StopBits
{
get { return (StopBits)Enum.Parse(typeof(StopBits), _settings.GetItemOrDefaultValue("StopBits", 1).ToString()); }
set { _settings.Settings["StopBits"] = value.ToString(); }
}
public static bool AutoConnectAtStartup
{
get { return Convert.ToBoolean(_settings.GetItemOrDefaultValue("AutoConnectAtStartup", false)); }
set { _settings.Settings["AutoConnectAtStartup"] = value.ToString(); }
}
public static string LastMDIChild
{
get { return _settings.GetItemOrDefaultValue("LastMDIChild", "Graphs").ToString(); }
set { _settings.Settings["LastMDIChild"] = value; }
}
public static int VFD_MinFreq
{
get { return _VFD_MinFreq; }
set
{
_VFD_MinFreq = value;
Settings.settingsForm.labelMinMaxFreq.Text = string.Format("Min/Max Frequency = {0}Hz/{1}Hz", _VFD_MinFreq, _VFD_MaxFreq);
}
}
private static int _VFD_MinFreq;
public static int VFD_MaxFreq
{
get { return _VFD_MaxFreq; }
set
{
_VFD_MaxFreq = value;
Settings.graphsForm.MeterOutF.ScaleMaxValue = _VFD_MaxFreq;
Settings.graphsForm.MeterSetF.ScaleMaxValue = _VFD_MaxFreq;
Settings.settingsForm.labelMinMaxFreq.Text = string.Format("Min/Max Frequency = {0}Hz / {1}Hz",_VFD_MinFreq, _VFD_MaxFreq);
}
}
private static int _VFD_MaxFreq;
public static int VFD_MaxRPM
{
get { return _VFD_MaxRPM; }
set
{
_VFD_MaxRPM = value;
Settings.graphsForm.MeterRPM.ScaleMaxValue = _VFD_MaxRPM;
Settings.graphsForm.MeterRPM.ScaleMaxValue = _VFD_MaxRPM;
Settings.settingsForm.labelMaxRPM.Text = string.Format("Maximum speed = {0:#,##0}RPM", _VFD_MaxRPM);
}
}
private static int _VFD_MaxRPM;
public static int VFD_MinRPM
{
get
{
if (VFD_MaxFreq > 0 && VFD_MaxRPM > 0)
{
int minRPM = (int)(((double)VFD_MaxRPM / (double)VFD_MaxFreq) * (double)VFD_MinFreq);
return minRPM;
}
else return 0;
}
set { ; }
}
public static int VFD_ModBusID
{
get { return Convert.ToInt32(_settings.GetItemOrDefaultValue("VFD_ModBusID", 1)); }
set { _settings.Settings["VFD_ModBusID"] = value.ToString(); }
}
public static string QuickSets
{
get { return _settings.GetItemOrDefaultValue("QuickSets", "6000;9000;15000;20000;24000").ToString(); }
set { _settings.Settings["QuickSets"] = value; }
}
public static void Save()
{
_settings.Save(settingsFile);
}
public static void ClearVFDSettings()
{
VFD_MaxFreq = -1;
VFD_MinFreq = -1;
VFD_MaxRPM = -1;
}
}
#region Settings4Net
#region Property Grid generation related code (PropertyContainer/PropertyDescriptor)
#pragma warning disable 1591
[System.Diagnostics.DebuggerNonUserCode]
public class PropertyContainer : Dictionary<string, object>, ICustomTypeDescriptor
{
public PropertyContainer()
{
}
#region Fields
Dictionary<string, Property> propertiesDefinition = new Dictionary<string, Property>();
#endregion
public void AddProperty(Property property)
{
this.propertiesDefinition.Add(property.Name, property);
}
#region ICustomTypeDescriptor Members
public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); }
public string GetClassName() { return TypeDescriptor.GetClassName(this, true); }
public string GetComponentName() { return TypeDescriptor.GetComponentName(this); }
public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); }
public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); }
public object GetEditor(System.Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); }
public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); }
public EventDescriptorCollection GetEvents(System.Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); }
public EventDescriptorCollection GetEvents() { return TypeDescriptor.GetEvents(this, true); }
public object GetPropertyOwner(PropertyDescriptor pd) { return this; }
public PropertyDescriptorCollection GetProperties(System.Attribute[] attributes) { return GetProperties(); }
public PropertyDescriptorCollection GetProperties()
{
PropertyDescriptorCollection pdc = new PropertyDescriptorCollection(null);
foreach (KeyValuePair<string, object> prop in this)
{
Property property;
if (this.propertiesDefinition.TryGetValue(prop.Key, out property))
pdc.Add(property);
}
return pdc;
}
#endregion
}
[System.Diagnostics.DebuggerNonUserCode]
public class Property : PropertyDescriptor
{
static public SettingsHashtable Settings;
#region Fields
private Type type;
private bool readOnly;
public string _description;
public string _category;
public bool? _visible = null;
#endregion
public Property(string name, Type type, bool readOnly, string description, string category, bool? visible)
: base(name, null)
{
this.type = type;
this.readOnly = readOnly;
this._description = description;
this._category = category;
this._visible = visible;
}
public override bool IsReadOnly { get { return this.readOnly; } }
public override Type PropertyType { get { return this.type; } }
public override Type ComponentType { get { throw new NotImplementedException(); } }
public override string DisplayName { get { return this.Name; } }
public override bool CanResetValue(object component) { return false; }
public override void ResetValue(object component) { }
public override bool ShouldSerializeValue(object component) { return true; }
public override string Description { get { return this._description; } }
public override string Category { get { return this._category; } }
public override bool IsBrowsable
{
get
{
if (_visible == null)
return true;
return _visible.Value;
}
}
public override object GetValue(object component)
{
PropertyContainer container = component as PropertyContainer;
if (container == null)
throw new Exception("Invalid component type");
return container[Name];
}
public override void SetValue(object component, object value)
{
if (this.readOnly)
throw new InvalidOperationException();
PropertyContainer container = component as PropertyContainer;
if (container == null)
throw new Exception("Invalid component type");
container[Name] = value;
Settings[Name] = value;
}
}
#pragma warning restore 1591
#endregion
/// <summary>
/// Class containing meta data of Settings item
/// </summary>
public class SettingsMetaData
{
/// <summary>
/// Settings item description
/// </summary>
public string Description = String.Empty;
/// <summary>
/// Settings item category
/// </summary>
public string Category = String.Empty;
/// <summary>
/// Settings item tag - could be used freely to identify object
/// </summary>
public string Tag = String.Empty;
/// <summary>
/// Settings item visibility - shows/hides it in PropertyGrid control
/// </summary>
public bool? Visible = null;
/// <summary>
/// SettingsMetaData Contructor
/// </summary>
/// <param name="Description">Settings item description</param>
/// <param name="Category">Settings item category</param>
/// <param name="Tag">Settings item tag</param>
/// <param name="Visible">Settings item visibility</param>
public SettingsMetaData(string Description, string Category, string Tag, bool? Visible)
{
this.Description = Description ?? String.Empty;
this.Category = Category ?? String.Empty;
this.Tag = Tag ?? String.Empty;
this.Visible = Visible;
}
/// <summary>
/// SettingsMetaData Constructor (creates default empty values)
/// </summary>
public SettingsMetaData()
{
}
}
/// <summary>
/// Class for storing and handling a single Settings' item
/// </summary>
/// <typeparam name="T">Generic type</typeparam>
public class Item<T>
{
/// <summary>
/// Contructor
/// </summary>
/// <param name="Name">Name of the settings item</param>
/// <param name="Value">Value of the settings item</param>
/// <param name="ModifiedDate">Date/Time of last modification</param>
/// <param name="Readonly">Writing/changing permissions</param>
/// <param name="MinValue">Minimum allowed value</param>
/// <param name="MaxValue">Maximum allowed value</param>
/// <param name="Default">Default value</param>
/// <param name="MetaData">MetaData object</param>
public Item(string Name, T Value, DateTime? ModifiedDate, bool? Readonly, T MinValue, T MaxValue, T Default, SettingsMetaData MetaData)
{
this.Name = Name;
this.Value = Value;
this.ModifiedDate = ModifiedDate;
this.Readonly = Readonly;
this.MinValue = MinValue;
this.MaxValue = MaxValue;
this.Default = Default;
if (MetaData != null)
this.MetaData = MetaData;
}
private SettingsMetaData _metaData = new SettingsMetaData();
public SettingsMetaData MetaData
{
set
{
_metaData = value;
}
get
{
return _metaData;
}
}
/// <summary>
/// Name of the settings item
/// </summary>
public string Name { set; get; }
private T _value = default(T);
/// <summary>
/// Value of the settings item. Has to be not null, not readonly and (if set) between [MinValue; MaxValue]
/// </summary>
public T Value
{
set
{
if (value != null && (Readonly == null || Readonly.Value == false))
{
bool ok = true;
if (value is int?)
{
if (MinValue != null && (MinValue as int?).Value > (value as int?).Value)
ok = false;
if (MaxValue != null && (MaxValue as int?).Value < (value as int?).Value)
ok = false;
}
else if (value is double?)
{
if (MinValue != null && (MinValue as double?).Value > (value as double?).Value)
ok = false;
if (MaxValue != null && (MaxValue as double?).Value < (value as double?).Value)
ok = false;
}
else if (value is double?)
{
if (MinValue != null && (MinValue as DateTime?).Value > (value as DateTime?).Value)
ok = false;
if (MaxValue != null && (MaxValue as DateTime?).Value < (value as DateTime?).Value)
ok = false;
}
if (ok)
_value = value;
}
}
get
{
return _value;
}
}
/// <summary>
/// Last modification date/time
/// </summary>
public DateTime? ModifiedDate { set; get; }
/// <summary>
/// Permission to change the Value
/// </summary>
public bool? Readonly { set; get; }
private T _minvalue = default(T);
/// <summary>
/// Minimum allowed value (for int/double/DateTime typs) or null
/// </summary>
public T MinValue
{
set
{
if (value != null && (value is int? || value is double? || value is DateTime?))
_minvalue = value;
}
get { return _minvalue; }
}
private T _maxvalue = default(T);
/// <summary>
/// Maximum allowed value (for int/double/DateTime typs) or null
/// </summary>
public T MaxValue
{
set
{
if (value != null && (value is int? || value is double? || value is DateTime?))
_maxvalue = value;
}
get { return _maxvalue; }
}
/// <summary>
/// Default nullable value of the settings item
/// </summary>
public T Default { set; get; }
}
/// <summary>
/// Class for storing Settings items
/// </summary>
[Serializable]
public class SettingsHashtable : Hashtable
{
/// <summary>
/// Adds a new Settings item
/// </summary>
/// <param name="key">Settings item name</param>
/// <param name="value">Settings item value</param>
public override void Add(object key, object value)
{
base[key] = value;
}
/// <summary>
/// Returns the whole Settings Item object
/// </summary>
/// <param name="key">Item key in the hashtable</param>
/// <param name="argument">Additional internal argument</param>
/// <returns>Item object</returns>
public object this[object key, object argument]
{
get
{
return base[key];
}
// not set
private set
{
}
}
/// <summary>
/// Settings items
/// </summary>
/// <param name="key">Settings item name</param>
/// <returns>Settings item value</returns>
public override object this[object key]
{
get
{
if (base[key] == null)
throw new Exception("Item doesn't exist.");
if (base[key] is Item<int?>)
return ((base[key] as Item<int?>).Value).Value;
else if (base[key] is Item<string>)
return (base[key] as Item<string>).Value;
else if (base[key] is Item<bool?>)
return (base[key] as Item<bool?>).Value;
else if (base[key] is Item<double?>)
return (base[key] as Item<double?>).Value;
else if (base[key] is Item<Color?>)
return (base[key] as Item<Color?>).Value;
else if (base[key] is Item<DateTime?>)
return (base[key] as Item<DateTime?>).Value;
else if (base[key] is Item<Font>)
return (base[key] as Item<Font>).Value;
return null;
}
set
{
if (base[key] == null)
{
if (value is int)
base[key] = new Item<int?>(key.ToString(), (int)value, null, null, null, null, null, null);
else if (value is string)
base[key] = new Item<string>(key.ToString(), (string)value, null, null, null, null, null, null);
else if (value is bool)
base[key] = new Item<bool?>(key.ToString(), (bool)value, null, null, null, null, null, null);
else if (value is double)
base[key] = new Item<double?>(key.ToString(), (double)value, null, null, null, null, null, null);
else if (value is Color)
base[key] = new Item<Color?>(key.ToString(), (Color)value, null, null, null, null, null, null);
else if (value is DateTime)
base[key] = new Item<DateTime?>(key.ToString(), (DateTime)value, null, null, null, null, null, null);
else if (value is Font)
base[key] = new Item<Font>(key.ToString(), (Font)value, null, null, null, null, null, null);
}
else
{
if (base[key] is Item<int?>)
((Item<int?>)base[key]).Value = (int?)value;
else if (base[key] is Item<string>)
((Item<string>)base[key]).Value = (string)value;
else if (base[key] is Item<bool?>)
((Item<bool?>)base[key]).Value = (bool)value;
else if (base[key] is Item<double?>)
((Item<double?>)base[key]).Value = (double)value;
else if (base[key] is Item<Color>)
((Item<Color?>)base[key]).Value = (Color)value;
else if (base[key] is Item<DateTime>)
((Item<DateTime?>)base[key]).Value = (DateTime)value;
else if (base[key] is Item<Font>)
(base[key] as Item<Font>).Value = (Font)value;
}
}
}
}
/// <summary>
/// Class for handling and manipulating Settings items
/// </summary>
public class Settings4Net
{
/// <summary>
/// Collection of Settings Items
/// </summary>
public SettingsHashtable Settings = new SettingsHashtable();
/// <summary>
/// Gets or sets an option for tracking date/time of last settings item modification
/// </summary>
public bool TrackModificationTimes { get; set; }
/// <summary>
/// Gets or sets an option to perform checksums on settings file to prevent manual editing of the file
/// </summary>
public bool PreventManualModifications { get; set; }
/// <summary>
/// Indicates if Settings were loaded from the file
/// </summary>
public bool IsLoaded
{
get;
private set;
}
/// <summary>
/// Indicates if Settings file was modified manually
/// </summary>
public bool WasModifiedManually
{
get;
private set;
}
/// <summary>
/// Checksum of the loaded file
/// </summary>
private string FileChecksum = "";
#region InternalClassProperties
private string _xml_version = "1.0";
private string _xml_encoding = "utf-8";
private string _magic_salt = "RG_Setting4Net";
#endregion
/// <summary>
/// Opens and reads settings from specified file
/// </summary>
/// <param name="filename">Settings file</param>
/// <returns>Status of the operation</returns>
public bool Open(string filename)
{
return Open(filename, PreventManualModifications, false); ;
}
/// <summary>
/// Opens and reads settings from specified file
/// </summary>
/// <param name="filename">Settings file</param>
/// <param name="PreventManualModifications">If set to true, prevents loading settings if the file was manually modified</param>
/// <returns>Status of the operation</returns>
public bool Open(string filename, bool PreventManualModifications)
{
return Open(filename, PreventManualModifications, false);
}
/// <summary>
/// Opens and reads settings from specified file
/// </summary>
/// <param name="filename">Settings file</param>
/// <param name="PreventManualModifications">If true, prevents loading settings if the file was manually modified</param>
/// <param name="AppendSettings">If true, appends settings from specified file to already existing ones instead of overwriting</param>
/// <returns></returns>
public bool Open(string filename, bool PreventManualModifications, bool AppendSettings)
{
IsLoaded = false;
bool res = false;
if (!AppendSettings)
Settings.Clear();
try
{
res = ParseXmlFile(filename);
}
catch (Exception)
{
return false;
}
if (res && PreventManualModifications && (CalculateChecksumValue() != FileChecksum))
{
Settings.Clear();
return false;
}
this.PreventManualModifications = PreventManualModifications;
IsLoaded = res;
return res;
}
/// <summary>
/// Saves all Settings to specified file
/// </summary>
/// <param name="filename">Output file</param>
public void Save(string filename)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.AppendChild(xmldoc.CreateXmlDeclaration(_xml_version, _xml_encoding, null));
XmlElement xmlRoot = xmldoc.CreateElement("settings");
xmldoc.AppendChild(xmlRoot);
string iname, ivalue, itype;
bool? ireadonly;
string imin = null, imax = null, idefault = null;
foreach (string key in Settings.Keys)
{
object setting = Settings[key, true];
SettingsMetaData imeta;
if (setting is Item<int?>)
{
itype = "int";
iname = (setting as Item<int?>).Name;
ireadonly = (setting as Item<int?>).Readonly;
ivalue = (setting as Item<int?>).Value.ToString();
imin = (setting as Item<int?>).MinValue == null ? null : (setting as Item<int?>).MinValue.Value.ToString();
imax = (setting as Item<int?>).MaxValue == null ? null : (setting as Item<int?>).MaxValue.Value.ToString();
idefault = (setting as Item<int?>).Default == null ? null : (setting as Item<int?>).Default.Value.ToString();
imeta = (setting as Item<int?>).MetaData;
}
else if (setting is Item<bool?>)
{
itype = "bool";
iname = (setting as Item<bool?>).Name;
ireadonly = (setting as Item<bool?>).Readonly;
ivalue = (setting as Item<bool?>).Value.ToString();
idefault = (setting as Item<bool?>).Default == null ? null : (setting as Item<bool?>).Default.ToString();
imeta = (setting as Item<bool?>).MetaData;
}
else if (setting is Item<double?>)
{
itype = "double";
iname = (setting as Item<double?>).Name;
ireadonly = (setting as Item<double?>).Readonly;
ivalue = (setting as Item<double?>).Value.ToString();
imin = (setting as Item<double?>).MinValue == null ? null : (setting as Item<double?>).MinValue.Value.ToString();
imax = (setting as Item<double?>).MaxValue == null ? null : (setting as Item<double?>).MaxValue.Value.ToString();
idefault = (setting as Item<double?>).Default == null ? null : (setting as Item<double?>).Default.Value.ToString();
imeta = (setting as Item<double?>).MetaData;
}
else if (setting is Item<Color?>)
{
itype = "color";
iname = (setting as Item<Color?>).Name;
ireadonly = (setting as Item<Color?>).Readonly;
ivalue = TypeDescriptor.GetConverter(typeof(Color)).ConvertToString((setting as Item<Color?>).Value);
idefault = TypeDescriptor.GetConverter(typeof(Color)).ConvertToString((setting as Item<Color?>).Default);
imeta = (setting as Item<Color?>).MetaData;
}
else if (setting is Item<DateTime?>)
{
itype = "datetime";
iname = (setting as Item<DateTime?>).Name;
ireadonly = (setting as Item<DateTime?>).Readonly;
ivalue = (setting as Item<DateTime?>).Value.ToString();
imin = (setting as Item<DateTime?>).MinValue == null ? null : (setting as Item<DateTime?>).MinValue.Value.ToString();
imax = (setting as Item<DateTime?>).MaxValue == null ? null : (setting as Item<DateTime?>).MaxValue.Value.ToString();
idefault = (setting as Item<DateTime?>).Default == null ? null : (setting as Item<DateTime?>).Default.Value.ToString();
imeta = (setting as Item<DateTime?>).MetaData;
}
else if (setting is Item<Font>)
{
itype = "font";
iname = (setting as Item<Font>).Name;
ireadonly = (setting as Item<Font>).Readonly;
ivalue = TypeDescriptor.GetConverter(typeof(Font)).ConvertToString((setting as Item<Font>).Value);
idefault = TypeDescriptor.GetConverter(typeof(Font)).ConvertToString((setting as Item<Font>).Default);
imeta = (setting as Item<Font>).MetaData;
}
else // string
{
itype = "string";
iname = (setting as Item<string>).Name;
ireadonly = (setting as Item<string>).Readonly;
ivalue = (setting as Item<string>).Value;
idefault = (setting as Item<string>).Default == null ? null : (setting as Item<string>).Default;
imeta = (setting as Item<string>).MetaData;
}
XmlElement element = xmldoc.CreateElement("item");
element.InnerText = ivalue;
element.SetAttribute("name", iname);
element.SetAttribute("type", itype);
if (ireadonly != null)
element.SetAttribute("readonly", ireadonly.Value.ToString());
if (imin != null)
element.SetAttribute("min", imin);
if (imax != null)
element.SetAttribute("max", imax);
if (idefault != null)
element.SetAttribute("default", idefault);
if (TrackModificationTimes)
element.SetAttribute("modified", DateTime.Now.ToString());
if (imeta != null)
{
if (imeta.Description != null && imeta.Description != String.Empty)
element.SetAttribute("description", imeta.Description);
if (imeta.Category != null && imeta.Category != String.Empty)
element.SetAttribute("category", imeta.Category);
if (imeta.Tag != null && imeta.Tag != String.Empty)
element.SetAttribute("tag", imeta.Tag);
if (imeta.Visible != null && imeta.Tag != String.Empty)
element.SetAttribute("tag", imeta.Tag);
}
xmlRoot.AppendChild(element);
}
// add checksum element
XmlElement checksumElement = xmldoc.CreateElement("checksum");
checksumElement.InnerText = CalculateChecksumValue();
xmlRoot.AppendChild(checksumElement);
try
{
xmldoc.Save(filename);
}
catch (Exception)
{
throw new Exception("Couldn't save settings to the specified file");
}
}
/// <summary>
/// Reads XML-Settings file contents
/// </summary>
/// <param name="filename">Input file</param>
/// <returns>Operation status</returns>
private bool ParseXmlFile(string filename)
{
XmlDocument xmldoc = new XmlDocument();
try
{
xmldoc.Load(filename);
}
catch (Exception)
{
return false;
}
foreach (XmlNode node in xmldoc.GetElementsByTagName("item"))
{
ParseANode(node);
}
XmlNodeList checksumNode = xmldoc.GetElementsByTagName("checksum");
if (checksumNode.Count != 1)
return false;
FileChecksum = checksumNode[0].InnerText;
return true;
}
/// <summary>
/// Parses and stores a single Settings item from XmlNode
/// </summary>
/// <param name="node">Input XML node</param>
private void ParseANode(XmlNode node)
{
string item_value = node.InnerText;
string item_name = node.Attributes["name"] == null ? null : node.Attributes["name"].Value;
if (item_name == null || item_name.Length <= 0)
throw new Exception("Corrupt XML file");
string item_type = node.Attributes["type"] == null ? String.Empty : node.Attributes["type"].Value;
string item_default = node.Attributes["default"] == null ? String.Empty : node.Attributes["default"].Value;
string item_min = node.Attributes["min"] == null ? String.Empty : node.Attributes["min"].Value;
string item_max = node.Attributes["max"] == null ? String.Empty : node.Attributes["max"].Value;
bool? item_readonly = null; bool tmp_b;
if (node.Attributes["readonly"] != null)
item_readonly = Boolean.TryParse(node.Attributes["readonly"].Value, out tmp_b) ? tmp_b : (bool?)null;
DateTime? item_modified = null; DateTime tmp_t;
if (node.Attributes["modified"] != null)
item_modified = DateTime.TryParse(node.Attributes["modified"].Value, out tmp_t) ? tmp_t : (DateTime?)null;
string idesc = node.Attributes["description"] == null ? String.Empty : node.Attributes["description"].Value;
string icat = node.Attributes["category"] == null ? String.Empty : node.Attributes["category"].Value;
string itag = node.Attributes["tag"] == null ? String.Empty : node.Attributes["tag"].Value;
bool? item_visible = null; bool tmp_visible;
if (node.Attributes["visible"] != null)
item_visible = Boolean.TryParse(node.Attributes["visible"].Value, out tmp_visible) ? tmp_visible : (bool?)null;
AddSettingsItem(item_type, item_name, item_value, item_modified, item_readonly, item_min, item_max, item_default, new SettingsMetaData(idesc, icat, itag, item_visible));
}
/// <summary>
/// Adds a new Settings item
/// </summary>
/// <param name="itype">Type</param>
/// <param name="iname">Name</param>
/// <param name="ivalue">Value</param>
/// <param name="imodified">Modified datetiem</param>
/// <param name="ireadonly">Readonly</param>
/// <param name="imax">MaxValue</param>
/// <param name="imin">MinValue</param>
/// <param name="idefault">Default</param>
/// <param name="imeta">Meta data</param>
private void AddSettingsItem(string itype, string iname, string ivalue, DateTime? imodified, bool? ireadonly, string imax, string imin, string idefault, SettingsMetaData imeta)
{
if (Settings.ContainsKey(iname))
return;
switch (itype)
{
case "int":
case "integer":
case "number":
int t_int;
if (!int.TryParse(ivalue, out t_int))
throw new Exception("Corrupt XML file");
Settings.Add(iname, new Item<int?>(
iname, int.Parse(ivalue), imodified, ireadonly,
(int.TryParse(imin, out t_int) == true) ? t_int : (int?)null,
(int.TryParse(imax, out t_int) == true) ? t_int : (int?)null,
(int.TryParse(idefault, out t_int) == true) ? t_int : (int?)null, imeta));
break;
case "bool":
case "boolean":
case "logic":
bool t_bool;
if (!bool.TryParse(ivalue, out t_bool))
throw new Exception("Corrupt XML file");
Settings.Add(iname, new Item<bool?>(
iname, bool.Parse(ivalue), imodified, ireadonly,
(bool.TryParse(imin, out t_bool) == true) ? t_bool : (bool?)null,
(bool.TryParse(imax, out t_bool) == true) ? t_bool : (bool?)null,
(bool.TryParse(idefault, out t_bool) == true) ? t_bool : (bool?)null, imeta));
break;
case "double":
case "float":
case "real":
double t_double;
if (!double.TryParse(ivalue, out t_double))
throw new Exception("Corrupt XML file");
Settings.Add(iname, new Item<double?>(
iname, double.Parse(ivalue), imodified, ireadonly,
(double.TryParse(imin, out t_double) == true) ? t_double : (double?)null,
(double.TryParse(imax, out t_double) == true) ? t_double : (double?)null,
(double.TryParse(idefault, out t_double) == true) ? t_double : (double?)null, imeta));
break;
case "color":
case "rgb":
case "brush":
Color color;
try
{
color = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString(ivalue);
}
catch (Exception)
{
throw new Exception("Corrupt XML file");
}
Color? color_default = null;
try
{
color_default = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString(idefault);
}
catch (Exception)
{
}
Settings.Add(iname, new Item<Color?>(
iname, color, imodified, ireadonly,
null,
null,
color_default == null ? (Color?)null : color_default.Value, imeta));
break;
case "datetime":
case "date":
case "time":
DateTime t_datetime;
if (!DateTime.TryParse(ivalue, out t_datetime))
throw new Exception("Corrupt XML file");
Settings.Add(iname, new Item<DateTime?>(
iname, DateTime.Parse(ivalue), imodified, ireadonly,
(DateTime.TryParse(imin, out t_datetime) == true) ? t_datetime : (DateTime?)null,
(DateTime.TryParse(imax, out t_datetime) == true) ? t_datetime : (DateTime?)null,
(DateTime.TryParse(idefault, out t_datetime) == true) ? t_datetime : (DateTime?)null, imeta));
break;
case "font":
case "style":
case "fontstyle":
Font font;
try
{