-
-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathBusinessRules.cs
1406 lines (1268 loc) · 50.7 KB
/
BusinessRules.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------
// <copyright file="BusinessRules.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Tracks the business rules for a business object.</summary>
//-----------------------------------------------------------------------
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using Csla.Core;
using Csla.Serialization.Mobile;
using Csla.Server;
using Csla.Threading;
namespace Csla.Rules
{
/// <summary>
/// Tracks the business rules for a business object.
/// </summary>
[Serializable]
public class BusinessRules :
MobileObject, ISerializationNotification, IBusinessRules, IUseApplicationContext
{
/// <summary>
/// Creates an instance of the type.
/// </summary>
public BusinessRules()
{ }
/// <summary>
/// Creates an instance of the type.
/// </summary>
/// <param name="applicationContext"></param>
/// <param name="target">Target business object.</param>
public BusinessRules(ApplicationContext applicationContext, IHostRules target)
{
_applicationContext = applicationContext;
SetTarget(target);
}
[NonSerialized]
private Lock SyncRoot = LockFactory.Create();
ApplicationContext IUseApplicationContext.ApplicationContext { get => _applicationContext; set => _applicationContext = value; }
private ApplicationContext _applicationContext;
// list of broken rules for this business object.
private BrokenRulesCollection _brokenRules;
private BrokenRulesCollection BrokenRules =>
_brokenRules ??= new(true);
private bool _suppressRuleChecking;
/// <summary>
/// Gets or sets a value indicating whether calling
/// CheckRules should result in rule
/// methods being invoked.
/// </summary>
/// <value>True to suppress all rule method invocation.</value>
public bool SuppressRuleChecking
{
get { return _suppressRuleChecking; }
set { _suppressRuleChecking = value; }
}
private int _processThroughPriority;
/// <summary>
/// Gets or sets the priority through which
/// all rules will be processed.
/// </summary>
public int ProcessThroughPriority
{
get { return _processThroughPriority; }
set { _processThroughPriority = value; }
}
private string _ruleSet = null;
/// <summary>
/// Gets or sets the rule set to use for this
/// business object instance.
/// </summary>
public string RuleSet
{
get { return string.IsNullOrEmpty(_ruleSet) ? ApplicationContext.DefaultRuleSet : _ruleSet; }
set
{
_typeRules = null;
_typeAuthRules = null;
_ruleSet = value == ApplicationContext.DefaultRuleSet ? null : value;
if (BrokenRules.Count > 0)
{
BrokenRules.ClearRules();
}
}
}
/// <summary>
/// Gets or sets a value indicating whether rule engine should cacade n-leves when property value is changed from OuputPropertyValues.
/// </summary>
/// <value>
/// <c>true</c> if [cascade when changed]; otherwise, <c>false</c>.
/// </value>
public bool CascadeOnDirtyProperties
{
get { return _cascadeOnDirtyProperties; }
set { _cascadeOnDirtyProperties = value; }
}
[NonSerialized]
private BusinessRuleManager _typeRules;
internal BusinessRuleManager TypeRules
{
get
{
if (_typeRules == null && _target != null)
_typeRules = BusinessRuleManager.GetRulesForType(_target.GetType(), _ruleSet);
return _typeRules;
}
}
[NonSerialized]
private AuthorizationRuleManager _typeAuthRules;
internal AuthorizationRuleManager TypeAuthRules
{
get
{
if (_typeAuthRules == null && _target != null)
_typeAuthRules = AuthorizationRuleManager.GetRulesForType(_applicationContext, _target.GetType(), _ruleSet);
return _typeAuthRules;
}
}
/// <summary>
/// Gets a list of rule:// URI values for
/// the rules defined in the object.
/// </summary>
public string[] GetRuleDescriptions()
{
var result = new List<string>();
foreach (var item in TypeRules.Rules)
result.Add(item.RuleName);
return result.ToArray();
}
// reference to current business object
[NonSerialized]
private IHostRules _target;
internal void SetTarget(IHostRules target)
{
_target = target;
}
internal object Target
{
get { return _target; }
}
/// <summary>
/// Associates a business rule with the business object.
/// </summary>
/// <param name="rule">Rule object.</param>
public void AddRule(IBusinessRuleBase rule)
{
TypeRules.Rules.Add(rule);
}
/// <summary>
/// Associates a business rule with the business object.
/// </summary>
/// <param name="rule">Rule object.</param>
/// <param name="ruleSet">Rule set name.</param>
public void AddRule(IBusinessRuleBase rule, string ruleSet)
{
var typeRules = BusinessRuleManager.GetRulesForType(_target.GetType(), ruleSet);
typeRules.Rules.Add(rule);
}
/// <summary>
/// Associates an authorization rule with the business object.
/// </summary>
/// <param name="rule">Rule object.</param>
public void AddRule(IAuthorizationRuleBase rule)
{
EnsureUniqueRule(TypeAuthRules, rule);
TypeAuthRules.Rules.Add(rule);
}
/// <summary>
/// Associates a per-type authorization rule with
/// the business type in the default rule set.
/// </summary>
/// <param name="objectType">Type of business object.</param>
/// <param name="rule">Rule object.</param>
public static void AddRule(Type objectType, IAuthorizationRuleBase rule)
{
AddRule(objectType, rule, ApplicationContext.DefaultRuleSet);
}
/// <summary>
/// Associates a per-type authorization rule with
/// the business type.
/// </summary>
/// <param name="objectType">Type of business object.</param>
/// <param name="rule">Rule object.</param>
/// <param name="ruleSet">Rule set name.</param>
public static void AddRule(Type objectType, IAuthorizationRuleBase rule, string ruleSet)
{
AddRule(null, objectType, rule, ruleSet);
}
/// <summary>
/// Associates a per-type authorization rule with
/// the business type.
/// </summary>
/// <param name="applicationContext">ApplicationContext instance</param>
/// <param name="objectType">Type of business object.</param>
/// <param name="rule">Rule object.</param>
/// <param name="ruleSet">Rule set name.</param>
public static void AddRule(ApplicationContext applicationContext, Type objectType, IAuthorizationRuleBase rule, string ruleSet)
{
var typeRules = AuthorizationRuleManager.GetRulesForType(applicationContext, objectType, ruleSet);
EnsureUniqueRule(typeRules, rule);
typeRules.Rules.Add(rule);
}
private static void EnsureUniqueRule(AuthorizationRuleManager mgr, IAuthorizationRuleBase rule)
{
IAuthorizationRuleBase oldRule = null;
if (rule.Element != null)
oldRule = mgr.Rules.FirstOrDefault(c => c.Element != null && c.Element.Name == rule.Element.Name && c.Action == rule.Action);
else
oldRule = mgr.Rules.FirstOrDefault(c => c.Element == null && c.Action == rule.Action);
if (oldRule != null)
throw new ArgumentException(nameof(rule));
}
/// <summary>
/// Gets a value indicating whether there are
/// any currently broken rules, which would
/// mean the object is not valid.
/// </summary>
public bool IsValid
{
get { return BrokenRules.ErrorCount == 0; }
}
/// <summary>
/// Gets the broken rules list.
/// </summary>
public BrokenRulesCollection GetBrokenRules()
{
return BrokenRules;
}
[NonSerialized]
private bool _runningRules;
/// <summary>
/// Gets a value indicating whether a CheckRules
/// operation is in progress.
/// </summary>
public bool RunningRules
{
get { return _runningRules; }
private set { _runningRules = value; }
}
[NonSerialized]
private bool _isBusy;
[NonSerialized]
private AsyncManualResetEvent _busyChanged;
private AsyncManualResetEvent BusyChanged =>
_busyChanged ??= new AsyncManualResetEvent();
/// <summary>
/// Gets a value indicating whether any async
/// rules are currently executing.
/// </summary>
public bool RunningAsyncRules
{
get { return _isBusy; }
set
{
_isBusy = value;
if (_isBusy)
BusyChanged.Reset();
else
BusyChanged.Set();
}
}
/// <summary>
/// Gets a value indicating whether a specific
/// property has any async rules running.
/// </summary>
/// <param name="property">Property to check.</param>
public bool GetPropertyBusy(IPropertyInfo property)
{
return BusyProperties.Contains(property);
}
/// <summary>
/// Checks per-type authorization rules.
/// </summary>
/// <param name="applicationContext"></param>
/// <param name="action">Authorization action.</param>
/// <param name="objectType">Type of business object.</param>
public static bool HasPermission(
ApplicationContext applicationContext,
AuthorizationActions action,
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
#endif
Type objectType)
{
if (applicationContext == null)
throw new ArgumentNullException(nameof(applicationContext));
var activator = applicationContext.GetRequiredService<IDataPortalActivator>();
var realType = activator.ResolveType(objectType);
// no object specified so must use RuleSet from ApplicationContext
return HasPermission(action, null, applicationContext, realType, null, applicationContext.RuleSet);
}
/// <summary>
/// Checks per-type authorization rules.
/// </summary>
/// <param name="applicationContext"></param>
/// <param name="action">Authorization action.</param>
/// <param name="objectType">Type of business object.</param>
/// <param name="criteria">The criteria object provided.</param>
public static bool HasPermission(ApplicationContext applicationContext,
AuthorizationActions action,
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
#endif
Type objectType,
object[] criteria)
{
if (applicationContext == null)
throw new ArgumentNullException(nameof(applicationContext));
var activator = applicationContext.GetRequiredService<IDataPortalActivator>();
var realType = activator.ResolveType(objectType);
// no object specified so must use RuleSet from ApplicationContext
return HasPermission(action, null, applicationContext, realType, criteria, applicationContext.RuleSet);
}
/// <summary>
/// Checks per-type authorization rules.
/// </summary>
/// <param name="applicationContext"></param>
/// <param name="action">Authorization action.</param>
/// <param name="objectType">Type of business object.</param>
/// <param name="ruleSet">The rule set.</param>
/// <returns>
/// <c>true</c> if the specified action has permission; otherwise, <c>false</c>.
/// </returns>
public static bool HasPermission(
ApplicationContext applicationContext,
AuthorizationActions action,
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
#endif
Type objectType,
string ruleSet)
{
if (applicationContext == null)
throw new ArgumentNullException(nameof(applicationContext));
var activator = applicationContext.GetRequiredService<IDataPortalActivator>();
var realType = activator.ResolveType(objectType);
return HasPermission(action, null, applicationContext, realType, null, ruleSet);
}
/// <summary>
/// Checks per-instance authorization rules.
/// </summary>
/// <param name="applicationContext"></param>
/// <param name="action">Authorization action.</param>
/// <param name="obj">Business object instance.</param>
public static bool HasPermission(ApplicationContext applicationContext, AuthorizationActions action, object obj)
{
if (applicationContext == null)
throw new ArgumentNullException(nameof(applicationContext));
return HasPermission(action, obj, applicationContext, obj.GetType(), null, applicationContext.RuleSet);
}
private static bool HasPermission(AuthorizationActions action, object obj, ApplicationContext applicationContext, Type objType, object[] criteria, string ruleSet)
{
if (action == AuthorizationActions.ReadProperty ||
action == AuthorizationActions.WriteProperty ||
action == AuthorizationActions.ExecuteMethod)
throw new ArgumentOutOfRangeException($"{nameof(action)}, {action}");
bool result = true;
var rule =
AuthorizationRuleManager.GetRulesForType(applicationContext, objType, ruleSet).Rules.FirstOrDefault(c => c.Element == null && c.Action == action);
if (rule != null)
{
if (rule is IAuthorizationRule sync)
{
var context = new AuthorizationContext(applicationContext, rule, obj, objType) { Criteria = criteria };
sync.Execute(context);
result = context.HasPermission;
}
else
throw new ArgumentOutOfRangeException(rule.GetType().FullName);
}
return result;
}
/// <summary>
/// Checks per-property authorization rules.
/// </summary>
/// <param name="applicationContext"></param>
/// <param name="action">Authorization action.</param>
/// <param name="element">Property or method to check.</param>
public bool HasPermission(ApplicationContext applicationContext, AuthorizationActions action, IMemberInfo element)
{
if (_suppressRuleChecking)
return true;
if (action == AuthorizationActions.CreateObject ||
action == AuthorizationActions.DeleteObject ||
action == AuthorizationActions.GetObject ||
action == AuthorizationActions.EditObject)
throw new ArgumentOutOfRangeException($"{nameof(action)}, {action}");
bool result = true;
var rule =
TypeAuthRules.Rules.FirstOrDefault(c => c.Element != null && c.Element.Name == element.Name && c.Action == action);
if (rule != null)
{
if (rule is IAuthorizationRule sync)
{
var context = new AuthorizationContext(applicationContext, rule, this.Target, this.Target.GetType());
sync.Execute(context);
result = context.HasPermission;
}
else
throw new ArgumentOutOfRangeException(rule.GetType().FullName);
}
return result;
}
/// <summary>
/// Checks per-type authorization rules.
/// </summary>
/// <param name="applicationContext">The application context.</param>
/// <param name="action">The authorization action.</param>
/// <param name="objectType">The type of the business object.</param>
/// <param name="ct">The cancellation token.</param>
/// <returns>A task representing the asynchronous operation that returns a boolean indicating whether the permission is granted.</returns>
public static Task<bool> HasPermissionAsync(
ApplicationContext applicationContext,
AuthorizationActions action,
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
#endif
Type objectType,
CancellationToken ct)
{
if (applicationContext == null)
throw new ArgumentNullException(nameof(applicationContext));
var activator = applicationContext.GetRequiredService<IDataPortalActivator>();
var realType = activator.ResolveType(objectType);
// no object specified so must use RuleSet from ApplicationContext
return HasPermissionAsync(action, null, applicationContext, realType, null, applicationContext.RuleSet, ct);
}
/// <summary>
/// Checks per-type authorization rules.
/// </summary>
/// <param name="applicationContext">The application context.</param>
/// <param name="action">The authorization action.</param>
/// <param name="objectType">The type of the business object.</param>
/// <param name="criteria">The criteria object provided.</param>
/// <param name="ct">The cancellation token.</param>
/// <returns>A task representing the asynchronous operation. The task result contains a boolean value indicating whether the permission is granted.</returns>
public static Task<bool> HasPermissionAsync(
ApplicationContext applicationContext,
AuthorizationActions action,
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
#endif
Type objectType,
object[] criteria,
CancellationToken ct)
{
if (applicationContext == null)
throw new ArgumentNullException(nameof(applicationContext));
var activator = applicationContext.GetRequiredService<IDataPortalActivator>();
var realType = activator.ResolveType(objectType);
// no object specified so must use RuleSet from ApplicationContext
return HasPermissionAsync(action, null, applicationContext, realType, criteria, applicationContext.RuleSet, ct);
}
/// <summary>
/// Checks per-type authorization rules.
/// </summary>
/// <param name="applicationContext">The application context.</param>
/// <param name="action">Authorization action.</param>
/// <param name="objectType">Type of business object.</param>
/// <param name="ruleSet">The rule set.</param>
/// <param name="ct">The cancellation token.</param>
/// <returns>
/// <c>true</c> if the specified action has permission; otherwise, <c>false</c>.
/// </returns>
public static Task<bool> HasPermissionAsync(
ApplicationContext applicationContext,
AuthorizationActions action,
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
#endif
Type objectType,
string ruleSet,
CancellationToken ct)
{
if (applicationContext == null)
throw new ArgumentNullException(nameof(applicationContext));
var activator = applicationContext.GetRequiredService<IDataPortalActivator>();
var realType = activator.ResolveType(objectType);
return HasPermissionAsync(action, null, applicationContext, realType, null, ruleSet, ct);
}
/// <summary>
/// Checks per-instance authorization rules.
/// </summary>
/// <param name="applicationContext">The application context.</param>
/// <param name="action">The authorization action.</param>
/// <param name="obj">The business object instance.</param>
/// <param name="ct">The cancellation token.</param>
public static Task<bool> HasPermissionAsync(ApplicationContext applicationContext, AuthorizationActions action, object obj, CancellationToken ct)
{
if (applicationContext == null)
throw new ArgumentNullException(nameof(applicationContext));
return HasPermissionAsync(action, obj, applicationContext, obj.GetType(), null, applicationContext.RuleSet, ct);
}
private static async Task<bool> HasPermissionAsync(AuthorizationActions action, object obj, ApplicationContext applicationContext, Type objType, object[] criteria, string ruleSet, CancellationToken ct)
{
if (action == AuthorizationActions.ReadProperty ||
action == AuthorizationActions.WriteProperty ||
action == AuthorizationActions.ExecuteMethod)
throw new ArgumentOutOfRangeException($"{nameof(action)}, {action}");
bool result = true;
var rule =
AuthorizationRuleManager.GetRulesForType(applicationContext, objType, ruleSet).Rules.FirstOrDefault(c => c.Element == null && c.Action == action);
if (rule != null)
{
if (rule is IAuthorizationRule sync)
{
var context = new AuthorizationContext(applicationContext, rule, obj, objType) { Criteria = criteria };
sync.Execute(context);
result = context.HasPermission;
}
else if (rule is IAuthorizationRuleAsync nsync)
{
var context = new AuthorizationContext(applicationContext, rule, obj, objType) { Criteria = criteria };
await nsync.ExecuteAsync(context, ct);
result = context.HasPermission;
}
else
throw new ArgumentOutOfRangeException(rule.GetType().FullName);
}
return result;
}
/// <summary>
/// Checks per-property authorization rules.
/// </summary>
/// <param name="applicationContext">The application context.</param>
/// <param name="action">The authorization action.</param>
/// <param name="element">The property or method to check.</param>
/// <param name="ct">The cancellation token.</param>
/// <returns>A task representing the asynchronous operation. The task result contains a boolean value indicating whether the permission is granted.</returns>
public async Task<bool> HasPermissionAsync(ApplicationContext applicationContext, AuthorizationActions action, Csla.Core.IMemberInfo element, CancellationToken ct)
{
if (_suppressRuleChecking)
return true;
if (action == AuthorizationActions.CreateObject ||
action == AuthorizationActions.DeleteObject ||
action == AuthorizationActions.GetObject ||
action == AuthorizationActions.EditObject)
throw new ArgumentOutOfRangeException($"{nameof(action)}, {action}");
bool result = true;
var rule =
TypeAuthRules.Rules.FirstOrDefault(c => c.Element != null && c.Element.Name == element.Name && c.Action == action);
if (rule != null)
{
if (rule is IAuthorizationRule sync)
{
var context = new AuthorizationContext(applicationContext, rule, this.Target, this.Target.GetType());
sync.Execute(context);
result = context.HasPermission;
}
else if (rule is IAuthorizationRuleAsync nsync)
{
var context = new AuthorizationContext(applicationContext, rule, this.Target, this.Target.GetType());
await nsync.ExecuteAsync(context, ct);
result = context.HasPermission;
}
else
throw new ArgumentOutOfRangeException(rule.GetType().FullName);
}
return result;
}
/// <summary>
/// Gets a value indicating whether the permission
/// result can be cached.
/// </summary>
/// <param name="action">Authorization action.</param>
/// <param name="element">Property or method to check.</param>
public bool CachePermissionResult(AuthorizationActions action, IMemberInfo element)
{
// cannot cache result when suppressRuleChecking as HasPermission is then short circuited to return true.
if (_suppressRuleChecking)
return false;
bool result = true;
var rule =
TypeAuthRules.Rules.FirstOrDefault(c => c.Element != null && c.Element.Name == element.Name && c.Action == action);
if (rule != null)
result = rule.CacheResult;
return result;
}
/// <summary>
/// Invokes all rules for a specific property of the business type.
/// </summary>
/// <param name="property">Property to check.</param>
/// <returns>
/// Returns a list of property names affected by the invoked rules.
/// The PropertyChanged event should be raised for each affected
/// property.
/// </returns>
/// <exception cref="System.ArgumentNullException">If property is null</exception>
public Task<List<string>> CheckRulesAsync(IPropertyInfo property)
{
return CheckRulesAsync(property, Timeout.InfiniteTimeSpan);
}
/// <summary>
/// Invokes all rules for a specific property of the business type.
/// </summary>
/// <param name="property">Property to check.</param>
/// <param name="timeout">Timeout to wait for the rule completion.</param>
/// <returns>
/// Returns a list of property names affected by the invoked rules.
/// The PropertyChanged event should be raised for each affected
/// property.
/// </returns>
/// <exception cref="System.ArgumentNullException">If property is null</exception>
public async Task<List<string>> CheckRulesAsync(IPropertyInfo property, TimeSpan timeout)
{
var affectedProperties = CheckRules(property);
await WaitForAsyncRulesToComplete(timeout);
return affectedProperties;
}
/// <summary>
/// Invokes all rules for the business type.
/// </summary>
/// <returns>
/// Returns a list of property names affected by the invoked rules.
/// The PropertyChanged event should be raised for each affected
/// property. Does not return until all async rules are complete.
/// </returns>
public Task<List<string>> CheckRulesAsync()
{
return CheckRulesAsync(int.MaxValue);
}
/// <summary>
/// Invokes all rules for the business type.
/// </summary>
/// <param name="timeout">Timeout value in milliseconds</param>
/// <returns>
/// Returns a list of property names affected by the invoked rules.
/// The PropertyChanged event should be raised for each affected
/// property. Does not return until all async rules are complete.
/// </returns>
public Task<List<string>> CheckRulesAsync(int timeout)
{
return CheckRulesAsync(TimeSpan.FromMilliseconds(timeout));
}
/// <summary>
/// Invokes all rules for the business type.
/// </summary>
/// <param name="timeout">Timeout value.</param>
/// <returns>
/// Returns a list of property names affected by the invoked rules.
/// The PropertyChanged event should be raised for each affected
/// property. Does not return until all async rules are complete.
/// </returns>
public async Task<List<string>> CheckRulesAsync(TimeSpan timeout)
{
var result = CheckRules();
await WaitForAsyncRulesToComplete(timeout);
return result;
}
private async Task WaitForAsyncRulesToComplete(TimeSpan timeout)
{
if (!RunningAsyncRules)
{
return;
}
var tasks = new Task[] { BusyChanged.WaitAsync(), Task.Delay(timeout) };
var final = await Task.WhenAny(tasks);
if (final == tasks[1])
throw new TimeoutException(nameof(CheckRulesAsync));
}
/// <summary>
/// Invokes all rules for the business type.
/// </summary>
/// <returns>
/// Returns a list of property names affected by the invoked rules.
/// The PropertyChanged event should be raised for each affected
/// property.
/// </returns>
public List<string> CheckRules()
{
if (_suppressRuleChecking)
return new List<string>();
RunningRules = true;
var affectedProperties = CheckObjectRules(RuleContextModes.CheckRules, false);
var properties = TypeRules.Rules.Where(p => p.PrimaryProperty != null)
.Select(p => p.PrimaryProperty)
.Distinct();
foreach (var property in properties)
affectedProperties.AddRange(CheckRules(property, RuleContextModes.CheckRules));
RunningRules = false;
if (!RunningRules && !RunningAsyncRules)
_target.AllRulesComplete();
return affectedProperties.Distinct().ToList();
}
/// <summary>
/// Invokes all rules attached at the class level
/// of the business type.
/// </summary>
/// <returns>
/// Returns a list of property names affected by the invoked rules.
/// The PropertyChanged event should be raised for each affected
/// property.
/// </returns>
public List<string> CheckObjectRules()
{
return CheckObjectRules(RuleContextModes.CheckObjectRules, true);
}
/// <summary>
/// Invokes all rules attached at the class level
/// of the business type.
/// </summary>
/// <returns>
/// Returns a list of property names affected by the invoked rules.
/// The PropertyChanged event should be raised for each affected
/// property.
/// </returns>
private List<string> CheckObjectRules(RuleContextModes executionContext, bool cascade)
{
if (_suppressRuleChecking)
return new List<string>();
var oldRR = RunningRules;
RunningRules = true;
var rules = from r in TypeRules.Rules
where r.PrimaryProperty == null
&& CanRunRule(_applicationContext, r, executionContext)
orderby r.Priority
select r;
BrokenRules.ClearRules(null);
// Changed to cascade propertyrule to make async ObjectLevel rules rerun PropertLevel rules.
var firstResult = RunRules(rules, false, executionContext);
// rerun property level rules for affected properties
if (cascade)
{
var propertiesToRun = new List<IPropertyInfo>();
foreach (var item in rules)
if (!item.IsAsync)
{
foreach (var p in item.AffectedProperties)
propertiesToRun.Add(p);
}
// run rules for affected properties
foreach (var item in propertiesToRun.Distinct())
{
var doCascade = false;
if (CascadeOnDirtyProperties)
doCascade = firstResult.DirtyProperties.Any(p => p == item.Name);
firstResult.AffectedProperties.AddRange(CheckRulesForProperty(item, doCascade,
executionContext | RuleContextModes.AsAffectedProperty));
}
}
RunningRules = oldRR;
if (!RunningRules && !RunningAsyncRules)
_target.AllRulesComplete();
return firstResult.AffectedProperties.Distinct().ToList();
}
/// <summary>
/// Invokes all rules for a specific property of the business type.
/// </summary>
/// <param name="property">Property to check.</param>
/// <returns>
/// Returns a list of property names affected by the invoked rules.
/// The PropertyChanged event should be raised for each affected
/// property.
/// </returns>
/// <exception cref="System.ArgumentNullException">If property is null</exception>
public List<string> CheckRules(IPropertyInfo property)
{
return CheckRules(property, RuleContextModes.PropertyChanged);
}
private List<string> CheckRules(Csla.Core.IPropertyInfo property, RuleContextModes executionContext)
{
if (property == null)
throw new ArgumentNullException(nameof(property));
if (_suppressRuleChecking)
return new List<string>();
var oldRR = RunningRules;
RunningRules = true;
var affectedProperties = new List<string>();
affectedProperties.AddRange(CheckRulesForProperty(property, true, executionContext));
RunningRules = oldRR;
if (!RunningRules && !RunningAsyncRules)
_target.AllRulesComplete();
return affectedProperties.Distinct().ToList();
}
/// <summary>
/// Determines whether this rule can run the specified context mode.
/// </summary>
/// <param name="applicationContext"></param>
/// <param name="rule">The rule.</param>
/// <param name="contextMode">The context mode.</param>
/// <returns>
/// <c>true</c> if this instance [can run rule] the specified context mode; otherwise, <c>false</c>.
/// </returns>
internal static bool CanRunRule(ApplicationContext applicationContext, IBusinessRuleBase rule, RuleContextModes contextMode)
{
// default then just return true
if (rule.RunMode == RunModes.Default) return true;
bool canRun = true;
if ((contextMode & RuleContextModes.AsAffectedProperty) > 0)
canRun &= (rule.RunMode & RunModes.DenyAsAffectedProperty) == 0;
if ((rule.RunMode & RunModes.DenyOnServerSidePortal) > 0)
canRun &= applicationContext.LogicalExecutionLocation != ApplicationContext.LogicalExecutionLocations.Server;
if ((contextMode & RuleContextModes.CheckRules) > 0)
canRun &= (rule.RunMode & RunModes.DenyCheckRules) == 0;
return canRun;
}
/// <summary>
/// Invokes all rules for a specific property.
/// </summary>
/// <param name="property">The property.</param>
/// <param name="cascade">if set to <c>true</c> [cascade].</param>
/// <param name="executionMode">The execute mode.</param>
private List<string> CheckRulesForProperty(IPropertyInfo property, bool cascade, RuleContextModes executionMode)
{
// checking rules for the primary property
var primaryRules = from r in TypeRules.Rules
where ReferenceEquals(r.PrimaryProperty, property)
&& CanRunRule(_applicationContext, r, executionMode)
orderby r.Priority
select r;
BrokenRules.ClearRules(property);
var primaryResult = RunRules(primaryRules, cascade, executionMode);
if (CascadeOnDirtyProperties)
cascade = cascade || primaryResult.DirtyProperties.Any();
if (cascade)
{
// get properties affected by all rules
var propertiesToRun = new List<IPropertyInfo>();
foreach (var item in primaryRules)
if (!item.IsAsync)
{
foreach (var p in item.AffectedProperties)
if (!ReferenceEquals(property, p))
propertiesToRun.Add(p);
}
// gets a list rules of of "affected" properties by adding
// PrimaryProperty where property is in InputProperties
var inputRules = from r in TypeRules.Rules
where !ReferenceEquals(r.PrimaryProperty, property)
&& r.PrimaryProperty != null
&& r.InputProperties != null
&& r.InputProperties.Contains(property)
select r;
var dirtyProperties = primaryResult.DirtyProperties;
var inputProperties = from r in inputRules
where !r.CascadeIfDirty || dirtyProperties.Contains(r.PrimaryProperty.Name)
select r.PrimaryProperty;
foreach (var p in inputProperties)
{
if (!ReferenceEquals(property, p))
propertiesToRun.Add(p);
}
// run rules for affected properties
foreach (var item in propertiesToRun.Distinct())
{
var doCascade = false;
if (CascadeOnDirtyProperties)
doCascade = primaryResult.DirtyProperties.Any(p => p == item.Name);
primaryResult.AffectedProperties.AddRange(CheckRulesForProperty(item, doCascade,
executionMode | RuleContextModes.AsAffectedProperty));
}
}
// always make sure to add PrimaryProperty
primaryResult.AffectedProperties.Add(property.Name);
return primaryResult.AffectedProperties.Distinct().ToList();
}
[NonSerialized]
private List<IPropertyInfo> _busyProperties;
private bool _cascadeOnDirtyProperties;
private List<IPropertyInfo> BusyProperties
{
get
{
if (_busyProperties == null)
_busyProperties = new List<IPropertyInfo>();
return _busyProperties;
}
}
/// <summary>
/// Runs the enumerable list of rules.
/// </summary>
/// <param name="rules">The rules.</param>
/// <param name="cascade">if set to <c>true</c> cascade.</param>
/// <param name="executionContext">The execution context.</param>
private RunRulesResult RunRules(IEnumerable<IBusinessRuleBase> rules, bool cascade, RuleContextModes executionContext)
{
var affectedProperties = new List<string>();
var dirtyProperties = new List<string>();
bool anyRuleBroken = false;
foreach (var rule in rules)
{
// implicit short-circuiting
if (anyRuleBroken && rule.Priority > ProcessThroughPriority)
break;
bool complete = false;
// set up context
var context = new RuleContext(_applicationContext, r =>
{
if (r.Rule.IsAsync)
{
lock (SyncRoot)
{
// update output values
if (r.OutputPropertyValues != null)
foreach (var item in r.OutputPropertyValues)
{
// value is changed add to dirtyValues
if (((IManageProperties)_target).LoadPropertyMarkDirty(item.Key, item.Value))
r.AddDirtyProperty(item.Key);
}
// update broken rules list
BrokenRules.SetBrokenRules(r.Results, r.OriginPropertyName, rule.Priority);
// run rules on affected properties for this async rule
var affected = new List<string>();
if (cascade)