-
-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathBusinessBindingListBase.cs
1361 lines (1187 loc) · 40.7 KB
/
BusinessBindingListBase.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="BusinessBindingListBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>This is the base class from which most business collections</summary>
//-----------------------------------------------------------------------
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using Csla.Core;
using Csla.Properties;
using Csla.Server;
namespace Csla
{
/// <summary>
/// This is the base class from which most business collections
/// or lists will be derived.
/// </summary>
/// <typeparam name="T">Type of the business object being defined.</typeparam>
/// <typeparam name="C">Type of the child objects contained in the list.</typeparam>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[Serializable]
public abstract class BusinessBindingListBase<
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
#endif
T,
#if NET8_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
#endif
C> :
ExtendedBindingList<C>, IContainsDeletedList,
IEditableCollection, IUndoableObject, ICloneable,
ISavable, ISavable<T>, IParent, IDataPortalTarget,
IUseApplicationContext
where T : BusinessBindingListBase<T, C>
where C : IEditableBusinessObject
{
/// <summary>
/// Creates an instance of the type.
/// </summary>
protected BusinessBindingListBase()
{ }
/// <summary>
/// Gets the current ApplicationContext
/// </summary>
protected ApplicationContext ApplicationContext { get; private set; }
ApplicationContext IUseApplicationContext.ApplicationContext
{
get => ApplicationContext;
set
{
ApplicationContext = value;
InitializeIdentity();
Initialize();
AllowNew = true;
}
}
#region Initialize
/// <summary>
/// Override this method to set up event handlers so user
/// code in a partial class can respond to events raised by
/// generated code.
/// </summary>
protected virtual void Initialize()
{ /* allows subclass to initialize events before any other activity occurs */ }
#endregion
#region Identity
private int _identity = -1;
int IBusinessObject.Identity
{
get { return _identity; }
}
private void InitializeIdentity()
{
_identity = ((IParent)this).GetNextIdentity(_identity);
}
[NonSerialized]
[NotUndoable]
private IdentityManager _identityManager;
int IParent.GetNextIdentity(int current)
{
if (Parent != null)
{
return Parent.GetNextIdentity(current);
}
else
{
if (_identityManager == null)
_identityManager = new IdentityManager();
return _identityManager.GetNextIdentity(current);
}
}
#endregion
#region ICloneable
object ICloneable.Clone()
{
return GetClone();
}
/// <summary>
/// Creates a clone of the object.
/// </summary>
/// <returns>A new object containing the exact data of the original object.</returns>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual object GetClone()
{
return ObjectCloner.GetInstance(ApplicationContext).Clone(this);
}
/// <summary>
/// Creates a clone of the object.
/// </summary>
/// <returns>A new object containing the exact data of the original object.</returns>
public T Clone()
{
return (T)GetClone();
}
#endregion
#region Delete and Undelete child
private MobileList<C> _deletedList;
/// <summary>
/// A collection containing all child objects marked
/// for deletion.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design", "CA1002:DoNotExposeGenericLists")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected MobileList<C> DeletedList => _deletedList ??= [];
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design", "CA1002:DoNotExposeGenericLists")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
IEnumerable<IEditableBusinessObject> IContainsDeletedList.DeletedList => (IEnumerable<IEditableBusinessObject>)DeletedList;
private void DeleteChild(C child)
{
// set child edit level
UndoableBase.ResetChildEditLevel(child, EditLevel, false);
// mark the object as deleted
child.DeleteChild();
// and add it to the deleted collection for storage
DeletedList.Add(child);
}
private void UnDeleteChild(C child)
{
// since the object is no longer deleted, remove it from
// the deleted collection
DeletedList.Remove(child);
// we are inserting an _existing_ object so
// we need to preserve the object's editleveladded value
// because it will be changed by the normal add process
int saveLevel = child.EditLevelAdded;
Add(child);
child.EditLevelAdded = saveLevel;
}
/// <summary>
/// Returns true if the internal deleted list
/// contains the specified child object.
/// </summary>
/// <param name="item">Child object to check.</param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public bool ContainsDeleted(C item)
{
return DeletedList.Contains(item);
}
#endregion
#region Begin/Cancel/ApplyEdit
/// <summary>
/// Starts a nested edit on the object.
/// </summary>
/// <remarks>
/// <para>
/// When this method is called the object takes a snapshot of
/// its current state (the values of its variables). This snapshot
/// can be restored by calling <see cref="CancelEdit" />
/// or committed by calling <see cref="ApplyEdit" />.
/// </para><para>
/// This is a nested operation. Each call to BeginEdit adds a new
/// snapshot of the object's state to a stack. You should ensure that
/// for each call to BeginEdit there is a corresponding call to either
/// CancelEdit or ApplyEdit to remove that snapshot from the stack.
/// </para><para>
/// See Chapters 2 and 3 for details on n-level undo and state stacking.
/// </para><para>
/// This method triggers the copying of all child object states.
/// </para>
/// </remarks>
public void BeginEdit()
{
if (IsChild)
throw new NotSupportedException(Resources.NoBeginEditChildException);
CopyState(EditLevel + 1);
}
/// <summary>
/// Cancels the current edit process, restoring the object's state to
/// its previous values.
/// </summary>
/// <remarks>
/// Calling this method causes the most recently taken snapshot of the
/// object's state to be restored. This resets the object's values
/// to the point of the last <see cref="BeginEdit" />
/// call.
/// <para>
/// This method triggers an undo in all child objects.
/// </para>
/// </remarks>
public void CancelEdit()
{
if (IsChild)
throw new NotSupportedException(Resources.NoCancelEditChildException);
UndoChanges(EditLevel - 1);
}
/// <summary>
/// Commits the current edit process.
/// </summary>
/// <remarks>
/// Calling this method causes the most recently taken snapshot of the
/// object's state to be discarded, thus committing any changes made
/// to the object's state since the last
/// <see cref="BeginEdit" /> call.
/// <para>
/// This method triggers an <see cref="Core.BusinessBase.ApplyEdit"/>
/// in all child objects.
/// </para>
/// </remarks>
public void ApplyEdit()
{
if (IsChild)
throw new NotSupportedException(Resources.NoApplyEditChildException);
AcceptChanges(EditLevel - 1);
}
Task IParent.ApplyEditChild(IEditableBusinessObject child)
{
EditChildComplete(child);
return Task.CompletedTask;
}
IParent IParent.Parent
{
get { return Parent; }
}
/// <summary>
/// Override this method to be notified when a child object's
/// <see cref="Core.BusinessBase.ApplyEdit" /> method has
/// completed.
/// </summary>
/// <param name="child">The child object that was edited.</param>
protected virtual void EditChildComplete(IEditableBusinessObject child)
{
// do nothing, we don't really care
// when a child has its edits applied
}
#endregion
#region Insert, Remove, Clear
/// <summary>
/// Override this method to create a new object that is added
/// to the collection.
/// </summary>
protected override object AddNewCore()
{
var dp = ApplicationContext.CreateInstanceDI<DataPortal<C>>();
var item = dp.CreateChild();
Add(item);
return item;
}
/// <summary>
/// This method is called by a child object when it
/// wants to be removed from the collection.
/// </summary>
/// <param name="child">The child object to remove.</param>
void IEditableCollection.RemoveChild(IEditableBusinessObject child)
{
Remove((C)child);
}
object IEditableCollection.GetDeletedList()
{
return DeletedList;
}
/// <summary>
/// This method is called by a child object when it
/// wants to be removed from the collection.
/// </summary>
/// <param name="child">The child object to remove.</param>
Task IParent.RemoveChild(IEditableBusinessObject child)
{
Remove((C)child);
return Task.CompletedTask;
}
/// <summary>
/// Sets the edit level of the child object as it is added.
/// </summary>
/// <param name="index">Index of the item to insert.</param>
/// <param name="item">Item to insert.</param>
protected override void InsertItem(int index, C item)
{
if (item.IsChild)
{
IdentityManager.EnsureNextIdentityValueIsUnique(this, this);
// set parent reference
item.SetParent(this);
// ensure child uses same context as parent
if (item is IUseApplicationContext iuac)
iuac.ApplicationContext = ApplicationContext;
// set child edit level
UndoableBase.ResetChildEditLevel(item, EditLevel, false);
// when an object is inserted we assume it is
// a new object and so the edit level when it was
// added must be set
item.EditLevelAdded = EditLevel;
base.InsertItem(index, item);
}
else
{
// item must be marked as a child object
throw new InvalidOperationException(Resources.ListItemNotAChildException);
}
}
/// <summary>
/// Marks the child object for deletion and moves it to
/// the collection of deleted objects.
/// </summary>
/// <param name="index">Index of the item to remove.</param>
protected override void RemoveItem(int index)
{
// when an object is 'removed' it is really
// being deleted, so do the deletion work
C child = this[index];
using (LoadListMode)
{
base.RemoveItem(index);
}
if (!_completelyRemoveChild)
{
// the child shouldn't be completely removed,
// so copy it to the deleted list
DeleteChild(child);
}
if (RaiseListChangedEvents)
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, index));
}
/// <summary>
/// Replaces the item at the specified index with
/// the specified item, first moving the original
/// item to the deleted list.
/// </summary>
/// <param name="index">The zero-based index of the item to replace.</param>
/// <param name="item">
/// The new value for the item at the specified index.
/// The value can be null for reference types.
/// </param>
/// <remarks></remarks>
protected override void SetItem(int index, C item)
{
C child = default(C);
if (!(ReferenceEquals(this[index], item)))
child = this[index];
// replace the original object with this new
// object
using (LoadListMode)
{
// set parent reference
item.SetParent(this);
// set child edit level
UndoableBase.ResetChildEditLevel(item, EditLevel, false);
// reset EditLevelAdded
item.EditLevelAdded = EditLevel;
// add to list
base.SetItem(index, item);
}
if (child != null)
DeleteChild(child);
if (RaiseListChangedEvents)
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, index));
}
/// <summary>
/// Clears the collection, moving all active
/// items to the deleted list.
/// </summary>
protected override void ClearItems()
{
while (Count > 0)
RemoveItem(0);
base.ClearItems();
}
#endregion
#region Edit level tracking
// keep track of how many edit levels we have
/// <summary>
/// Returns the current edit level of the object.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
protected int EditLevel { get; private set; }
int IUndoableObject.EditLevel
{
get
{
return EditLevel;
}
}
#endregion
#region N-level undo
void IUndoableObject.CopyState(int parentEditLevel, bool parentBindingEdit)
{
if (!parentBindingEdit)
CopyState(parentEditLevel);
}
void IUndoableObject.UndoChanges(int parentEditLevel, bool parentBindingEdit)
{
if (!parentBindingEdit)
UndoChanges(parentEditLevel);
}
void IUndoableObject.AcceptChanges(int parentEditLevel, bool parentBindingEdit)
{
if (!parentBindingEdit)
AcceptChanges(parentEditLevel);
}
private void CopyState(int parentEditLevel)
{
if (EditLevel + 1 > parentEditLevel)
throw new UndoException(string.Format(Resources.EditLevelMismatchException, "CopyState"), GetType().Name, _parent?.GetType().Name, EditLevel, parentEditLevel - 1);
// we are going a level deeper in editing
EditLevel += 1;
// cascade the call to all child objects
foreach (C child in this)
child.CopyState(EditLevel, false);
// cascade the call to all deleted child objects
foreach (C child in DeletedList)
child.CopyState(EditLevel, false);
}
private bool _completelyRemoveChild;
private void UndoChanges(int parentEditLevel)
{
C child;
if (EditLevel - 1 != parentEditLevel)
throw new UndoException(string.Format(Resources.EditLevelMismatchException, "UndoChanges"), GetType().Name, _parent?.GetType().Name, EditLevel, parentEditLevel + 1);
// we are coming up one edit level
EditLevel -= 1;
if (EditLevel < 0) EditLevel = 0;
try
{
using (LoadListMode)
{
// Cancel edit on all current items
for (int index = Count - 1; index >= 0; index--)
{
child = this[index];
child.UndoChanges(EditLevel, false);
// if item is below its point of addition, remove
if (child.EditLevelAdded > EditLevel)
{
bool oldAllowRemove = AllowRemove;
try
{
AllowRemove = true;
_completelyRemoveChild = true;
RemoveAt(index);
}
finally
{
_completelyRemoveChild = false;
AllowRemove = oldAllowRemove;
}
}
}
// cancel edit on all deleted items
for (int index = DeletedList.Count - 1; index >= 0; index--)
{
child = DeletedList[index];
child.UndoChanges(EditLevel, false);
if (child.EditLevelAdded > EditLevel)
{
// if item is below its point of addition, remove
DeletedList.RemoveAt(index);
}
else
{
// if item is no longer deleted move back to main list
if (!child.IsDeleted) UnDeleteChild(child);
}
}
}
}
finally
{
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
}
private void AcceptChanges(int parentEditLevel)
{
if (EditLevel - 1 != parentEditLevel)
throw new UndoException(string.Format(Resources.EditLevelMismatchException, "AcceptChanges"), GetType().Name, _parent?.GetType().Name, EditLevel, parentEditLevel + 1);
// we are coming up one edit level
EditLevel -= 1;
if (EditLevel < 0) EditLevel = 0;
// cascade the call to all child objects
foreach (C child in this)
{
child.AcceptChanges(EditLevel, false);
// if item is below its point of addition, lower point of addition
if (child.EditLevelAdded > EditLevel) child.EditLevelAdded = EditLevel;
}
// cascade the call to all deleted child objects
for (int index = DeletedList.Count - 1; index >= 0; index--)
{
C child = DeletedList[index];
child.AcceptChanges(EditLevel, false);
// if item is below its point of addition, remove
if (child.EditLevelAdded > EditLevel)
DeletedList.RemoveAt(index);
}
}
#endregion
#region Mobile Object overrides
/// <summary>
/// Override this method to insert your field values
/// into the MobileFormatter serialization stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnGetState(Serialization.Mobile.SerializationInfo info)
{
info.AddValue("Csla.BusinessListBase._isChild", _isChild);
info.AddValue("Csla.BusinessListBase._editLevel", EditLevel);
info.AddValue("Csla.Core.BusinessBase._identity", _identity);
base.OnGetState(info);
}
/// <summary>
/// Override this method to retrieve your field values
/// from the MobileFormatter serialization stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnSetState(Serialization.Mobile.SerializationInfo info)
{
_isChild = info.GetValue<bool>("Csla.BusinessListBase._isChild");
EditLevel = info.GetValue<int>("Csla.BusinessListBase._editLevel");
_identity = info.GetValue<int>("Csla.Core.BusinessBase._identity");
base.OnSetState(info);
}
/// <summary>
/// Override this method to insert child objects
/// into the MobileFormatter serialization stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
/// <param name="formatter">
/// Reference to the current SerializationFormatterFactory.GetFormatter().
/// </param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnGetChildren(Serialization.Mobile.SerializationInfo info, Serialization.Mobile.MobileFormatter formatter)
{
base.OnGetChildren(info, formatter);
if (_deletedList != null)
{
var fieldManagerInfo = formatter.SerializeObject(_deletedList);
info.AddChild("_deletedList", fieldManagerInfo.ReferenceId);
}
}
/// <summary>
/// Override this method to get child objects
/// from the MobileFormatter serialization stream.
/// </summary>
/// <param name="info">
/// Object containing the serialized data.
/// </param>
/// <param name="formatter">
/// Reference to the current SerializationFormatterFactory.GetFormatter().
/// </param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnSetChildren(Serialization.Mobile.SerializationInfo info, Serialization.Mobile.MobileFormatter formatter)
{
if (info.Children.TryGetValue("_deletedList", out var child))
{
_deletedList = (MobileList<C>)formatter.GetObject(child.ReferenceId);
}
base.OnSetChildren(info, formatter);
}
#endregion
#region IsChild
[NotUndoable]
private bool _isChild = false;
/// <summary>
/// Indicates whether this collection object is a child object.
/// </summary>
/// <returns>True if this is a child object.</returns>
[Browsable(false)]
[Display(AutoGenerateField = false)]
[ScaffoldColumn(false)]
public bool IsChild
{
get { return _isChild; }
}
/// <summary>
/// Marks the object as being a child object.
/// </summary>
/// <remarks>
/// <para>
/// By default all business objects are 'parent' objects. This means
/// that they can be directly retrieved and updated into the database.
/// </para><para>
/// We often also need child objects. These are objects which are contained
/// within other objects. For instance, a parent Invoice object will contain
/// child LineItem objects.
/// </para><para>
/// To create a child object, the MarkAsChild method must be called as the
/// object is created. Please see Chapter 7 for details on the use of the
/// MarkAsChild method.
/// </para>
/// </remarks>
protected void MarkAsChild()
{
_identity = -1;
_isChild = true;
}
#endregion
#region IsDirty, IsValid, IsSavable
/// <summary>
/// Await this method to ensure business object is not busy.
/// </summary>
public async Task WaitForIdle()
{
var cslaOptions = ApplicationContext.GetRequiredService<Configuration.CslaOptions>();
await WaitForIdle(TimeSpan.FromSeconds(cslaOptions.DefaultWaitForIdleTimeoutInSeconds)).ConfigureAwait(false);
}
/// <summary>
/// Gets a value indicating whether this object's data has been changed.
/// </summary>
bool ITrackStatus.IsSelfDirty
{
get { return IsDirty; }
}
/// <summary>
/// Gets a value indicating whether this object's data has been changed.
/// </summary>
[Browsable(false)]
[Display(AutoGenerateField = false)]
[ScaffoldColumn(false)]
public bool IsDirty
{
get
{
// any non-new deletions make us dirty
foreach (C item in DeletedList)
if (!item.IsNew)
return true;
// run through all the child objects
// and if any are dirty then then
// collection is dirty
foreach (C child in this)
if (child.IsDirty)
return true;
return false;
}
}
bool ITrackStatus.IsSelfValid
{
get { return IsSelfValid; }
}
/// <summary>
/// Gets a value indicating whether this object is currently in
/// a valid state (has no broken validation rules).
/// </summary>
protected virtual bool IsSelfValid
{
get { return IsValid; }
}
/// <summary>
/// Gets a value indicating whether this object is currently in
/// a valid state (has no broken validation rules).
/// </summary>
[Browsable(false)]
[Display(AutoGenerateField = false)]
[ScaffoldColumn(false)]
public virtual bool IsValid
{
get
{
// run through all the child objects
// and if any are invalid then the
// collection is invalid
foreach (C child in this)
if (!child.IsValid)
return false;
return true;
}
}
/// <summary>
/// Returns true if this object is both dirty and valid.
/// </summary>
/// <returns>A value indicating if this object is both dirty and valid.</returns>
[Browsable(false)]
[Display(AutoGenerateField = false)]
public virtual bool IsSavable
{
get
{
var result = IsDirty && IsValid && !IsBusy;
if (result)
result = Rules.BusinessRules.HasPermission(ApplicationContext, Rules.AuthorizationActions.EditObject, this);
return result;
}
}
/// <summary>
/// Gets the busy status for this object and its child objects.
/// </summary>
public override bool IsBusy
{
get
{
// run through all the child objects
// and if any are busy then then
// collection is busy
foreach (C item in DeletedList)
if (item.IsBusy)
return true;
foreach (C child in this)
if (child.IsBusy)
return true;
return false;
}
}
#endregion
#region ITrackStatus
bool ITrackStatus.IsNew
{
get
{
return false;
}
}
bool ITrackStatus.IsDeleted
{
get
{
return false;
}
}
#endregion
#region Child Data Access
/// <summary>
/// Initializes a new instance of the object
/// with default values.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_Create()
{ /* do nothing - list self-initializes */ }
/// <summary>
/// Saves all items in the list, automatically
/// performing insert, update or delete operations
/// as necessary.
/// </summary>
/// <param name="parameters">
/// Optional parameters passed to child update
/// methods.
/// </param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_Update(params object[] parameters)
{
using (LoadListMode)
{
var dp = ApplicationContext.CreateInstanceDI<DataPortal<C>>();
foreach (var child in DeletedList)
dp.UpdateChild(child, parameters);
DeletedList.Clear();
foreach (var child in this)
if (child.IsDirty) dp.UpdateChild(child, parameters);
}
}
/// <summary>
/// Asynchronously saves all items in the list, automatically
/// performing insert, update or delete operations as necessary.
/// </summary>
/// <param name="parameters">
/// Optional parameters passed to child update
/// methods.
/// </param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[UpdateChild]
protected virtual async Task Child_UpdateAsync(params object[] parameters)
{
using (LoadListMode)
{
var dp = ApplicationContext.CreateInstanceDI<DataPortal<C>>();
foreach (var child in DeletedList)
await dp.UpdateChildAsync(child, parameters).ConfigureAwait(false);
DeletedList.Clear();
foreach (var child in this)
if (child.IsDirty) await dp.UpdateChildAsync(child, parameters).ConfigureAwait(false);
}
}
#endregion
#region Data Access
/// <summary>
/// Saves the object to the database.
/// </summary>
/// <remarks>
/// <para>
/// Calling this method starts the save operation, causing the all child
/// objects to be inserted, updated or deleted within the database based on the
/// each object's current state.
/// </para><para>
/// All this is contingent on <see cref="IsDirty" />. If
/// this value is false, no data operation occurs.
/// It is also contingent on <see cref="IsValid" />. If this value is
/// false an exception will be thrown to
/// indicate that the UI attempted to save an invalid object.
/// </para><para>
/// It is important to note that this method returns a new version of the
/// business collection that contains any data updated during the save operation.
/// You MUST update all object references to use this new version of the
/// business collection in order to have access to the correct object data.
/// </para><para>
/// You can override this method to add your own custom behaviors to the save
/// operation. For instance, you may add some security checks to make sure
/// the user can save the object. If all security checks pass, you would then
/// invoke the base Save method via <c>MyBase.Save()</c>.
/// </para>
/// </remarks>
/// <returns>A new object containing the saved values.</returns>
public T Save()
{
try
{
return SaveAsync(null, true).Result;
}
catch (AggregateException ex)
{
if (ex.InnerExceptions.Count > 0)
throw ex.InnerExceptions[0];
else
throw;
}
}
/// <summary>
/// Saves the object to the database.
/// </summary>
public async Task<T> SaveAsync()
{
return await SaveAsync(null, false);
}
/// <summary>
/// Saves the object to the database.
/// </summary>
/// <param name="userState">User state data.</param>
/// <param name="isSync">True if the save operation should be synchronous.</param>
protected virtual async Task<T> SaveAsync(object userState, bool isSync)
{
T result;
if (IsChild)
throw new InvalidOperationException(Resources.NoSaveChildException);
if (EditLevel > 0)
throw new InvalidOperationException(Resources.NoSaveEditingException);
if (!IsValid)
throw new Rules.ValidationException(Resources.NoSaveInvalidException);
if (IsBusy)
throw new InvalidOperationException(Resources.BusyObjectsMayNotBeSaved);
if (IsDirty)
{
var dp = ApplicationContext.CreateInstanceDI<DataPortal<T>>();
if (isSync)
{
result = dp.Update((T)this);
}
else
{
result = await dp.UpdateAsync((T)this);
}
}
else
{
result = (T)this;
}
OnSaved(result, null, userState);
return result;