-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathunitofwork.html
More file actions
1123 lines (976 loc) · 54.9 KB
/
Copy pathunitofwork.html
File metadata and controls
1123 lines (976 loc) · 54.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UnitOfWork<T> - Beep Data Management Engine Documentation</title>
<link rel="stylesheet" href="sphinx-style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
</head>
<body>
<!-- Mobile Menu Toggle -->
<button class="mobile-menu-toggle" onclick="toggleSidebar()">
<i class="bi bi-list"></i>
</button>
<!-- Theme Toggle -->
<button class="theme-toggle" onclick="toggleTheme()" title="Toggle theme">
<i class="bi bi-sun-fill" id="theme-icon"></i>
</button>
<div class="container">
<!-- Sidebar -->
<aside class="sidebar" id="sidebar">
<!-- Navigation will be loaded dynamically -->
</aside>
<!-- Main Content -->
<main class="content">
<div class="content-wrapper">
<!-- Breadcrumb -->
<nav class="breadcrumb-nav">
<a href="index.html">Home</a>
<span>></span>
<span>UnitOfWork Pattern</span>
</nav>
<!-- Page Header -->
<div class="page-header">
<h1>UnitOfWork<T></h1>
<p class="page-subtitle">Generic Unit of Work pattern implementation with change tracking and validation
</p>
</div>
<div class="note">
<strong>Source of truth (2026) — 20 files in Editor/UOW/</strong>
<ul>
<li><code>UnitofWork.Core.cs</code> — Constructors (7), ~30 properties, OBL wiring, helper composition, ChangeSummary, Export/Import, Dispose</li>
<li><code>UnitofWork.CRUD.cs</code> — Read/Get/New/Add/Update/Insert/Delete with async variants</li>
<li><code>UnitofWork.Core.Extensions.cs</code> — 13 lifecycle events (Pre/Post Create,Insert,Update,Delete,Query,Commit,Edit), Commit/Rollback, AddRange/UpdateRange/DeleteRange, RevertItem, FindAsync</li>
<li><code>UnitofWork.Core.Utilities.cs</code> — Clear, navigation (MoveFirst/Next/Previous/Last/MoveTo), state queries (DocExist, FindDocIdx, Getindex, GetTrackingItem)</li>
<li><code>UnitofWork.OBLIntegration.cs</code> — Validation, Undo/Redo, Computed Columns, Bookmarks, Thread Safety, Aggregates, Virtual Loading</li>
<li><code>IUnitofWorkCapabilities.cs</code> — 7 interfaces: IRevertable, IBatchCommittable, IExportable, IImportable, IAggregatable, IUndoable, IMergeable, IUnitofWorkHistory</li>
<li><code>UnitOfWorkFactory.cs</code> (517 lines) — Runtime type creation, caching, validation</li>
<li><code>UnitOfWorkWrapper.cs</code> (1164 lines) — Late-bound wrapper with full CRUD, navigation, events</li>
<li><code>UnitOfWorkWrapperExtensions.cs</code> — ForEachRecordAsync, FindRecord, BatchInsertAsync, etc.</li>
<li><code>Helpers/</code> — StateHelper, DataHelper, CollectionHelper, ValidationHelper, EventHelper, DefaultsHelper, QueryHistory, ExportHelper</li>
<li><code>Models/</code> — QueryHistoryEntry, ChangeSummary, CommitBatchProgress, CommitBatchResult</li>
</ul>
</div>
<!-- Table of Contents -->
<div class="toc">
<h3>📚 Table of Contents</h3>
<ul>
<li><a href="#overview">Overview</a></li>
<li><a href="#constructors">Constructors</a></li>
<li><a href="#core-properties">Core Properties</a></li>
<li><a href="#data-retrieval">Data Retrieval</a></li>
<li><a href="#crud-operations">CRUD Operations</a></li>
<li><a href="#transaction-management">Transaction Management</a></li>
<li><a href="#change-tracking">Change Tracking</a></li>
<li><a href="#navigation">Navigation</a></li>
<li><a href="#events">Events</a></li>
<li><a href="#undo-redo">Undo/Redo</a></li>
<li><a href="#logging">Logging</a></li>
<li><a href="#capability-interfaces">Capability Interfaces</a></li>
<li><a href="#batch-commit">Batch Commit</a></li>
<li><a href="#obl-change-inspection">OBL Change Inspection</a></li>
<li><a href="#revert-merge">Revert & Merge</a></li>
<li><a href="#change-history">Change History & Audit</a></li>
<li><a href="#export-import">Export & Import</a></li>
<li><a href="#advanced-aggregates">Advanced Aggregates</a></li>
<li><a href="#best-practices">Best Practices</a></li>
</ul>
</div>
<!-- Overview -->
<section id="overview" class="section">
<h2>Overview</h2>
<p>
The <code>UnitOfWork<T></code> class implements the Unit of Work pattern for managing a collection of
entities of type T. It provides change tracking, validation, CRUD operations, and transaction management for
a single entity type within a data source.
</p>
<div class="success">
<strong>🎯 Key Features</strong>
<ul>
<li>Generic implementation for any Entity type</li>
<li>Automatic change tracking and state management</li>
<li>Observable collections with property change notifications</li>
<li>Field-level change inspection via OBL (Phase 1)</li>
<li>Filtering and pagination support</li>
<li>Full Undo/Redo stack (<code>IUndoable</code>)</li>
<li>Batch commit with chunked progress (<code>IBatchCommittable</code>)</li>
<li>Per-item revert & server-merge (<code>IRevertable</code> / <code>IMergeable</code>)</li>
<li>JSON / CSV export and import (<code>IExportable</code> / <code>IImportable</code>)</li>
<li>Change history & query audit log (<code>IUnitofWorkHistory</code>)</li>
<li>Advanced in-memory aggregates: SumWhere, GroupBy, etc. (<code>IAggregatable</code>)</li>
<li>Async CRUD operations</li>
<li>Event-driven architecture with lifecycle hooks</li>
<li>Validation and error handling</li>
</ul>
</div>
<div class="code-example">
<h3>Signature-Verified Snapshot</h3>
<pre><code class="language-csharp">public partial class UnitofWork<T>
: IUnitofWork<T>, INotifyPropertyChanged,
IRevertable, IBatchCommittable, IExportable, IImportable,
IAggregatable, IUndoable, IMergeable, IUnitofWorkHistory
where T : Entity, new()
{
public UnitofWork();
public UnitofWork(IDMEEditor dMEEditor, string datasourceName, string entityName);
public UnitofWork(IDMEEditor dMEEditor, string datasourceName, string entityName, EntityStructure entityStructure);
public UnitofWork(IDMEEditor dMEEditor, string datasourceName, string entityName, string primarykey);
public UnitofWork(IDMEEditor dMEEditor, string datasourceName, string entityName, EntityStructure entityStructure, string primarykey);
public UnitofWork(IDMEEditor dMEEditor, bool isInListMode, ObservableBindingList<T> ts);
public UnitofWork(IDMEEditor dMEEditor, bool isInListMode, ObservableBindingList<T> ts, string primarykey);
public bool IsDirty { get; }
public bool IsLogging { get; set; }
public string SoftDeleteFieldName { get; set; }
public bool IncludeDeleted { get; set; }
public ConcurrencyMode ConcurrencyMode { get; set; }
public CommitOrder CommitOrder { get; set; }
}</code></pre>
</div>
</section>
<!-- Constructors -->
<section id="constructors" class="section">
<h2>Constructors</h2>
<div class="code-example">
<h3>Basic Constructor</h3>
<pre><code class="language-csharp">public UnitofWork(IDMEEditor dMEEditor, string datasourceName, string entityName, string primarykey)</code></pre>
</div>
<div class="code-example">
<h3>With Entity Structure</h3>
<pre><code class="language-csharp">public UnitofWork(IDMEEditor dMEEditor, string datasourceName, string entityName, EntityStructure entityStructure, string primarykey)</code></pre>
</div>
<div class="code-example">
<h3>List Mode Constructor</h3>
<pre><code class="language-csharp">public UnitofWork(IDMEEditor dMEEditor, bool isInListMode, ObservableBindingList<T> ts, string primarykey)</code></pre>
</div>
<table class="property-table">
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>dMEEditor</td>
<td>IDMEEditor</td>
<td>Data management editor instance</td>
</tr>
<tr>
<td>datasourceName</td>
<td>string</td>
<td>Name of the data source</td>
</tr>
<tr>
<td>entityName</td>
<td>string</td>
<td>Name of the entity</td>
</tr>
<tr>
<td>primarykey</td>
<td>string</td>
<td>Name of the primary key field</td>
</tr>
<tr>
<td>entityStructure</td>
<td>EntityStructure</td>
<td>Metadata about the entity structure</td>
</tr>
<tr>
<td>isInListMode</td>
<td>bool</td>
<td>True for in-memory operations only</td>
</tr>
<tr>
<td>ts</td>
<td>ObservableBindingList<T></td>
<td>Initial collection for list mode</td>
</tr>
</tbody>
</table>
<div class="code-example">
<h3>Usage Examples</h3>
<pre><code class="language-csharp">// Create UnitOfWork for Customer entities
var customerUoW = new UnitofWork<Customer>(dmeEditor, "SqlServer", "Customers", "CustomerID");
// Create UnitOfWork with entity structure
var orderUoW = new UnitofWork<Order>(dmeEditor, "MongoDB", "Orders", orderStructure, "OrderID");
// Create UnitOfWork in list mode (in-memory)
var tempCustomers = new ObservableBindingList<Customer>();
var listUoW = new UnitofWork<Customer>(dmeEditor, true, tempCustomers, "CustomerID");</code></pre>
</div>
</section>
<!-- Core Properties -->
<section id="core-properties" class="section">
<h2>Core Properties</h2>
<table class="property-table">
<thead>
<tr>
<th>Property</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Units</td>
<td>ObservableBindingList<T></td>
<td>The main collection of entities (filtered or unfiltered)</td>
</tr>
<tr>
<td>FilteredUnits</td>
<td>ObservableBindingList<T></td>
<td>Filtered collection when filters are applied</td>
</tr>
<tr>
<td>CurrentItem</td>
<td>T</td>
<td>Currently selected entity in the collection</td>
</tr>
<tr>
<td>IsDirty</td>
<td>bool</td>
<td>True if there are uncommitted changes</td>
</tr>
<tr>
<td>IsInListMode</td>
<td>bool</td>
<td>True for in-memory operations only</td>
</tr>
<tr>
<td>PrimaryKey</td>
<td>string</td>
<td>Name of the primary key field</td>
</tr>
<tr>
<td>EntityName</td>
<td>string</td>
<td>Name of the entity</td>
</tr>
<tr>
<td>DataSource</td>
<td>IDataSource</td>
<td>Associated data source</td>
</tr>
<tr>
<td>IsIdentity</td>
<td>bool</td>
<td>True if primary key is auto-generated</td>
</tr>
<tr>
<td>IsLogging</td>
<td>bool</td>
<td>Enable/disable change logging</td>
</tr>
<tr>
<td>SoftDeleteFieldName</td>
<td>string</td>
<td>Field name used for soft-delete behavior</td>
</tr>
<tr>
<td>IncludeDeleted</td>
<td>bool</td>
<td>Includes soft-deleted rows in retrieval queries</td>
</tr>
<tr>
<td>ConcurrencyMode</td>
<td>ConcurrencyMode</td>
<td>Optimistic concurrency behavior for updates/deletes</td>
</tr>
<tr>
<td>CommitOrder</td>
<td>CommitOrder</td>
<td>Commit ordering strategy for FK-safe persistence</td>
</tr>
</tbody>
</table>
</section>
<!-- Data Retrieval -->
<section id="data-retrieval" class="section">
<h2>Data Retrieval Methods</h2>
<div class="code-example">
<h3>Get All Entities</h3>
<pre><code class="language-csharp">public virtual async Task<ObservableBindingList<T>> Get()</code></pre>
<p>Retrieves all entities from the data source.</p>
</div>
<div class="code-example">
<h3>Get with Filters</h3>
<pre><code class="language-csharp">public virtual async Task<ObservableBindingList<T>> Get(List<AppFilter> filters)</code></pre>
<p>Retrieves entities with applied filters.</p>
</div>
<div class="code-example">
<h3>Custom Query</h3>
<pre><code class="language-csharp">public virtual async Task<ObservableBindingList<T>> GetQuery(string query)</code></pre>
<p>Executes a custom query and returns results.</p>
</div>
<div class="code-example">
<h3>Get by Primary Key</h3>
<pre><code class="language-csharp">public virtual T Get(string primaryKeyId)</code></pre>
<p>Gets a single entity by its primary key value.</p>
</div>
<div class="code-example">
<h3>Usage Examples</h3>
<pre><code class="language-csharp">// Get all customers
var allCustomers = await customerUoW.Get();
// Get customers with filters
var filters = new List<AppFilter>
{
new AppFilter {FieldName = "Country", Operator = "=", FilterValue = "USA" },
new AppFilter {FieldName = "Status", Operator = "=", FilterValue = "Active" }
};
var filteredCustomers = await customerUoW.Get(filters);
// Get customer by ID
var customer = customerUoW.Get("CUST001");
// Custom query
var queryResult = await customerUoW.GetQuery("SELECT * FROM Customers WHERE CreateDate > '2023-01-01'");</code></pre>
</div>
</section>
<!-- CRUD Operations -->
<section id="crud-operations" class="section">
<h2>CRUD Operations</h2>
<h3>Create Operations</h3>
<div class="code-example">
<pre><code class="language-csharp">public void New() // Creates a new entity and adds it to the collection
public void Add(T entity) // Adds an existing entity to the collection</code></pre>
</div>
<h3>Insert Operations</h3>
<div class="code-example">
<pre><code class="language-csharp">public async Task<IErrorsInfo> InsertAsync(T doc) // Async insert to data source
public IErrorsInfo InsertDoc(T doc) // Sync insert to data source</code></pre>
</div>
<h3>Update Operations</h3>
<div class="code-example">
<pre><code class="language-csharp">public async Task<IErrorsInfo> UpdateAsync(T doc) // Async update in data source
public IErrorsInfo Update(T entity) // Update entity in collection</code></pre>
</div>
<h3>Delete Operations</h3>
<div class="code-example">
<pre><code class="language-csharp">public async Task<IErrorsInfo> DeleteAsync(T doc) // Async delete from data source
public IErrorsInfo Delete(T entity) // Delete entity from collection
public IErrorsInfo Delete(string id) // Delete entity by primary key</code></pre>
</div>
<div class="code-example">
<h3>Complete CRUD Example</h3>
<pre><code class="language-csharp">using (var customerUoW = new UnitofWork<Customer>(dmeEditor, "SqlServer", "Customers", "CustomerID"))
{
// Create new customer
customerUoW.New();
var newCustomer = customerUoW.CurrentItem;
newCustomer.Name = "John Doe";
newCustomer.Email = "john@example.com";
// Add existing customer
var existingCustomer = new Customer { Name = "Jane Smith" };
customerUoW.Add(existingCustomer);
// Insert to database
var insertResult = await customerUoW.InsertAsync(newCustomer);
if (insertResult.Flag == Errors.Ok)
{
Console.WriteLine("Customer inserted successfully");
}
// Update customer
newCustomer.Email = "newemail@example.com";
var updateResult = await customerUoW.UpdateAsync(newCustomer);
// Delete customer
var deleteResult = await customerUoW.DeleteAsync(newCustomer);
// Delete by ID
customerUoW.Delete("CUST001");
}</code></pre>
</div>
</section>
<!-- Transaction Management -->
<section id="transaction-management" class="section">
<h2>Transaction Management</h2>
<div class="code-example">
<h3>Commit Operations</h3>
<pre><code class="language-csharp">public virtual async Task<IErrorsInfo> Commit()
public virtual async Task<IErrorsInfo> Commit(IProgress<PassedArgs> progress, CancellationToken token)</code></pre>
<p>Commits all pending changes to the data source with optional progress reporting and cancellation support.</p>
</div>
<div class="code-example">
<h3>Rollback Operations</h3>
<pre><code class="language-csharp">public Task<IErrorsInfo> Rollback()</code></pre>
<p>Rolls back all uncommitted changes.</p>
</div>
<div class="code-example">
<h3>Transaction Example</h3>
<pre><code class="language-csharp">try
{
// Make multiple changes
customerUoW.New();
var customer1 = customerUoW.CurrentItem;
customer1.Name = "Customer 1";
customerUoW.New();
var customer2 = customerUoW.CurrentItem;
customer2.Name = "Customer 2";
// Commit all changes
var result = await customerUoW.Commit();
if (result.Flag == Errors.Ok)
{
Console.WriteLine("All changes committed");
}
else
{
Console.WriteLine($"Commit failed: {result.Message}");
await customerUoW.Rollback();
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
await customerUoW.Rollback();
}</code></pre>
</div>
</section>
<!-- Change Tracking -->
<section id="change-tracking" class="section">
<h2>Change Tracking</h2>
<p>The UnitOfWork automatically tracks changes to entities with the following states:</p>
<div class="feature-grid">
<div class="feature-card">
<h3>➕ Added</h3>
<p>New entities not yet persisted to the data source</p>
</div>
<div class="feature-card">
<h3>✏️ Modified</h3>
<p>Existing entities with property changes</p>
</div>
<div class="feature-card">
<h3>🗑️ Deleted</h3>
<p>Entities marked for removal from data source</p>
</div>
<div class="feature-card">
<h3>➖ Unchanged</h3>
<p>Entities with no modifications since last commit</p>
</div>
</div>
<div class="code-example">
<h3>Change Tracking Methods</h3>
<pre><code class="language-csharp">public IEnumerable<int> GetAddedEntities() // Get indexes of added entities
public IEnumerable<int> GetModifiedEntities() // Get indexes of modified entities
public IEnumerable<T> GetDeletedEntities() // Get deleted entities
public bool GetIsDirty() // Check if there are uncommitted changes</code></pre>
</div>
<div class="code-example">
<h3>Change Tracking Example</h3>
<pre><code class="language-csharp">// Check for changes
if (customerUoW.IsDirty)
{
var added = customerUoW.GetAddedEntities();
var modified = customerUoW.GetModifiedEntities();
var deleted = customerUoW.GetDeletedEntities();
Console.WriteLine($"Changes: Added={added.Count()}, Modified={modified.Count()}, Deleted={deleted.Count()}");
// Detailed tracking
foreach (var addedIndex in added)
{
var entity = customerUoW.Units[addedIndex];
Console.WriteLine($"Added: {entity.Name}");
}
}</code></pre>
</div>
</section>
<!-- Navigation -->
<section id="navigation" class="section">
<h2>Navigation Methods</h2>
<div class="code-example">
<h3>Navigation API</h3>
<pre><code class="language-csharp">public void MoveFirst() // Move to first entity
public void MoveNext() // Move to next entity
public void MovePrevious() // Move to previous entity
public void MoveLast() // Move to last entity
public void MoveTo(int index) // Move to specific position</code></pre>
</div>
<div class="code-example">
<h3>Navigation Example</h3>
<pre><code class="language-csharp">// Navigate through records
customerUoW.MoveFirst();
Console.WriteLine($"First customer: {customerUoW.CurrentItem.Name}");
customerUoW.MoveNext();
Console.WriteLine($"Next customer: {customerUoW.CurrentItem.Name}");
// Move to specific position
customerUoW.MoveTo(5);
Console.WriteLine($"Customer at position 5: {customerUoW.CurrentItem.Name}");
// Check current position
Console.WriteLine($"Current position: {customerUoW.Units.IndexOf(customerUoW.CurrentItem)}");
Console.WriteLine($"Total records: {customerUoW.Units.Count}");</code></pre>
</div>
</section>
<!-- Events -->
<section id="events" class="section">
<h2>Events</h2>
<p>The UnitOfWork provides comprehensive event support for lifecycle management:</p>
<table class="property-table">
<thead>
<tr>
<th>Event</th>
<th>When Fired</th>
<th>Cancellable</th>
</tr>
</thead>
<tbody>
<tr>
<td>PreCreate</td>
<td>Before creating new entity</td>
<td>✅ Yes</td>
</tr>
<tr>
<td>PostCreate</td>
<td>After creating new entity</td>
<td>✅ Yes</td>
</tr>
<tr>
<td>PreInsert</td>
<td>Before inserting to data source</td>
<td>✅ Yes</td>
</tr>
<tr>
<td>PostInsert</td>
<td>After inserting to data source</td>
<td>❌ No</td>
</tr>
<tr>
<td>PreUpdate</td>
<td>Before updating in data source</td>
<td>✅ Yes</td>
</tr>
<tr>
<td>PostUpdate</td>
<td>After updating in data source</td>
<td>❌ No</td>
</tr>
<tr>
<td>PreDelete</td>
<td>Before deleting from data source</td>
<td>✅ Yes</td>
</tr>
<tr>
<td>PostDelete</td>
<td>After deleting from data source</td>
<td>❌ No</td>
</tr>
<tr>
<td>PreCommit</td>
<td>Before committing changes</td>
<td>✅ Yes</td>
</tr>
<tr>
<td>PostCommit</td>
<td>After committing changes</td>
<td>❌ No</td>
</tr>
<tr>
<td>PostEdit</td>
<td>After property changes</td>
<td>❌ No</td>
</tr>
</tbody>
</table>
<div class="code-example">
<h3>Event Handling Example</h3>
<pre><code class="language-csharp">// Subscribe to validation events
customerUoW.PreInsert += (sender, args) =>
{
var customer = (Customer)sender;
if (string.IsNullOrEmpty(customer.Name))
{
args.Cancel = true;
args.ErrorMessage = "Customer name is required";
}
};
// Track property changes
customerUoW.PostEdit += (sender, args) =>
{
Console.WriteLine($"Property {args.PropertyName} changed to {args.PropertyValue}");
// Log to audit trail
auditService.LogChange(customerUoW.CurrentItem.CustomerID, args.PropertyName, args.PropertyValue);
};
// Final validation before commit
customerUoW.PreCommit += (sender, args) =>
{
if (!ValidateAllCustomers())
{
args.Cancel = true;
args.ErrorMessage = "Validation failed - please fix errors before saving";
}
};
// Success notification
customerUoW.PostCommit += (sender, args) =>
{
MessageBox.Show("Changes saved successfully!");
RefreshUI();
};</code></pre>
</div>
</section>
<!-- Undo/Redo -->
<section id="undo-redo" class="section">
<h2>Undo/Redo Functionality</h2>
<div class="code-example">
<h3>Undo Methods</h3>
<pre><code class="language-csharp">public void UndoLastChange() // Undoes the last change made to the collection
public void UndoDelete() // Undoes the most recent delete operation</code></pre>
</div>
<div class="code-example">
<h3>Undo Example</h3>
<pre><code class="language-csharp">// Make a change
var customer = customerUoW.CurrentItem;
var originalName = customer.Name;
customer.Name = "New Name";
Console.WriteLine($"Changed name from '{originalName}' to '{customer.Name}'");
// Undo the change
customerUoW.UndoLastChange();
Console.WriteLine($"Name restored to: '{customer.Name}'");
// Delete and undo example
var customerToDelete = customerUoW.CurrentItem;
customerUoW.Delete(customerToDelete);
Console.WriteLine($"Customer {customerToDelete.Name} deleted");
// Restore deleted customer
customerUoW.UndoDelete();
Console.WriteLine($"Customer {customerToDelete.Name} restored");</code></pre>
</div>
<div class="tip">
<strong>💡 Tip:</strong>
<p>Undo functionality is limited to the current session. Once you commit changes to the database, use the
Rollback method to revert uncommitted changes.</p>
</div>
</section>
<!-- Logging -->
<section id="logging" class="section">
<h2>Logging</h2>
<div class="code-example">
<h3>Logging Properties & Methods</h3>
<pre><code class="language-csharp">public bool IsLogging { get; set; } // Enable/disable change logging
public bool SaveLog(string pathandname) // Save change log to JSON file</code></pre>
</div>
<div class="code-example">
<h3>Logging Example</h3>
<pre><code class="language-csharp">// Enable logging
customerUoW.IsLogging = true;
// Make changes
customerUoW.New();
var customer = customerUoW.CurrentItem;
customer.Name = "John Doe";
customer.Email = "john@example.com";
customerUoW.CurrentItem.Name = "John Smith"; // This change will be logged
// Save log to file
var logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"MyApp", "Logs", $"customer_changes_{DateTime.Now:yyyyMMdd}.json");
Directory.CreateDirectory(Path.GetDirectoryName(logPath));
var success = customerUoW.SaveLog(logPath);
if (success)
{
Console.WriteLine($"Change log saved to: {logPath}");
}</code></pre>
</div>
<div class="note">
<strong>📝 Log Format:</strong>
<p>The log is saved as JSON and includes timestamps, entity information, property changes, and operation
types. This is useful for auditing and debugging purposes.</p>
</div>
</section>
<!-- Capability Interfaces -->
<section id="capability-interfaces" class="section">
<h2>Capability Interfaces (Phase 3)</h2>
<p>Since <code>UnitofWork<T></code> implements eight marker interfaces you can detect capabilities at runtime without casting to the concrete type:</p>
<table class="property-table">
<thead><tr><th>Interface</th><th>Capability</th><th>Key Members</th></tr></thead>
<tbody>
<tr><td><code>IRevertable</code></td><td>Per-item server revert</td><td><code>RevertItem</code>, <code>RevertItemAsync</code></td></tr>
<tr><td><code>IBatchCommittable</code></td><td>Chunked batch commit</td><td><code>CommitBatchAsync</code></td></tr>
<tr><td><code>IExportable</code></td><td>Data export</td><td><code>ToDataTable</code>, <code>ToJsonAsync</code>, <code>ToCsvAsync</code></td></tr>
<tr><td><code>IImportable</code></td><td>Data import</td><td><code>LoadFromJsonAsync</code>, <code>LoadFromCsvAsync</code></td></tr>
<tr><td><code>IAggregatable</code></td><td>Aggregate calculations</td><td><code>Sum</code>, <code>Average</code>, <code>Count</code></td></tr>
<tr><td><code>IUndoable</code></td><td>Undo/Redo stack</td><td><code>UndoLastAction</code>, <code>RedoLastAction</code>, <code>EnableUndo</code></td></tr>
<tr><td><code>IMergeable</code></td><td>Server-merge refresh</td><td><code>RefreshAsync</code></td></tr>
<tr><td><code>IUnitofWorkHistory</code></td><td>Query history & change audit</td><td><code>GetChangeSummary</code>, <code>GetQueryHistory</code>, <code>CloneItem</code></td></tr>
</tbody>
</table>
<div class="code-example">
<h3>Runtime Capability Detection</h3>
<pre><code class="language-csharp">IUnitofWork uow = GetUnitOfWork(blockName); // returns non-generic IUnitofWork
// Detect and use capabilities safely
if (uow is IBatchCommittable batchable)
{
var result = await batchable.CommitBatchAsync(batchSize: 50);
Console.WriteLine($"Committed {result.TotalCommitted} records.");
}
if (uow is IExportable exportable)
{
using var stream = File.Create("export.json");
await exportable.ToJsonAsync(stream);
}
if (uow is IUnitofWorkHistory hist)
{
var summary = hist.GetChangeSummary();
Console.WriteLine($"Inserted: {summary.InsertedCount}, Updated: {summary.UpdatedCount}, Deleted: {summary.DeletedCount}");
}</code></pre>
</div>
</section>
<!-- Batch Commit -->
<section id="batch-commit" class="section">
<h2>Batch Commit (IBatchCommittable)</h2>
<p>Commit large sets of changes in configurable chunks, with progress reporting and cancellation support. Implements <code>IBatchCommittable</code>.</p>
<div class="code-example">
<h3>Signature</h3>
<pre><code class="language-csharp">Task<CommitBatchResult> CommitBatchAsync(
int batchSize = 200,
IProgress<CommitBatchProgress> progress = null,
CancellationToken ct = default);</code></pre>
</div>
<div class="code-example">
<h3>CommitBatchResult Properties</h3>
<pre><code class="language-csharp">public class CommitBatchResult
{
public bool Success { get; set; } // Overall success flag
public int TotalCommitted { get; set; } // Records persisted
public List<string> Errors { get; set; } // Per-batch error messages
}</code></pre>
</div>
<div class="code-example">
<h3>Example — Import 10,000 Records in Batches of 200</h3>
<pre><code class="language-csharp">// Add a large number of entities
for (int i = 0; i < 10_000; i++)
uow.Add(new Product { Name = $"Product {i}", Price = i * 1.5m });
var progress = new Progress<CommitBatchProgress>(p =>
Console.WriteLine($"Batch {p.BatchNumber}/{p.TotalBatches} — {p.Committed} committed"));
var result = await uow.CommitBatchAsync(batchSize: 200, progress, CancellationToken.None);
if (result.Success)
Console.WriteLine($"Done — {result.TotalCommitted} records saved.");
else
foreach (var err in result.Errors)
Console.Error.WriteLine(err);</code></pre>
</div>
<div class="tip">
<strong>💡 When to use CommitBatchAsync vs Commit</strong>
<p>Use <code>CommitBatchAsync</code> when inserting or updating thousands of records to avoid database time-outs and to give UI progress feedback. Use <code>Commit()</code> for normal form-save operations with a small number of changes.</p>
</div>
</section>
<!-- OBL Change Inspection -->
<section id="obl-change-inspection" class="section">
<h2>OBL Change Inspection (Phase 1)</h2>
<p>The underlying <code>ObservableBindingList<T></code> exposes rich field-level change inspection methods added in Phase 1:</p>
<table class="property-table">
<thead><tr><th>Method</th><th>Returns</th><th>Description</th></tr></thead>
<tbody>
<tr><td><code>GetChangedFields(item)</code></td><td><code>IReadOnlyList<string></code></td><td>Field names modified since the item was loaded</td></tr>
<tr><td><code>GetFieldDelta(item, field)</code></td><td><code>FieldDelta</code></td><td>Original and current value pair for a field</td></tr>
<tr><td><code>HasFieldChanges(item)</code></td><td><code>bool</code></td><td>Whether the item has any field-level changes</td></tr>
<tr><td><code>GetInserted()</code></td><td><code>IReadOnlyList<T></code></td><td>All newly inserted items not yet committed</td></tr>
<tr><td><code>GetUpdated()</code></td><td><code>IReadOnlyList<T></code></td><td>All modified items</td></tr>
<tr><td><code>GetDeleted()</code></td><td><code>IReadOnlyList<T></code></td><td>Soft-deleted items still in the list</td></tr>
<tr><td><code>GetDirty()</code></td><td><code>IReadOnlyList<T></code></td><td>All items in a non-Unchanged state</td></tr>
<tr><td><code>GetChangeSetSummary()</code></td><td><code>ChangeSetSummary</code></td><td>Counts of inserted / updated / deleted items</td></tr>
<tr><td><code>GetOriginalValue(item, field)</code></td><td><code>object</code></td><td>Snapshot value captured at first modification</td></tr>
</tbody>
</table>
<div class="code-example">
<h3>Example — Per-Item Delta Report</h3>
<pre><code class="language-csharp">await customerUoW.Get();
var customer = customerUoW.Units.First();
customer.Name = "Updated Name";
customer.Status = "Premium";
// Field-level inspection
var changedFields = customerUoW.Units.GetChangedFields(customer);
foreach (var field in changedFields)
{
var delta = customerUoW.Units.GetFieldDelta(customer, field);
Console.WriteLine($"{field}: '{delta.OriginalValue}' → '{delta.CurrentValue}'");
}
// Summary
var summary = customerUoW.Units.GetChangeSetSummary();
Console.WriteLine($"Inserted={summary.InsertedCount}, Updated={summary.UpdatedCount}, Deleted={summary.DeletedCount}");</code></pre>
</div>
</section>
<!-- Revert & Merge -->
<section id="revert-merge" class="section">
<h2>Revert & Merge (IRevertable / IMergeable)</h2>
<h3>IRevertable — Discard Changes for a Single Item</h3>
<div class="code-example">
<pre><code class="language-csharp">// Strongly typed (compile-time)
bool ok = customerUoW.RevertItem(customer);
await customerUoW.RevertItemAsync(customer);
// Via non-generic IUnitofWork (runtime cast)
if (uow is IRevertable r)
r.RevertItem(customer); // object overload</code></pre>
</div>
<h3>IMergeable — Re-fetch from Server & Resolve Conflicts</h3>
<div class="code-example">
<pre><code class="language-csharp">// Re-fetch and merge with conflict resolution
var result = await customerUoW.RefreshAsync(
filters: null,
conflictMode: ConflictMode.ServerWins, // or ClientWins / KeepBoth / ThrowOnConflict
ct: CancellationToken.None);
if (result.Flag == Errors.Ok)
Console.WriteLine("Data refreshed — server values applied to conflicting records.");</code></pre>
</div>
<table class="property-table">
<thead><tr><th>ConflictMode</th><th>Behaviour</th></tr></thead>
<tbody>
<tr><td><code>ServerWins</code></td><td>Server value replaces local change</td></tr>
<tr><td><code>ClientWins</code></td><td>Local change is kept</td></tr>
<tr><td><code>KeepBoth</code></td><td>Both rows retained (new server row appended)</td></tr>
<tr><td><code>ThrowOnConflict</code></td><td>Throws <code>MergeConflictException</code> on first conflict</td></tr>
</tbody>
</table>
</section>
<!-- Change History & Audit -->
<section id="change-history" class="section">
<h2>Change History & Audit (IUnitofWorkHistory)</h2>
<table class="property-table">
<thead><tr><th>Member</th><th>Returns</th><th>Description</th></tr></thead>
<tbody>
<tr><td><code>GetChangeSummary()</code></td><td><code>ChangeSummary</code></td><td>Counts of inserted / updated / deleted items in current session</td></tr>
<tr><td><code>GetQueryHistory()</code></td><td><code>IReadOnlyList<QueryHistoryEntry></code></td><td>Log of all Get / GetQuery calls with timestamps and filter snapshots</td></tr>
<tr><td><code>ClearQueryHistory()</code></td><td>void</td><td>Resets the query history log</td></tr>
<tr><td><code>CloneItem(item, deep)</code></td><td><code>T</code></td><td>Deep-copy or shallow-copy of an entity (deep uses binary / JSON serialization)</td></tr>
<tr><td><code>GetChangeLog()</code></td><td><code>List<ChangeRecord></code></td><td>Full per-property change audit log (requires <code>IsLogging = true</code>)</td></tr>
</tbody>
</table>
<div class="code-example">
<h3>Example — Audit Dashboard</h3>
<pre><code class="language-csharp">// Summary stats
var summary = customerUoW.GetChangeSummary();
Console.WriteLine($"Session changes: +{summary.InsertedCount} / ~{summary.UpdatedCount} / -{summary.DeletedCount}");
// Query history
foreach (var entry in customerUoW.GetQueryHistory())
Console.WriteLine($"[{entry.ExecutedAt:HH:mm:ss}] {entry.QueryText}");
// Clone before editing (non-destructive preview)
var original = customerUoW.CloneItem(customerUoW.CurrentItem, deep: true);
customerUoW.CurrentItem.Status = "Suspended";
// cancel? restore original
// customerUoW.Units[idx] = original;
</code></pre>
</div>
</section>
<!-- Export & Import -->
<section id="export-import" class="section">
<h2>Export & Import (IExportable / IImportable)</h2>
<div class="code-example">
<h3>Export API</h3>
<pre><code class="language-csharp">DataTable dt = customerUoW.ToDataTable();
using var js = File.Create("customers.json");
await customerUoW.ToJsonAsync(js);
using var csv = File.Create("customers.csv");
await customerUoW.ToCsvAsync(csv, delimiter: ',');</code></pre>
</div>
<div class="code-example">
<h3>Import API</h3>
<pre><code class="language-csharp">// Import from JSON
using var js = File.OpenRead("customers.json");
int imported = await customerUoW.LoadFromJsonAsync(js, clearFirst: true);
Console.WriteLine($"{imported} records imported from JSON");
// Import from CSV
using var csv = File.OpenRead("customers.csv");
imported = await customerUoW.LoadFromCsvAsync(
csv, delimiter: ',', clearFirst: false, hasHeaderRow: true);
Console.WriteLine($"{imported} records appended from CSV");</code></pre>
</div>
<div class="note">
<strong>📋 Note</strong>
<p>Import methods populate the in-memory <code>Units</code> collection and mark all loaded items as <em>Added</em>. Call <code>Commit()</code> to persist them to the database, or keep in list mode as an in-memory dataset.</p>