-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathAdminShellUtil.cs
More file actions
1770 lines (1547 loc) · 60.9 KB
/
Copy pathAdminShellUtil.cs
File metadata and controls
1770 lines (1547 loc) · 60.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2018-2023 Festo SE & Co. KG <https://www.festo.com/net/de_de/Forms/web/contact_international>
Author: Michael Hoffmeister
This source code is licensed under the Apache License 2.0 (see LICENSE.txt).
This source code may use other Open Source software components (see LICENSE.txt).
*/
using AasxCompatibilityModels;
using Extensions;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
namespace AdminShellNS
{
public static class AdminShellUtil
{
#region Various utilities
// ------------------------------------------------------------------------------------
public static T[] GetEnumValues<T>() where T : Enum
=> (T[])Enum.GetValues(typeof(T));
public static IEnumerable<T> GetEnumValues<T>(T[] excludes) where T : Enum
{
foreach (var v in (T[])Enum.GetValues(typeof(T)))
if (!excludes.Contains(v))
yield return v;
}
#endregion
#region V3 Methods
public static void EnumerateSearchable(
SearchResults results, object obj, string qualifiedNameHead, int depth, SearchOptions options,
object businessObject = null)
{
// access
if (results == null || obj == null || options == null)
return;
Type objType = obj.GetType();
// depth
if (depth > options.maxDepth)
return;
// try to get element name of an AAS entity
string elName = null;
if (obj is IReferable)
{
elName = (obj as IReferable).GetType().Name;
businessObject = obj;
}
// enrich qualified name, accordingly
var qualifiedName = qualifiedNameHead;
if (elName != null)
qualifiedName = qualifiedName + (qualifiedName.Length > 0 ? "." : "") + elName;
// do NOT dive into objects, which are not in the reight assembly
if (options.allowedAssemblies == null || !options.allowedAssemblies.Contains(objType.Assembly))
return;
// do not dive into enums
if (objType.IsEnum)
return;
// look at fields, first
var fields = objType.GetFields();
foreach (var fi in fields)
{
// is the object marked to be skipped?
var x3 = fi.GetCustomAttribute<AdminShell.SkipForReflection>();
if (x3 != null)
continue;
var x4 = fi.GetCustomAttribute<AdminShell.SkipForSearch>();
if (x4 != null)
continue;
// get value(s)
var fieldValue = fi.GetValue(obj);
if (fieldValue == null)
continue;
var valueElems = fieldValue as IList;
if (valueElems != null)
{
// field is a collection .. dive deeper, if allowed
foreach (var el in valueElems)
EnumerateSearchable(results, el, qualifiedName, depth + 1, options, businessObject);
}
else
{
// field is a single entity .. check it
CheckSearchable(
results, options, qualifiedName, businessObject, fi, fieldValue, obj,
() => { return fieldValue.GetHashCode(); });
// dive deeper ..
EnumerateSearchable(results, fieldValue, qualifiedName, depth + 1, options, businessObject);
}
}
// properties & objects behind
var properties = objType.GetProperties();
foreach (var pi in properties)
{
var gip = pi.GetIndexParameters();
if (gip.Length > 0)
// no indexed properties, yet
continue;
// is the object marked to be skipped?
var x3 = pi.GetCustomAttribute<AdminShell.SkipForReflection>();
if (x3 != null)
continue;
var x4 = pi.GetCustomAttribute<AdminShell.SkipForSearch>();
if (x4 != null)
continue;
// get value(s)
var propValue = pi.GetValue(obj, null);
if (propValue == null)
continue;
var valueElems = propValue as IList;
if (valueElems != null)
{
// property is a collection .. dive deeper, if allowed
foreach (var el in valueElems)
EnumerateSearchable(results, el, qualifiedName, depth + 1, options, businessObject);
}
else
{
// field is a single entity .. check it
CheckSearchable(
results, options, qualifiedName, businessObject, pi, propValue, obj,
() => { return propValue.GetHashCode(); });
// dive deeper ..
EnumerateSearchable(results, propValue, qualifiedName, depth + 1, options, businessObject);
}
}
}
public static void CheckSearchable(
SearchResults results, SearchOptions options, string qualifiedNameHead, object businessObject,
MemberInfo mi, object memberValue, object containingObject, Func<int> getMemberHash)
{
// try get a speaking name
var metaModelName = "<unknown>";
var x1 = mi.GetCustomAttribute<AdminShell.MetaModelName>();
if (x1 != null && x1.name != null)
metaModelName = x1.name;
// check if this object is searchable
var x2 = mi.GetCustomAttribute<AdminShell.TextSearchable>();
if (x2 != null)
{
// what to check?
string foundText = "" + memberValue?.ToString();
// find options
var found = true;
if (options.findText != null)
found = foundText.IndexOf(
options.findText, options.isIgnoreCase ? StringComparison.CurrentCultureIgnoreCase : 0) >= 0;
// add?
if (found)
{
var sri = new SearchResultItem();
sri.searchOptions = options;
sri.qualifiedNameHead = qualifiedNameHead;
sri.metaModelName = metaModelName;
sri.businessObject = businessObject;
sri.foundText = foundText;
sri.foundObject = memberValue;
sri.containingObject = containingObject;
if (getMemberHash != null)
sri.foundHash = getMemberHash();
// avoid duplicates
if (!results.foundResults.Contains(sri))
results.foundResults.Add(sri);
}
}
}
public class SearchResultItem : IEquatable<SearchResultItem>
{
public SearchOptions searchOptions;
public string qualifiedNameHead;
public string metaModelName;
public object businessObject;
public string foundText;
public object foundObject;
public object containingObject;
public int foundHash;
public bool Equals(SearchResultItem other)
{
if (other == null)
return false;
return this.qualifiedNameHead == other.qualifiedNameHead &&
this.metaModelName == other.metaModelName &&
this.businessObject == other.businessObject &&
this.containingObject == other.containingObject &&
this.foundText == other.foundText &&
this.foundHash == other.foundHash;
}
}
public class SearchResults
{
public int foundIndex = 0;
public List<SearchResultItem> foundResults = new List<SearchResultItem>();
public void Clear()
{
foundIndex = -1;
foundResults.Clear();
}
}
public class SearchOptions
{
public Assembly[] allowedAssemblies = null;
public int maxDepth = int.MaxValue;
public bool findFirst = false;
public int skipFirstResults = 0;
public string findText = null;
public bool isIgnoreCase = false;
public bool isRegex = false;
}
public static string[] GetPopularMimeTypes()
{
return
new[] {
System.Net.Mime.MediaTypeNames.Text.Plain,
System.Net.Mime.MediaTypeNames.Text.Xml,
System.Net.Mime.MediaTypeNames.Text.Html,
"text/markdown",
"text/asciidoc",
"application/json",
"application/rdf+xml",
System.Net.Mime.MediaTypeNames.Application.Pdf,
System.Net.Mime.MediaTypeNames.Image.Jpeg,
"image/png",
System.Net.Mime.MediaTypeNames.Image.Gif,
"application/iges",
"application/step",
"application/octet-stream"
};
}
public static bool CheckForTextContentType(string input)
{
if (input == null)
return false;
input = input.Trim().ToLower();
foreach (var tst in new[] {
System.Net.Mime.MediaTypeNames.Text.Plain,
System.Net.Mime.MediaTypeNames.Text.Xml,
System.Net.Mime.MediaTypeNames.Text.Html,
"text/markdown",
"text/asciidoc",
"application/json",
"application/rdf+xml"
})
if (input.Contains(tst.ToLower()))
return true;
return false;
}
public static string GuessExtension(string contentType = null, byte[] contents = null)
{
if (contentType?.HasContent() == true)
{
var list = GetPopularMimeTypes().ToList();
var p = list.IndexOf(contentType);
if (p >= 0)
return (new[] {
".txt",
".xml",
".html",
".md",
".adoc",
".json",
".rdf",
".pdf",
".jpg",
".png",
".gif",
".iges",
".stp"
})[p];
}
// ok, guess by bytes
if (contents != null && contents.Length > 0)
{
return GuessImageTypeExtension(contents);
}
// ok, nop
return ".tmp";
}
public static IEnumerable<AasSubmodelElements> GetAdequateEnums(AasSubmodelElements[] excludeValues = null, AasSubmodelElements[] includeValues = null)
{
if (includeValues != null)
{
foreach (var en in includeValues)
yield return en;
}
else
{
foreach (var en in (AasSubmodelElements[])Enum.GetValues(typeof(AasSubmodelElements)))
{
if (en == AasSubmodelElements.SubmodelElement)
continue;
if (excludeValues != null && excludeValues.Contains(en))
continue;
yield return en;
}
}
}
public static AasSubmodelElements? AasSubmodelElementsFrom<T>() where T : ISubmodelElement
{
if (typeof(T) == typeof(Property))
return AasSubmodelElements.Property;
if (typeof(T) == typeof(MultiLanguageProperty))
return AasSubmodelElements.MultiLanguageProperty;
if (typeof(T) == typeof(AasCore.Aas3_0.Range))
return AasSubmodelElements.Range;
if (typeof(T) == typeof(AasCore.Aas3_0.File))
return AasSubmodelElements.File;
if (typeof(T) == typeof(Blob))
return AasSubmodelElements.Blob;
if (typeof(T) == typeof(ReferenceElement))
return AasSubmodelElements.ReferenceElement;
if (typeof(T) == typeof(RelationshipElement))
return AasSubmodelElements.RelationshipElement;
if (typeof(T) == typeof(AnnotatedRelationshipElement))
return AasSubmodelElements.AnnotatedRelationshipElement;
if (typeof(T) == typeof(Capability))
return AasSubmodelElements.Capability;
if (typeof(T) == typeof(SubmodelElementCollection))
return AasSubmodelElements.SubmodelElementCollection;
if (typeof(T) == typeof(Operation))
return AasSubmodelElements.Operation;
if (typeof(T) == typeof(BasicEventElement))
return AasSubmodelElements.BasicEventElement;
if (typeof(T) == typeof(Entity))
return AasSubmodelElements.Entity;
return null;
}
public class CreateSubmodelElementDefaultHelper
{
public Func<IReference> CreateDefaultReference = null;
}
public static ISubmodelElement CreateSubmodelElementFromEnum(
AasSubmodelElements smeEnum, ISubmodelElement sourceSme = null,
CreateSubmodelElementDefaultHelper defaultHelper = null)
{
Func<IReference> crDefRef = () => { return (defaultHelper?.CreateDefaultReference?.Invoke()) ??
new Reference(ReferenceTypes.ExternalReference, new List<IKey>(
new[] { new Key(KeyTypes.GlobalReference, "") })); };
switch (smeEnum)
{
case AasSubmodelElements.Property:
{
return new Property(DataTypeDefXsd.String).UpdateFrom(sourceSme);
}
case AasSubmodelElements.MultiLanguageProperty:
{
return new MultiLanguageProperty().UpdateFrom(sourceSme);
}
case AasSubmodelElements.Range:
{
return new AasCore.Aas3_0.Range(DataTypeDefXsd.String).UpdateFrom(sourceSme);
}
case AasSubmodelElements.File:
{
return new AasCore.Aas3_0.File("").UpdateFrom(sourceSme);
}
case AasSubmodelElements.Blob:
{
return new Blob("").UpdateFrom(sourceSme);
}
case AasSubmodelElements.ReferenceElement:
{
// TODO (??, 0000-00-00): AAS core crashes without this
return new ReferenceElement(
value: crDefRef()
).UpdateFrom(sourceSme);
}
case AasSubmodelElements.RelationshipElement:
{
return new RelationshipElement(
crDefRef(),
crDefRef())
.UpdateFrom(sourceSme);
}
case AasSubmodelElements.AnnotatedRelationshipElement:
{
return new AnnotatedRelationshipElement(
crDefRef(),
crDefRef())
.UpdateFrom(sourceSme);
}
case AasSubmodelElements.Capability:
{
return new Capability().UpdateFrom(sourceSme);
}
case AasSubmodelElements.SubmodelElementCollection:
{
return new SubmodelElementCollection().UpdateFrom(sourceSme);
}
case AasSubmodelElements.SubmodelElementList:
{
return new SubmodelElementList(AasSubmodelElements.SubmodelElement).UpdateFrom(sourceSme);
}
case AasSubmodelElements.Operation:
{
return new Operation().UpdateFrom(sourceSme);
}
case AasSubmodelElements.BasicEventElement:
{
var observed = new Reference(ReferenceTypes.ModelReference, new List<IKey>() { new Key(KeyTypes.Referable, "") });
return new BasicEventElement(observed,
Direction.Input, StateOfEvent.Off).UpdateFrom(sourceSme);
}
case AasSubmodelElements.Entity:
{
return new Entity(EntityType.SelfManagedEntity).UpdateFrom(sourceSme);
}
default:
{
return null;
}
}
}
#endregion
public static string EvalToNonNullString(string fmt, object o, string elseString = "")
{
if (o == null)
return elseString;
return string.Format(fmt, o);
}
public static string EvalToNonEmptyString(string fmt, string o, string elseString = "")
{
if (o == null || o == "")
return elseString;
return string.Format(fmt, o);
}
/// <summary>
/// Some syntactic sugar to easily take the first string which has content.
/// </summary>
public static string TakeFirstContent(params string[] choices)
{
foreach (var c in choices)
if (c != null && c.Trim().Length > 0)
return c;
return "";
}
/// <summary>
/// Takes the character at index 0 and converts it to upper case.
/// </summary>
public static string CapitalizeFirstLetter(string str)
{
if (str.HasContent() && char.IsLower(str[0]))
str = char.ToUpperInvariant(str[0]) + str.Substring(1);
return str;
}
/// <summary>
/// If len of <paramref name="str"/> exceeds <paramref name="maxLen"/> then
/// string is shortened and returned with an ellipsis(…) at the end.
/// </summary>
/// <returns>Shortened string</returns>
public static string ShortenWithEllipses(string str, int maxLen)
{
if (str == null)
return null;
if (maxLen >= 0 && str.Length > maxLen)
str = str.Substring(0, maxLen) + "\u2026";
return str;
}
/// <summary>
/// Returns a string without newlines and shortened (with ellipsis)
/// to a certain length
/// </summary>
/// <returns>Single-line, shortened string</returns>
public static string ToSingleLineShortened(string str, int maxLen, string textNewLine = " ")
{
str = str.ReplaceLineEndings(textNewLine);
return ShortenWithEllipses(str, maxLen);
}
/// <summary>Creates a filter-friendly name from the source.</summary>
/// <example>
/// <code>Assert.AreEqual("", AdminShellUtil.FilterFriendlyName(""));</code>
/// <code doctest="true">Assert.AreEqual("someName", AdminShellUtil.FilterFriendlyName("someName"));</code>
/// <code doctest="true">Assert.AreEqual("some__name", AdminShellUtil.FilterFriendlyName("some!;name"));</code>
/// </example>
public static string FilterFriendlyName(string src,
bool pascalCase = false,
bool fixMoreBlanks = false,
string regexForFilter = null,
bool removeEnumerationTemplate = false)
{
if (src == null)
return null;
if (pascalCase && src.Length > 0)
src = char.ToUpper(src[0]) + src.Substring(1);
var regex = regexForFilter ?? @"[^a-zA-Z0-9_]";
src = Regex.Replace(src, regex, "_");
if (fixMoreBlanks)
{
src = src.Trim('_');
// stupid
for (int i=0; i<9; i++)
src = src.Replace("__", "_");
}
if (removeEnumerationTemplate)
{
src = src.Replace("__00__", "");
src = src.Replace("__000__", "");
src = src.Replace("__0000__", "");
}
return src;
}
public static string GiveRandomIdShort(IReferable rf)
{
var sd = rf?.GetSelfDescription();
if (sd?.ElementAbbreviation?.HasContent() != true)
return "";
var r = new Random();
return sd.ElementAbbreviation + r.Next(0, 999999).ToString("D6");
}
/// <example>
/// <code doctest="true">Assert.IsFalse(AdminShellUtil.HasWhitespace(""));</code>
/// <code doctest="true">Assert.IsTrue(AdminShellUtil.HasWhitespace(" "));</code>
/// <code doctest="true">Assert.IsTrue(AdminShellUtil.HasWhitespace("aa bb"));</code>
/// <code doctest="true">Assert.IsTrue(AdminShellUtil.HasWhitespace(" aabb"));</code>
/// <code doctest="true">Assert.IsTrue(AdminShellUtil.HasWhitespace("aabb "));</code>
/// <code doctest="true">Assert.IsFalse(AdminShellUtil.HasWhitespace("aabb"));</code>
/// </example>
public static bool HasWhitespace(string src)
{
if (src == null)
throw new ArgumentNullException(nameof(src));
foreach (var s in src)
if (char.IsWhiteSpace(s))
return true;
return false;
}
/// <code doctest="true">Assert.IsTrue(AdminShellUtil.ComplyIdShort(""));</code>
public static bool ComplyIdShort(string src)
{
if (src == null)
throw new ArgumentNullException(nameof(src));
var res = true;
foreach (var s in src)
if (!Char.IsLetterOrDigit(s) && s != '_')
res = false;
if (src.Length > 0 && !Char.IsLetter(src[0]))
res = false;
return res;
}
public static string ByteSizeHumanReadable(long len)
{
// see: https://stackoverflow.com/questions/281640/
// how-do-i-get-a-human-readable-file-size-in-bytes-abbreviation-using-net
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
int order = 0;
while (len >= 1024 && order < sizes.Length - 1)
{
order++;
len = len / 1024;
}
// Adjust the format string to your preferences. For example "{0:0.#}{1}" would
// show a single decimal place, and no space.
string res = String.Format("{0:0.##} {1}", len, sizes[order]);
return res;
}
public static string ExtractPascalCasingLetters(string src)
{
// access
src = src?.Trim();
if (src == null || src.Length < 1)
return null;
// walk through
var res = "";
var arm = true;
foreach (var c in src)
{
// take?
if (arm && Char.IsUpper(c))
res += c;
// state for next iteration
arm = !Char.IsUpper(c);
}
// result
return res;
}
public static string FromDouble(double input, string format)
{
return string.Format(CultureInfo.InvariantCulture, format, input);
}
/// <summary>
/// Checks a given string to be float compatible.
/// </summary>
public static bool IsFloatingPointString(string input)
{
var res = double.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out var f);
return res;
}
/// <summary>
/// Fixes a given string to be float compatible.
/// </summary>
/// <returns>If the string was fixed.</returns>
public static bool FixFloatingPointString(ref string valstr, string noneResult = "0.0")
{
if (valstr?.HasContent() != true)
{
valstr = noneResult;
return true;
}
if (IsFloatingPointString(valstr))
return false;
var res = "";
foreach (var c in valstr)
if (c == ',')
res += '.';
else if ("0123456789.+-E".IndexOf(c) >= 0)
res += c;
valstr = res;
if (!IsFloatingPointString(valstr))
valstr = noneResult;
// was altered
return true;
}
/// <summary>
/// Checks a given string to be float compatible.
/// </summary>
public static bool IsIntegerString(string input)
{
var res = Int64.TryParse(input, NumberStyles.Any, CultureInfo.InvariantCulture, out var i);
return res;
}
/// <summary>
/// Fixes a given string to be float compatible.
/// </summary>
/// <returns>If the string was fixed.</returns>
public static bool FixIntegerString(ref string valstr, string noneResult = "0.0")
{
if (valstr?.HasContent() != true)
{
valstr = noneResult;
return true;
}
if (IsIntegerString(valstr))
return false;
var res = "";
foreach (var c in valstr)
if ("0123456789-".IndexOf(c) >= 0)
res += c;
valstr = res;
if (!IsIntegerString(valstr))
valstr = noneResult;
// was altered
return true;
}
/// <summary>
/// Checks if a given string is a ISO 639-1 language code; here: 2 digits only lower case
/// </summary>
public static bool IsIso6391LangCode(string input)
{
// access
if (input == null)
return false;
// directly filter
var test = "";
foreach (var c in input)
if ("abcdefghijklmnopqrstuvwxyz".IndexOf(c) >= 0)
test += c;
return input == test && input.Length == 2;
}
/// <summary>
/// Fixes a given string to be float compatible.
/// </summary>
/// <returns>If the string was fixed.</returns>
public static bool FixIso6391LangCode(ref string valstr, string noneResult = "en")
{
if (valstr?.HasContent() != true)
{
valstr = noneResult;
return true;
}
if (IsIso6391LangCode(valstr))
return false;
var res = "";
foreach (var c in valstr)
if ("abcdefghijklmnopqrstuvwxyz".IndexOf(c) >= 0)
res += c;
valstr = res;
if (!IsIso6391LangCode(valstr))
valstr = noneResult;
// was altered
return true;
}
public static int CountHeadingSpaces(string line)
{
if (line == null)
return 0;
int j;
for (j = 0; j < line.Length; j++)
if (!Char.IsWhiteSpace(line[j]))
break;
return j;
}
/// <summary>
/// Used to re-reformat a C# here string, which is multiline string introduced by @" ... ";
/// </summary>
public static string[] CleanHereStringToArray(string here)
{
if (here == null)
return null;
// convert all weird breaks to pure new lines
here = here.Replace("\r\n", "\n");
here = here.Replace("\n\r", "\n");
// convert all tabs to spaces
here = here.Replace("\t", " ");
// split these
var lines = new List<string>(here.Split('\n'));
if (lines.Count < 1)
return lines.ToArray();
// the first line could be special
string firstLine = null;
if (lines[0].Trim() != "")
{
firstLine = lines[0].Trim();
lines.RemoveAt(0);
}
// detect an constant amount of heading spaces
var headSpaces = int.MaxValue;
foreach (var line in lines)
if (line.Trim() != "")
headSpaces = Math.Min(headSpaces, CountHeadingSpaces(line));
// multi line trim possible?
if (headSpaces != int.MaxValue && headSpaces > 0)
for (int i = 0; i < lines.Count; i++)
if (lines[i].Length > headSpaces)
lines[i] = lines[i].Substring(headSpaces);
// re-compose again
if (firstLine != null)
lines.Insert(0, firstLine);
// return
return lines.ToArray();
}
/// <summary>
/// Used to re-reformat a C# here string, which is multiline string introduced by @" ... ";
/// </summary>
public static string CleanHereStringWithNewlines(string here, string nl = null)
{
if (nl == null)
nl = System.Environment.NewLine;
var lines = CleanHereStringToArray(here);
if (lines == null)
return null;
return String.Join(nl, lines);
}
public static string ShortLocation(Exception ex)
{
if (ex == null || ex.StackTrace == null)
return "";
string[] lines = ex.StackTrace.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
if (lines.Length < 1)
return "";
// search for " in "
// as the most actual stacktrace might be a built-in function, this might not work and therefore
// go down in the stack
int currLine = 0;
while (true)
{
// nothing found at all
if (currLine >= lines.Length)
return "";
// access current line
/* TODO (MIHO, 2020-11-12): replace with Regex for multi language. Ideally have Exception messages
always as English. */
var p = lines[currLine].IndexOf(" in ", StringComparison.Ordinal);
if (p < 0)
p = lines[currLine].IndexOf(" bei ", StringComparison.Ordinal);
if (p < 0)
{
// advance to next oldest line
currLine++;
continue;
}
// search last "\" or "/", to get only filename portion and position
p = lines[currLine].LastIndexOfAny(new[] { '\\', '/' });
if (p < 0)
{
// advance to next oldest line
currLine++;
continue;
}
// return this
return lines[currLine].Substring(p);
}
}
public static string MapIntToStringArray(int? input, string ifNull, string[] choices)
{
if (input == null || choices == null || choices.Length < 1)
return ifNull;
int i = input ?? 0;
if (i < 0 || i >= choices.Length)
return ifNull;
return choices[i];
}
public static string MapBoolToStringArray(bool? input, string ifNull, string[] choices)
{
if (input == null || choices == null || choices.Length != 2)
return ifNull;
bool b = input ?? false;
return choices[b ? 1 : 0];
}
public enum ConstantFoundEnum { No, AnyCase, ExactCase }
public static ConstantFoundEnum CheckIfInConstantStringArray(string[] arr, string str)
{
if (arr == null || str == null)
return ConstantFoundEnum.No;
bool anyCaseFound = false;
bool exactCaseFound = false;
foreach (var a in arr)
{
anyCaseFound = anyCaseFound || str.ToLower() == a.ToLower();
exactCaseFound = exactCaseFound || str == a;
}
if (exactCaseFound)
return ConstantFoundEnum.ExactCase;
if (anyCaseFound)
return ConstantFoundEnum.AnyCase;
return ConstantFoundEnum.No;
}
public static string CorrectCasingForConstantStringArray(string[] arr, string str)
{
if (arr == null || str == null)
return str;
foreach (var a in arr)
if (str.ToLower() == a.ToLower())
return a;
return str;
}
//
// String manipulations
//
public static List<string> StringSplitUnquoted(
string input,
char splitChar,
StringSplitOptions options = StringSplitOptions.None)
{
var curr = "";
var res = new List<string>();
Action<string> issue = (str) =>
{
if ((options & StringSplitOptions.TrimEntries) != 0)
str = str.Trim();
if (str == "" && (options & StringSplitOptions.RemoveEmptyEntries) != 0)
return;
res.Add(str);
};
foreach (var ci in input)
{
// split?
if (ci == splitChar)
{
issue(curr);
curr = "";
continue;
}
// no, add
curr += ci;
}
// issue (again)?
issue(curr);
// ok
return res;
}
public static string ReplacePercentPlaceholder(
string input,
string searchFor,
Func<string> substLamda,
StringComparison comparisonType = StringComparison.InvariantCulture)
{
// access
if (input == null || searchFor == null || searchFor == "")
return input;
// find
while (true)
{
// any occurence
var p = input.IndexOf(searchFor, comparisonType);
if (p < 0)
break;
// split