-
Notifications
You must be signed in to change notification settings - Fork 0
/
BReusablePm.fs
1437 lines (1268 loc) · 58.6 KB
/
BReusablePm.fs
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
[<AutoOpen>]
module Pm.Schema.BReusable
open System
open System.Collections.Generic
open System.Diagnostics
// for statically typed parameters in an active pattern see: http://stackoverflow.com/questions/7292719/active-patterns-and-member-constraint
//consider pulling in useful functions from https://gist.github.com/ruxo/a9244a6dfe5e73337261
let cast<'T> (x:obj) = x :?> 'T
//https://blogs.msdn.microsoft.com/dsyme/2009/11/08/equality-and-comparison-constraints-in-f/
type System.Int32 with
static member tryParse x =
System.Int32.TryParse x
|> function
| true, x -> Some x
| _ -> None
module Choices =
let private allOrNone fChoose items =
match items with
| [] -> None
| items ->
List.foldBack(fun item state ->
match state with
| None -> None
| Some items ->
match fChoose item with
| Some item ->
item::items
|> Some
| None -> None
) items (Some [])
let (|Homogenous1Of2|_|) items = allOrNone (function | Choice1Of2 x -> Some x | _ -> None) items
let (|Homogenous2Of2|_|) items = allOrNone (function | Choice2Of2 x -> Some x | _ -> None) items
let (|Just1sOf2|) items =
items
|> List.choose(function | Choice1Of2 x -> Some x | _ -> None)
|> Some
let (|Just2sOf2|) items =
items
|> List.choose(function | Choice2Of2 x -> Some x | _ -> None)
module IComparable =
let equalsOn f x (yobj:obj) =
match yobj with
| :? 'T as y -> (f x = f y)
| _ -> false
let hashOn f x = hash (f x)
let compareOn f x (yobj: obj) =
match yobj with
| :? 'T as y -> compare (f x) (f y)
| _ -> invalidArg "yobj" "cannot compare values of different types"
#nowarn "0042"
// http://fssnip.net/7SK
// allows using units of measure on other types
module IGUoM =
open System
type UoM = class end
with
static member inline Tag< ^W, ^t, ^tm when (^W or ^t) : (static member IsUoM : ^t * ^tm -> unit)> (t : ^t) = (# "" t : ^tm #)
static member inline UnTag< ^W, ^t, ^tm when (^W or ^t) : (static member IsUoM : ^t * ^tm -> unit)> (t : ^tm) = (# "" t : ^t #)
let inline tag (x : 't) : 'tm = UoM.Tag<UoM, 't, 'tm> x
let inline untag (x : 'tm) : 't = UoM.UnTag<UoM, 't, 'tm> x
[<MeasureAnnotatedAbbreviation>]
type string<[<Measure>] 'Measure> = string
type UoM with
// Be *very* careful when writing this; bad args will result in invalid IL
static member IsUoM(_ : string, _ : string<'Measure>) = ()
[<Measure>] type FullName = class end
[<Measure>] type FirstName= class end
/// this doesn't account for cases where the identity is longer than signed int holds
type ValidIdentity<[<Measure>] 'T> private(i:int<'T>) =
static let fIsValid i = i > 0<_>
let i = if fIsValid i then i else failwithf "Invalid value"
member __.Value = i
/// valid values are 1..x
static member TryCreateOpt i =
if fIsValid i then
ValidIdentity<'T>(i) |> Some
else None
static member get (vi:ValidIdentity<_>) : int<'T> = vi.Value
static member OptionOfInt x = if fIsValid x then Some x else None
member private __.ToDump() = i |> string // linqpad friendly
override x.ToString() =
x.ToDump()
override x.Equals y = IComparable.equalsOn ValidIdentity.get x y
override x.GetHashCode() = IComparable.hashOn ValidIdentity.get x
interface System.IComparable with
member x.CompareTo y = IComparable.compareOn ValidIdentity.get x y
module IntPatterns =
let (|PositiveInt|Zero|NegativeInt|) (x:int<_>) =
if x > 0<_> then PositiveInt
elif x = 0<_> then Zero
else NegativeInt
// things that assist with point-free style
[<AutoOpen>]
module FunctionalHelpersAuto =
let teeTuple f x = x, f x
/// take a dead-end function and curry the input
let tee f x = f x; x
// take a value and adjust it to fall within the range of vMin .. vMax
let clamp vMin vMax v =
max v vMin
|> min vMax
/// super handy with operators like (*) and (-)
/// take a function that expects 2 arguments and flips them before applying to the function
let inline flip f x y = f y x
/// take a tuple and apply the 2 arguments one at a time (from haskell https://www.haskell.org/hoogle/?hoogle=uncurry)
let uncurry f (x,y) = f x y
/// does not work with null x
let inline getType x = x.GetType()
// based on http://stackoverflow.com/a/2362114/57883
// mimic the C# as keyword
let castAs<'t> (o:obj): 't option =
match o with
| :? 't as x -> Some x
| _ -> None
// long pipe chains don't allow breakpoints anywhere inside
// does this need anything to prevent the method from being inlined/optimized away?
let breakpoint x =
let result = x
result
let breakpointf f x =
let result = f x
result
// allows you to pattern match against non-nullables to check for null (in case c# calls)
let (|NonNull|UnsafeNull|) x =
match box x with
| null -> UnsafeNull
| _ -> NonNull
module Tuple2 = // idea and most code taken from https://gist.github.com/ploeh/6d8050e121a5175fabb1d08ef5266cd7
let replicate x = x,x
// useful for Seq.mapi
let fromCurry x y = (x,y)
let curry f x y = f (x, y)
// calling already defined function from outer namespace, instead of duplicating the functionality for consistency with gist
let uncurry f (x, y) = uncurry f (x, y)
let swap (x, y) = (y, x)
let mapFst f (x, y) = f x, y
let mapSnd f (x, y) = x, f y
let extendFst f (x,y) = f (x,y), y
let extendSnd f (x,y) = x, f(x,y)
let optionOfFst f (x,y) =
match f x with
| Some x -> Some (x, y)
| None -> None
let optionOfSnd f (x,y) =
match f y with
| Some y -> Some (x,y)
| None -> None
// start Brandon additions
let mapBoth f (x,y) = f x, f y
let private failNullOrEmpty paramName x = if String.IsNullOrEmpty x then raise <| ArgumentOutOfRangeException paramName else x
type System.String with
// // no idea how to call this thing with a comparer
// static member indexOf (delimiter,?c:StringComparison) (x:string) =
// match failNullOrEmpty "delimiter" delimiter,c with
// | d, Some c -> x.IndexOf(d,comparisonType=c)
// | d, None -> x.IndexOf d
static member indexOf delimiter (x:string) =
failNullOrEmpty "delimiter" delimiter
|> x.IndexOf
static member indexOfC delimiter c (x:string) =
x.IndexOf(failNullOrEmpty "delimiter" delimiter ,comparisonType=c)
// couldn't get this guy to call the other guy, so... leaving him out too
// static member contains (delimiter, ?c:StringComparison) (x:string) =
// match failNullOrEmpty "delimiter" delimiter, c with
// | d, Some c -> x.IndexOf(d, comparisonType=c) |> flip (>=) 0
// | d, None -> x.Contains d
static member contains delimiter (x:string) =
failNullOrEmpty "delimiter" delimiter
|> x.Contains
static member containsC delimiter c (x:string) =
x
|> String.indexOfC (failNullOrEmpty "delimiter" delimiter) c
|> flip (>=) 0
static member substring i (x:string) = x.Substring i
static member substring2 i e (x:string)= x.Substring(i,e)
// the default insensitive comparison
static member defaultIComparison = StringComparison.InvariantCultureIgnoreCase
static member Null:string = null
static member trim (s:string) = match s with | null -> null | s -> s.Trim()
static member split (delims:string seq) (x:string) = x.Split(delims |> Array.ofSeq, StringSplitOptions.None)
static member splitO (items:string seq) options (x:string) = x.Split(items |> Array.ofSeq, options)
static member emptyToNull (x:string) = if String.IsNullOrEmpty x then null else x
static member equalsI (x:string) (x2:string) = not <| isNull x && not <| isNull x2 && x.Equals(x2, String.defaultIComparison)
static member startsWithI (toMatch:string) (x:string) = not <| isNull x && not <| isNull toMatch && toMatch.Length > 0 && x.StartsWith(toMatch, String.defaultIComparison)
static member isNumeric (x:string) = not <| isNull x && x.Length > 0 && x |> String.forall Char.IsNumber
static member splitLines(x:string) = x.Split([| "\r\n";"\n"|], StringSplitOptions.None)
static member before (delimiter:string) s = s |> String.substring2 0 (s.IndexOf delimiter)
static member beforeOrSelf (delimiter:string) x = if x|> String.contains delimiter then x |> String.before delimiter else x
static member beforeAnyOf (delimiters:string list) (x:string) =
let index, _ =
delimiters
|> Seq.map (fun delimiter -> x.IndexOf(delimiter),delimiter)
|> Seq.filter(fun (index,_) -> index >= 0)
|> Seq.minBy (fun (index, _) -> index)
x.Substring(0,index)
static member replace (target:string) (replacement) (str:string) = if String.IsNullOrEmpty target then invalidOp "bad target" else str.Replace(target,replacement)
// comment/concern/critique auto-opening string functions may pollute (as there are so many string functions)
// not having to type `String.` on at least the used constantly is a huge reduction in typing
// also helps with point-free style
module StringHelpers =
// I've been fighting/struggling with where to namespace/how to architect string functions, they are so commonly used, static members make it easier to find them
// since typing `String.` with this module open makes them all easy to find
// favor non attached methods for commonly used methods
// let before (delimiter:string) (x:string) = x.Substring(0, x.IndexOf delimiter)
let contains (delimiter:string) (x:string) = String.contains delimiter x
let containsI (delimiter:string) (x:string) = x |> String.containsC delimiter String.defaultIComparison
let substring i x = x |> String.substring i
let substring2 i length (x:string) = x |> String.substring2 i length //x.Substring(i, length)
let before (delimiter:string) s = s |> String.substring2 0 (s.IndexOf delimiter)
let beforeOrSelf delimiter x = if x|> String.contains delimiter then x |> before delimiter else x
let after (delimiter:string) (x:string) =
failNullOrEmpty "x" x
|> tee (fun _ -> failNullOrEmpty "delimiter" delimiter |> ignore)
|> fun x ->
match x.IndexOf delimiter with
| i when i < 0 -> failwithf "after called without matching substring in '%s'(%s)" x delimiter
| i -> x |> String.substring (i + delimiter.Length)
let afterI (delimiter:string) (x:string) =
x
|> String.indexOfC delimiter String.defaultIComparison
|> (+) delimiter.Length
|> flip String.substring x
let afterOrSelf delimiter x = if x|> String.contains delimiter then x |> after delimiter else x
let afterOrSelfI (delimiter:string) (x:string) = if x |> String.containsC delimiter String.defaultIComparison then x |> afterI delimiter else x
let containsAnyOf (delimiters:string seq) (x:string) = delimiters |> Seq.exists(flip contains x)
let containsIAnyOf (delimiters:string seq) (x:string) = delimiters |> Seq.exists(flip containsI x)
let delimit (delimiter:string) (items:#seq<string>) = String.Join(delimiter,items)
let endsWith (delimiter:string) (x:string) = x.EndsWith delimiter
let isNumeric (s:string)= not <| isNull s && s.Length > 0 && s |> String.forall Char.IsNumber
let replace (target:string) (replacement) (str:string) = if String.IsNullOrEmpty target then invalidOp "bad target" else str.Replace(target,replacement)
let splitLines(x:string) = x.Split([| "\r\n";"\n"|], StringSplitOptions.None)
let startsWith (delimiter:string) (s:string) = s.StartsWith delimiter
let startsWithI (delimiter:string) (s:string) = s.StartsWith(delimiter,String.defaultIComparison)
let trim = String.trim
// let after (delimiter:string) (x:string) =
// match x.IndexOf delimiter with
// | i when i < 0 -> failwithf "after called without matching substring in '%s'(%s)" x delimiter
// | i -> x.Substring(i + delimiter.Length)
let afterLast delimiter x =
if x |> String.contains delimiter then failwithf "After last called with no match"
x |> String.substring (x.LastIndexOf delimiter + delimiter.Length)
let stringEqualsI s1 (toMatch:string)= not <| isNull toMatch && toMatch.Equals(s1, StringComparison.InvariantCultureIgnoreCase)
let inline isNullOrEmptyToOpt s =
if String.IsNullOrEmpty s then None else Some s
// was toFormatString
// with help from http://www.readcopyupdate.com/blog/2014/09/26/type-constraints-by-example-part1.html
let inline toFormatString (f:string) (a:^a) = ( ^a : (member ToString:string -> string) (a,f))
//if more is needed consider humanizer or inflector
let toPascalCase s =
s
|> Seq.mapi (fun i l -> if i=0 && Char.IsLower l then Char.ToUpper l else l)
|> String.Concat
let humanize camel :string =
seq {
let pascalCased = toPascalCase camel
yield pascalCased.[0]
for l in pascalCased |> Seq.skip 1 do
if System.Char.IsUpper l then
yield ' '
yield l
else
yield l
}
|> String.Concat
// I've also been struggling with the idea that Active patterns are frequently useful as just methods, so sometimes methods are duplicated as patterns
[<AutoOpen>]
module StringPatterns =
open StringHelpers
let (|NullString|Empty|WhiteSpace|ValueString|) (s:string) =
match s with
| null -> NullString
| "" -> Empty
| _ when String.IsNullOrWhiteSpace s -> WhiteSpace
| _ -> ValueString
let (|StartsWith|_|) (str:string) arg = if str.StartsWith(arg) then Some() else None
let (|StartsWithI|_|) s1 (toMatch:string) = if not <| isNull toMatch && toMatch.StartsWith(s1, StringComparison.InvariantCultureIgnoreCase) then Some () else None
let (|StringEqualsI|_|) s1 (toMatch:string) = if String.equalsI toMatch s1 then Some() else None
let (|InvariantEqualI|_|) (str:string) arg =
if String.Compare(str, arg, StringComparison.InvariantCultureIgnoreCase) = 0
then Some() else None
let (|IsNumeric|_|) (s:string) = if not <| isNull s && s.Length > 0 && s |> String.forall Char.IsNumber then Some() else None
let (|ContainsI|_|) s1 (toMatch:string) = if toMatch |> containsI s1 then Some () else None
let (|OrdinalEqualI|_|) (str:string) arg =
if String.Compare(str, arg, StringComparison.OrdinalIgnoreCase) = 0
then Some() else None
let inline (|IsTOrTryParse|_|) (t,parser) (x:obj): 't option =
match x with
| v when v.GetType() = t -> Some (v :?> 't)
| :? string as p ->
match parser p with
| true, v -> Some v
| _, _ -> None
| _ -> None
let (|Int|_|) (x:obj) =
match x with
| :? string as p ->
let success,value = System.Int32.TryParse(p)
if success then
Some value
else None
| _ -> None
type System.String with
static member IsValueString =
function
| ValueString _ -> true
| _ -> false
module Xml =
open System.Xml.Linq
let nsNone = XNamespace.None
let toXName (ns:XNamespace) name =
ns + name
let getElement1 n (e:XElement) =
e.Element n
|> Option.ofObj
// leaving out a 'getElement' as it will likely be (samples in code comments below):
// let getElement = toXName nsNone >> getElement1
// let getElement = toXName doc.Root.Name.Namespace >> getElement1
let getElements1 n (e:XElement) = e.Elements n
// point-free Seq.filter argument
let isNamed n (e:XElement) = e.Name = n
let getElementsAfter n (e:XElement) =
e
|> getElements1 n
|> Seq.skipWhile (isNamed n >> not)
|> Seq.skip 1
let getAttribVal name (e:XElement) =
nsNone + name
|> e.Attribute
|> Option.ofObj
|> Option.map (fun a -> a.Value)
let setAttribVal name value (e:XElement) =
e.SetAttributeValue(nsNone + name, value)
let getDescendants n (e:XElement) = e.Descendants n
let attribValueIs name value e =
e
|> getAttribVal name
|> Option.toObj
|> (=) value
let isElement (e:XNode) =
match e with
| :? XElement -> true
| _ -> false
// when you |> string an XElement, normally it writes appends the namespace as an attribute, but this is normally covered by the root element
let stripNamespaces (e:XElement):XElement=
// if the node is not XElement, pass through
let rec stripNamespaces (n:XNode): XNode =
match n with
| :? XElement as x ->
let contents =
x.Attributes()
// strips default namespace, but not other declared namespaces
|> Seq.filter(fun xa -> xa.Name.LocalName <> "xmlns")
|> Seq.cast<obj>
|> List.ofSeq
|> (@) (
x.Nodes()
|> Seq.map stripNamespaces
|> Seq.cast<obj>
|> List.ofSeq
)
XElement(nsNone + x.Name.LocalName, contents |> Array.ofList) :> XNode
| x -> x
stripNamespaces e :?> XElement
// e.nodes
// XElement(nsNone + e.Name.LocalName, content = e.Nodes)
()
module Caching =
let (|IsUnderXMinutes|_|) maxAgeMinutes (dt:DateTime) =
let minutes =
DateTime.Now - dt
|> fun x -> x.TotalMinutes
if minutes < maxAgeMinutes then
Some()
else None
type Result =
| Success
| Failed
[<NoEquality>]
[<NoComparison>]
type CacheAccess<'TKey,'TValue when 'TKey: comparison> = {Getter: 'TKey -> 'TValue option; Setter : 'TKey -> 'TValue -> unit; GetSetter: 'TKey -> (unit -> 'TValue) -> 'TValue} with
// C# helper(s)
member x.GetSetterFuncy (k,f:Func<_>)=
x.GetSetter k f.Invoke
let iDictTryFind<'T,'TValue> (k:'T) (d:IDictionary<'T,'TValue>) =
if d.ContainsKey k then
Some d.[k]
else None
let createTimedCache<'TKey,'TValue when 'TKey:comparison> (fIsYoungEnough) =
let cache = System.Collections.Concurrent.ConcurrentDictionary<'TKey,DateTime*'TValue>()
//let cache: Map<'TKey,DateTime*'TValue> = Map.empty
let getter k =
let result = cache |> iDictTryFind k |> Option.filter( fst >> fIsYoungEnough) |> Option.map snd
match result with
| Some v ->
printfn "Cache hit for %A" k
Some v
| None ->
printfn "Cache miss for %A" k
None
let setter k v =
cache.[k] <- (DateTime.Now,v)
let getSetter k f =
match getter k with
| Some v -> v
| _ ->
let v = f()
setter k v
v
{Getter=getter;Setter =setter; GetSetter=getSetter}
module Debug =
open System.Collections.ObjectModel
type FListener(fWrite: _ -> unit,fWriteLn:_ -> unit, name) =
inherit TraceListener(name)
override __.Write (msg:string) = fWrite msg
override __.WriteLine (msg:string) = fWriteLn msg
new(fWrite,fWriteLn) = new FListener(fWrite,fWriteLn, null)
type FLineListener(source:string ObservableCollection, fLineMap) =
inherit TraceListener()
let mutable lastWasWriteNotWriteLine = false
let fLineMap = defaultArg fLineMap id
let addText msg isLineFinished =
if lastWasWriteNotWriteLine then
let lastLine = source.[source.Count - 1]
assert (source.Remove lastLine)
lastLine + msg
else msg
|> fun x -> if isLineFinished then fLineMap x else x
|> source.Add
new(source, lineMap:Func<_, _>) = new FLineListener(source,fLineMap = if isNull lineMap then None else Some lineMap.Invoke)
override __.Write (msg:string) =
addText msg false
lastWasWriteNotWriteLine <- true
override __.WriteLine (msg:string) =
addText msg true
lastWasWriteNotWriteLine <- false
type DebugTraceListener(?breakOnAll) =
inherit TraceListener()
let mutable breakOnAll:bool = defaultArg breakOnAll false
override __.Write (_msg:string) = ()
override __.WriteLine (msg:string) =
let toIgnorePatterns = [
@"BindingExpression path error: 'Title' property not found on 'object' ''String' \(HashCode=-[0-9]+\)'. BindingExpression:Path=Title; DataItem='String' \(HashCode=-[0-9]+\); target element is 'ContentPresenter' \(Name='Content'\); target property is 'ResourceKey' \(type 'String'\)"
]
let regMatch p =
let m = Text.RegularExpressions.Regex.Match(msg,p)
if m.Success then
Some p
else
None
let matchedIgnorePattern = toIgnorePatterns |> Seq.choose regMatch |> Seq.tryHead
match matchedIgnorePattern with
| Some _ -> ()
| None ->
if breakOnAll && Debugger.IsAttached then
Debugger.Break()
else ()
type Listener(created:DateTime, name) =
inherit TraceListener(name)
new(created) = new Listener(created, null)
override __.Write (msg:string) = printf "%s" msg
override __.WriteLine (msg:string) =
printfn "%s" msg
member __.Created= created
let inline assertIfDebugger b =
if not b then
printfn "Assertion failed"
if Diagnostics.Debugger.IsAttached then
Debugger.Break()
// this option may be different from Debug.Assert somehow
// https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/assertions
// else
// assert b
type System.Action with
static member invoke (x:System.Action) () = x.Invoke()
static member invoke1 (x:System.Action<_>) y = x.Invoke(y)
static member invoke2 (x:System.Action<_,_>) y z = x.Invoke(y,z)
static member invoke3 (x:System.Action<_,_,_>) a b c = x.Invoke(a,b,c)
type System.Func<'tResult> with
static member invoke (x:System.Func<'tResult>) () = x.Invoke()
static member invoke1<'t> (x:System.Func<'t,'tResult>) y = x.Invoke y
static member invoke2<'t1,'t2> (x:System.Func<'t1,'t2,'tResult>) y z = x.Invoke(y, z)
static member invoke3 (x:System.Func<'t1,'t2,'t3,'tResult>) a b c = x.Invoke(a,b,c)
static member invoke4 (x:System.Func<'t1, 't2, 't3, 't4, 'tResult>) a b c d = x.Invoke(a,b,c,d)
//module Array =
// let ofOne x = [| x |]
module Seq =
/// Seq.take throws if there are no items
let takeLimit limit =
let mutable count = 0
Seq.takeWhile(fun _ ->
let result = count < limit
count <- count + 1
result)
let any items = items |> Seq.exists(fun _ -> true)
let copyFrom (source: _ seq) (toPopulate:IList<_>) =
if not <| isNull source && not <| isNull toPopulate then
use enumerator = source.GetEnumerator()
while enumerator.MoveNext() do
toPopulate.Add(enumerator.Current)
let ofType<'t> items =
items |> Seq.cast<obj> |> Seq.choose (fun x -> match x with | :? 't as x -> Some x | _ -> None )
module List =
// is this worth having/keeping?
// let except toScrape items =
// let toScrape = Set.ofList toScrape
// let items = Set.ofList items
// items - toScrape
// return a Tuple where (A, B) (both present if they have a match)
let forceJoin b a =
let b = Set.ofList b
let a = Set.ofList a
let x = Set.intersect a b
let diffa = a - b
let diffb = b - a
diffa - x
|> Seq.map (fun a' -> Some a', None)
|> Seq.append (x |> Seq.map (fun x' -> (Some x', Some x')))
|> Seq.append (diffb - x |> Seq.map (fun b' -> None, Some b'))
|> List.ofSeq
module Observables =
open System.Collections.ObjectModel
open System.Collections.Specialized
let bindObsTToObsObjDispatched (obsCollection:ObservableCollection<'t>) fDispatch =
let obsObj = ObservableCollection<obj>()
obsCollection.CollectionChanged.Add (fun e ->
match e.Action with
|NotifyCollectionChangedAction.Add ->
fDispatch (fun () ->
e.NewItems
|> Seq.cast<obj>
|> Seq.iter obsObj.Add
)
|NotifyCollectionChangedAction.Move ->
fDispatch (fun () ->
let oldIndex = e.OldStartingIndex
let newIndex = e.NewStartingIndex
obsObj.Move(oldIndex,newIndex)
)
|NotifyCollectionChangedAction.Remove ->
fDispatch (fun () ->
e.OldItems
|> Seq.cast<obj>
|> Seq.iter (obsObj.Remove>> ignore<bool>)
)
|NotifyCollectionChangedAction.Replace ->
fDispatch (fun () ->
e.NewItems
|> Seq.cast<obj>
|> Seq.zip (e.OldItems |> Seq.cast<obj>)
|> Seq.iteri(fun i (oldItem,newItem) ->
assert (obsObj.[e.OldStartingIndex + i] = oldItem)
obsObj.[e.OldStartingIndex + i] <- newItem
)
)
| NotifyCollectionChangedAction.Reset ->
fDispatch (fun () ->
obsObj.Clear()
if not <| isNull e.NewItems then
e.NewItems
|> Seq.cast<obj>
|> Seq.iter obsObj.Add
)
| x -> failwithf "Case %A is unimplemented" x
)
obsObj
let bindObsTToObsObj (obsCollection:ObservableCollection<'t>) =
bindObsTToObsObjDispatched obsCollection (fun f -> f())
// |Null|Value| already in use by Nullable active pattern
type System.Convert with
static member ToGuid(o:obj) = o :?> Guid
static member ToBinaryData(o:obj) = o :?> byte[] // http://stackoverflow.com/a/5371281/57883
// based on http://stackoverflow.com/questions/15115050/f-type-constraints-on-enums
type System.Enum with // I think enum<int> is the only allowed enum-ish constraint allowed in all of .net
static member parse<'t when 't : enum<int>> x = Enum.Parse(typeof<'t>,x)
static member parseT t x = Enum.Parse(t, x)
static member fromString<'t when 't:enum<int>> x = Enum.parse<'t> x :?> 't
static member getName<'t when 't : enum<int>> x = Enum.GetName(typeof<'t>,x)
static member getAll<'t when 't : enum<int>>() =
Enum.GetValues typeof<'t>
|> Seq.cast<int>
|> Seq.map (fun x -> Enum.getName<'t> x)
|> Seq.map (fun x -> Enum.parse<'t> x :?> 't)
static member fromInt<'t when 't :enum<int>>(i:int) =
Enum.getName<'t> i
|> fun x -> Enum.parse<'t> x :?> 't
type System.DateTime with
static member addDays dy (dt:DateTime) = dt.AddDays dy
static member addHours h (dt:DateTime) = dt.AddHours h
static member addMinutes min (dt:DateTime) = dt.AddMinutes min
static member toShortDateString (dt:DateTime) = dt.ToShortDateString()
static member getStartOfMonth (dt:DateTime) = DateTime(dt.Year, dt.Month,1)
static member getYear (dt:DateTime) = dt.Year
static member getHour (dt:DateTime) = dt.Hour
static member getMinute (dt:DateTime) = dt.Minute
static member roundTo useRoundUp (ts:TimeSpan) (dt:DateTime) =
if useRoundUp then
ts.Ticks - 1L
else
ts.Ticks / 2L
|> flip (+) dt.Ticks
|> flip (/) ts.Ticks
|> (*) ts.Ticks
|> DateTime
// taken from SO http://stackoverflow.com/a/1595311/57883
static member getAge (now:DateTime) (dt:DateTime) =
let age = now.Year - dt.Year
if (now.Month < dt.Month || (now.Month = dt.Month && now.Day < dt.Day)) then
age - 1
else
age
static member toString (format:string) (dt:DateTime) = dt.ToString(format)
//public static string CalculateAge(DateTime birthDate, DateTime now)
static member getAgeDisplay (now:DateTime) (dob:DateTime) =
let years = DateTime.getAge now dob
let _days,now =
let days = now.Day - dob.Day
if days < 0 then
let newNow = now.AddMonths(-1)
let totalDays = now - newNow
let totalDays = int totalDays.TotalDays
days + totalDays,newNow
else days,now
let months = ((now.Year - dob.Year) * 12) + now.Month - dob.Month
if (years <= 2) then
months.ToString() + "m"
else
years.ToString() + "y"
member x.GetAge (now:DateTime) = DateTime.getAge now x
module Time =
[<CustomComparison>]
[<CustomEquality>]
// shadowed constructor/private implementation
type ValidatedTime = private {_Hour:int; _Minute:int;} with
static member op_LessThan (x:ValidatedTime,y:ValidatedTime) = x.Hour < y.Hour || (x.Hour = y.Hour && x.Minute < y.Minute)
static member op_GreaterThan (x:ValidatedTime, y:ValidatedTime) = x.Hour > y.Hour || (x.Hour = y.Hour && x.Minute > y.Minute)
static member op_GreaterThanOrEqual (x:ValidatedTime, y:ValidatedTime) = x.Hour > y.Hour || (x.Hour = y.Hour && x.Minute >= y.Minute)
static member op_LessThanOrEqual (x:ValidatedTime,y:ValidatedTime) = x.Hour < y.Hour || (x.Hour = y.Hour && x.Minute <= y.Minute)
static member CanCreate hour minute = hour < 24 && hour >= 0 && minute >=0 && minute < 60
static member Create hour minute = if ValidatedTime.CanCreate hour minute then {_Hour=hour; _Minute = minute} |> Some else None
// exposing any members is a questionable decision for a Pure ADT, but... maybe this is ok for the way I'm using it
member x.Hour = x._Hour
member x.Minute = x._Minute
override x.ToString() =
DateTime.Today
|> DateTime.addHours (float x.Hour)
|> DateTime.addMinutes (float x.Minute)
|> DateTime.toString "hh:mmtt"
override x.GetHashCode() = (x.Hour,x.Minute).GetHashCode()
override x.Equals obj =
match obj with
| :? ValidatedTime as y ->
x.Hour = y.Hour && x.Minute = y.Minute
| _ -> false
interface IComparable with
member x.CompareTo (obj:obj)=
match obj with
| :? ValidatedTime as y ->
if ValidatedTime.op_LessThan (x, y) then
-1
elif ValidatedTime.op_GreaterThan (x, y) then
1
else
0
| _ -> raise <| InvalidOperationException("Type must be ValidatedTime")
[<RequireQualifiedAccess; CompilationRepresentation (CompilationRepresentationFlags.ModuleSuffix)>]
module ValidatedTime = //| ValidatedTime of hour:int * minute:int
let create hour minute = if ValidatedTime.CanCreate hour minute then {_Hour = hour; _Minute=minute} |> Some else None
let ofDateTime (dt:DateTime) = ValidatedTime.Create dt.Hour dt.Minute
let ofTimeSpan (ts:TimeSpan) = ValidatedTime.Create ts.Hours ts.Minutes
let getHour (vt: ValidatedTime) = vt.Hour
let getMinute (vt:ValidatedTime) = vt.Minute
// // shadow constructor
// let ValidatedTime hour minute = ValidatedTime.Create hour minute
// where only the hour component and below are relevant
// a timespan of
type IntraDayTimeSpan = |IntraDayTimeSpan of start:ValidatedTime*stop:ValidatedTime with
member x.Start = x |> function |IntraDayTimeSpan(start,_) -> start
member x.Stop = x |> function |IntraDayTimeSpan(_,stop) -> stop
member x.Contains (t:ValidatedTime) =
x.Start < t && t < x.Stop
member x.Overlaps (y:IntraDayTimeSpan) =
x.Contains y.Start || x.Contains y.Stop || y.Contains x.Start || y.Contains x.Stop
let IntraDayTimeSpan start stop =
if start < stop then
IntraDayTimeSpan(start,stop) |> Some
else None
type System.TimeSpan with
static member getTicks (x:TimeSpan) = x.Ticks
static member toString (s:string) (x:TimeSpan) = x.ToString(s)
[<CompilationRepresentation (CompilationRepresentationFlags.ModuleSuffix)>] // for C# access
module DateTime =
let getAgeDisplay now dob = DateTime.getAgeDisplay now dob
// Railway Oriented Programming
type Rail<'tSuccess,'tFailure> =
|Happy of 'tSuccess
|Unhappy of 'tFailure
[<RequireQualifiedAccess>]
module Railway =
/// apply either a success function or a failure function
let inline either happyFunc unhappyFunc twoTrackInput =
match twoTrackInput with
|Happy s -> happyFunc s
|Unhappy u -> unhappyFunc u
/// convert a one-track function into a switch
let inline switch f = f >> Happy
/// convert a switch function into a two-track function
let inline bind f = either f Unhappy
// convert a one-track function into a two-track function
let inline map f = //why isn't this simply "bind (f >> Happy)" ?
either (f >> Happy) Unhappy
/// bind a function to the failure track
/// primary design purpose: adding data to the failure track
let inline bind' f = either (Happy) f
let toHappyOption =
function
| Happy s -> s |> Some
| _ -> None
/// An adapter that takes a normal one-track function and turns it into a switch function, and also catches exceptions
/// could use id instead of a full exnHandler function for cases you just want the exception
let inline tryCatch f exnHandler x =
try
f x |> Happy
with ex -> exnHandler ex |> Unhappy
module Rop =
type Error = {Property : string; Message : string}
type Result<'a> =
| Success of 'a
| Fail of Error
let bind f x =
match x with Success x -> f x |Fail err -> Fail err
let bind' f1 f2 x =
match f1 x with
| Success x -> f2 x
| Fail err -> Fail err
// let inline (>>=) f1 f2 = bind' f1 f2
let overrideFail default' r = match r with |Success x -> x | Fail(_) -> default'
let overrideFail' f r = match r with |Success x -> x | Fail(_) -> f()
//http://stackoverflow.com/a/8227943/57883
let lock (lockobj:obj) f =
System.Threading.Monitor.Enter lockobj
try
f()
finally
System.Threading.Monitor.Exit lockobj
let buildCmdString fs arg i :string*string*obj =
let applied = sprintf fs arg
let replacement = (sprintf"{%i}" i)
let replace target = StringHelpers.replace target replacement
let replaced =
fs.Value
|> replace "'%s'"
|> replace "'%i'"
|> replace "'%d'"
applied,replaced, upcast arg
let inline SetAndNotify eq setter notifier=
if eq() then false
else
setter()
notifier()
true
let inline SetAndNotifyEquality field value setter notifier =
let eq () = EqualityComparer<'T>.Default.Equals(field, value)
SetAndNotify eq setter notifier
let SetAndNotifyEqualityC (field:'a byref, value:'a, notifier:System.Action) =
if EqualityComparer<'a>.Default.Equals(field,value) then
false
else
field <- value
notifier.Invoke()
true
module Diagnostics =
open StringHelpers
open System.Diagnostics
let tryAsyncCatch f =
f
|> Async.Catch
|> Async.Ignore
|> Async.Start
let makeDatedFilename (dt:DateTime) =
let dt = dt.ToString("yyyyMMdd")
sprintf "DebugLog_%s.txt" dt
let logToFile filename (dt:DateTime) topic attrs s =
let pid,sessionId =
try
let proc = System.Diagnostics.Process.GetCurrentProcess()
proc.Id, proc.SessionId
with _ -> 0,0
let attrs = [sprintf "dt=\"%A\"" dt;sprintf "pid=\"%i\"" pid; sprintf "sId=\"%i\"" sessionId]@attrs |> StringHelpers.delimit " "
let topic = match topic with |Some t -> t |_ -> "Message"
let msg = sprintf "<%s %s>%s</%s>%s" topic attrs s topic Environment.NewLine
System.IO.File.AppendAllText(filename,msg)
let logToEventLog s =
use eventLog = new EventLog("Application")
eventLog.Source <- "Application"
eventLog.WriteEntry s
let logS topic attrs s =
if not <| String.IsNullOrEmpty s then
printfn "%s" s
Debug.WriteLine s
let dt = DateTime.Now
let filename = makeDatedFilename(dt)
let fileLog= logToFile filename dt topic attrs
try
fileLog s
with ex ->
printfn "Exception attemping to log:%A" ex
try
sprintf "Failed to write to file: %s" filename
|> logToEventLog
with _ ->
printfn "Failed to log to event log"
try
logToEventLog s
with _ ->
printfn "Failed to log to event log"
let LogS topic s =
logS (isNullOrEmptyToOpt topic) [] s
let inline addDataIfPresent (ex:#exn) (s:string) =
if not <| isNull ex.Data && ex.Data.Keys.Count > 0 then
let extractString (v:obj) =
match v with
| :? string as s -> s
| x -> sprintf "%A" x
|> replace "\"" "\\\""
|> sprintf "\"%s\""
ex.Data.Keys
|> Seq.cast<obj>
|> Seq.map (fun k -> k, ex.Data.[k])
|> Seq.map (Tuple2.mapBoth extractString)
|> Seq.map (fun (k,v) -> sprintf "%s:%s" k v)
|> delimit ","
// escape double quotes
|> sprintf "%s\r\n{data:{%s}}" s
else
s
// this needs to account for ex.Data information
let logObj topic sOpt (x:obj) =
match sOpt with
| Some s -> sprintf "%s:%A" s x
| None -> sprintf "%A" x
|> fun s ->
match x with
| :? exn as x -> s |> addDataIfPresent x
| _ -> s
|> logS topic []
// if desired, only add data if the key isn't already present
let addDataMaybe k v (ex:#exn) =
if not <| ex.Data.Contains k then
ex.Data.Add (k, v)
// purpose: in a catch clause, try to do f, swallow exceptions so the outer exception is still handled the way it was intended to
// not using addDataMaybe in case the behavior is not desired
let inline tryDataAdd (x:#exn) f =
try
f x.Data.Add
with ex ->
logObj (Some "error adding exception data") None ex
let logExS topic s ex = logObj topic s ex
let BeginLogScope scopeName=
let pid = Process.GetCurrentProcess().Id
logS (Some scopeName) [ sprintf "pid=\"%i\"" pid ] ""
{ new System.IDisposable
with member __.Dispose() = logS (Some scopeName) [] (sprintf "<%s/>" scopeName)
}
let BeginTimedLogScope scopeName=
let pid = Process.GetCurrentProcess().Id
let sw = Stopwatch.StartNew()
logS (Some scopeName) [ sprintf "pid=\"%i\"" pid ] ""
{
new System.IDisposable
with member __.Dispose() =
sw.Stop()
logS (Some scopeName) [] (sprintf " <Elapsed>%A</Elapsed>" sw.ElapsedMilliseconds)
logS (Some scopeName) [] (sprintf "<%s/>" scopeName)
}
module Option = // https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/option.fs
/// unsafe (Unchecked.defaultof<_>)
let getValueOrDefault (n: 'a option) = match n with | Some x -> x | None -> Unchecked.defaultof<_>