├── .gitattributes
├── .gitignore
├── DataLayer
├── DataLayer.csproj
└── ExampleDbContext.cs
├── EntityClasses
├── Book.cs
├── DomainEvents
│ ├── AllocateProductEvent.cs
│ ├── DeDupEvent.cs
│ ├── NewBookEvent.cs
│ ├── NewBookEventButBeforeSave.cs
│ ├── OrderCreatedEvent.cs
│ ├── OrderReadyToDispatchEvent.cs
│ └── TaxRateChangedEvent.cs
├── EntityClasses.csproj
├── LineItem.cs
├── Order.cs
├── ProductStock.cs
├── Review.cs
├── SupportClasses
│ ├── BasketItemDto.cs
│ └── ICreatedUpdated.cs
└── TaxRate.cs
├── GenericEventRunner.DomainParts
├── EntityEventsBase.cs
├── EventToSend.cs
├── GenericEventRunner.DomainParts.csproj
├── GenericEventsRunnerDomainNuGetIcon128.png
├── IEntityEvent.cs
├── IEntityWithAfterSaveEvents.cs
├── IEntityWithBeforeSaveEvents.cs
├── IEntityWithDuringSaveEvents.cs
├── MakeDuringEventRunBeforeSaveChangesAttribute.cs
└── RemoveDuplicateEventsAttribute.cs
├── GenericEventRunner.sln
├── GenericEventRunner
├── ForDbContext
│ ├── DbContextWithEvents.cs
│ ├── GenericEventRunnerStatusException.cs
│ ├── IEventsRunner.cs
│ └── IStatusFromLastSaveChanges.cs
├── ForHandlers
│ ├── EventHandlerConfigAttribute.cs
│ ├── EventsRunner.cs
│ ├── GenericEventRunnerException.cs
│ ├── IAfterSaveEventHandler.cs
│ ├── IAfterSaveEventHandlerAsync.cs
│ ├── IBeforeSaveEventHandler.cs
│ ├── IBeforeSaveEventHandlerAsync.cs
│ ├── IDuringSaveEventHandler.cs
│ ├── IDuringSaveEventHandlerAsync.cs
│ └── Internal
│ │ ├── AfterEntityAndEvent.cs
│ │ ├── AfterSaveEventHandler.cs
│ │ ├── AfterSaveEventHandlerAsync.cs
│ │ ├── AsyncHelper.cs
│ │ ├── BeforeSaveEventHandler.cs
│ │ ├── BeforeSaveEventHandlerAsync.cs
│ │ ├── DuringEventsExtensions.cs
│ │ ├── DuringSaveEventHandler.cs
│ │ ├── DuringSaveEventHandlerAsync.cs
│ │ ├── EntityAndEvent.cs
│ │ ├── FindHandlers.cs
│ │ ├── FindRunHandlers.cs
│ │ ├── HandlerAndWrapper.cs
│ │ ├── RunEachTypeOfEvents.cs
│ │ └── ValueTaskSyncCheckers.cs
├── ForSetup
│ ├── GenericEventRunnerConfig.cs
│ ├── IGenericEventRunnerConfig.cs
│ ├── Internal
│ │ └── RegisterIfNotThere.cs
│ ├── RegisterGenericEventRunnerExtensions.cs
│ ├── ServiceDescriptorIncludeLifeTimeCompare.cs
│ └── ServiceDescriptorNoLifeTimeCompare.cs
├── GenericEventRunner.csproj
└── GenericEventsRunnerNuGetIcon128.png
├── GenericEventRunnerTypesOfEvents.png
├── GenericEventsRunnerDomainNuGetIcon128.png
├── GenericEventsRunnerNuGetIcon128.png
├── Infrastructure
├── AfterEventHandlers
│ ├── DeDupAfterEventHandler.cs
│ └── OrderReadyToDispatchAfterHandler.cs
├── BeforeEventHandlers
│ ├── AllocateProductHander.cs
│ ├── DeDupBeforeEventHandler.cs
│ ├── Internal
│ │ └── TaxRateLookup.cs
│ ├── OrderCreatedHandler.cs
│ ├── OrderDispatchedBeforeHandler.cs
│ └── TaxRateChangedHandler.cs
├── DuringEventHandlers
│ ├── DeDupDuringEventHandler.cs
│ ├── NewBookDuringButBeforeSaveEventHandler.cs
│ ├── NewBookDuringButBeforeSaveEventHandlerAsync.cs
│ ├── NewBookDuringEventHandler.cs
│ └── NewBookDuringEventHandlerAsync.cs
└── Infrastructure.csproj
├── LICENSE
├── OnlyAfterHandlers
├── AfterHandler.cs
└── OnlyAfterHandlers.csproj
├── OnlyBeforeHandlers
├── BeforeHandler.cs
└── OnlyBeforeHandlers.csproj
├── OnlyDuringHandlers
├── DuringHandler.cs
└── OnlyDuringHandlers.csproj
├── README.md
├── ReleaseNotes.md
└── Test
├── EfHelpers
├── SeedExtensions.cs
├── SetupToTestEvents.cs
└── SqlServerWithExecution.cs
├── EventsAndHandlers
├── AfterHandlerDoNothing.cs
├── AfterHandlerDoNothingAsync.cs
├── AfterHandlerThrowsException.cs
├── BeforeHandlerCircularEvent.cs
├── BeforeHandlerDoNothing.cs
├── BeforeHandlerDoNothingAsync.cs
├── BeforeHandlerReturnsErrorStatus.cs
├── BeforeHandlerThrowsException.cs
├── BeforeHandlerThrowsExceptionWithAttribute.cs
├── DuringHandlerDoNothing.cs
├── DuringHandlerReturnsErrorStatus.cs
├── DuringHandlerReturnsErrorStatusAsync.cs
├── DuringHandlerThrowsException.cs
├── DuringHandlerThrowsExceptionAsync.cs
├── DuringPreHandlerReturnsErrorStatus.cs
├── DuringPreHandlerReturnsErrorStatusAsync.cs
├── DuringPreHandlerThrowsException.cs
├── DuringPreHandlerThrowsExceptionAsync.cs
├── EventAfterHandlerThrowsException.cs
├── EventCircularEvent.cs
├── EventDoNothing.cs
├── EventTestAfterExceptionHandler.cs
├── EventTestBeforeExceptionHandler.cs
├── EventTestBeforeReturnError.cs
├── EventTestDuringExceptionHandler.cs
├── EventTestDuringPreExceptionHandler.cs
├── EventTestDuringPreReturnError.cs
├── EventTestDuringReturnError.cs
├── EventTestExceptionHandlerWithAttribute.cs
└── EventWithNoHandler.cs
├── Test.csproj
├── UnitTests
├── DataLayerTests
│ └── TestExampleDbContext.cs
└── InfrastructureTests
│ ├── TestAsyncEventHandlers.cs
│ ├── TestDeDupEvents.cs
│ ├── TestEventSaveChangesAsync.cs
│ ├── TestEventSaveChangesExceptionHandler.cs
│ ├── TestEventSaveChangesSync.cs
│ ├── TestEventSaveChangesTransactionsAsync.cs
│ ├── TestEventSaveChangesTransactionsSync.cs
│ ├── TestEventSaveChangesWithStatusAsync.cs
│ ├── TestEventSaveChangesWithStatusSync.cs
│ ├── TestRegisterEventHandlers.cs
│ └── TestRegisterEventHandlersIfAlreadyRegistered.cs
└── appsettings.json
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Build results
17 | [Dd]ebug/
18 | [Dd]ebugPublic/
19 | [Rr]elease/
20 | [Rr]eleases/
21 | x64/
22 | x86/
23 | [Aa][Rr][Mm]/
24 | [Aa][Rr][Mm]64/
25 | bld/
26 | [Bb]in/
27 | [Oo]bj/
28 | [Ll]og/
29 |
30 | # Visual Studio 2015/2017 cache/options directory
31 | .vs/
32 | # Uncomment if you have tasks that create the project's static files in wwwroot
33 | #wwwroot/
34 |
35 | # Visual Studio 2017 auto generated files
36 | Generated\ Files/
37 |
38 | # MSTest test Results
39 | [Tt]est[Rr]esult*/
40 | [Bb]uild[Ll]og.*
41 |
42 | # NUNIT
43 | *.VisualState.xml
44 | TestResult.xml
45 |
46 | # Build Results of an ATL Project
47 | [Dd]ebugPS/
48 | [Rr]eleasePS/
49 | dlldata.c
50 |
51 | # Benchmark Results
52 | BenchmarkDotNet.Artifacts/
53 |
54 | # .NET Core
55 | project.lock.json
56 | project.fragment.lock.json
57 | artifacts/
58 |
59 | # StyleCop
60 | StyleCopReport.xml
61 |
62 | # Files built by Visual Studio
63 | *_i.c
64 | *_p.c
65 | *_h.h
66 | *.ilk
67 | *.meta
68 | *.obj
69 | *.iobj
70 | *.pch
71 | *.pdb
72 | *.ipdb
73 | *.pgc
74 | *.pgd
75 | *.rsp
76 | *.sbr
77 | *.tlb
78 | *.tli
79 | *.tlh
80 | *.tmp
81 | *.tmp_proj
82 | *_wpftmp.csproj
83 | *.log
84 | *.vspscc
85 | *.vssscc
86 | .builds
87 | *.pidb
88 | *.svclog
89 | *.scc
90 |
91 | # Chutzpah Test files
92 | _Chutzpah*
93 |
94 | # Visual C++ cache files
95 | ipch/
96 | *.aps
97 | *.ncb
98 | *.opendb
99 | *.opensdf
100 | *.sdf
101 | *.cachefile
102 | *.VC.db
103 | *.VC.VC.opendb
104 |
105 | # Visual Studio profiler
106 | *.psess
107 | *.vsp
108 | *.vspx
109 | *.sap
110 |
111 | # Visual Studio Trace Files
112 | *.e2e
113 |
114 | # TFS 2012 Local Workspace
115 | $tf/
116 |
117 | # Guidance Automation Toolkit
118 | *.gpState
119 |
120 | # ReSharper is a .NET coding add-in
121 | _ReSharper*/
122 | *.[Rr]e[Ss]harper
123 | *.DotSettings.user
124 |
125 | # JustCode is a .NET coding add-in
126 | .JustCode
127 |
128 | # TeamCity is a build add-in
129 | _TeamCity*
130 |
131 | # DotCover is a Code Coverage Tool
132 | *.dotCover
133 |
134 | # AxoCover is a Code Coverage Tool
135 | .axoCover/*
136 | !.axoCover/settings.json
137 |
138 | # Visual Studio code coverage results
139 | *.coverage
140 | *.coveragexml
141 |
142 | # NCrunch
143 | _NCrunch_*
144 | .*crunch*.local.xml
145 | nCrunchTemp_*
146 |
147 | # MightyMoose
148 | *.mm.*
149 | AutoTest.Net/
150 |
151 | # Web workbench (sass)
152 | .sass-cache/
153 |
154 | # Installshield output folder
155 | [Ee]xpress/
156 |
157 | # DocProject is a documentation generator add-in
158 | DocProject/buildhelp/
159 | DocProject/Help/*.HxT
160 | DocProject/Help/*.HxC
161 | DocProject/Help/*.hhc
162 | DocProject/Help/*.hhk
163 | DocProject/Help/*.hhp
164 | DocProject/Help/Html2
165 | DocProject/Help/html
166 |
167 | # Click-Once directory
168 | publish/
169 |
170 | # Publish Web Output
171 | *.[Pp]ublish.xml
172 | *.azurePubxml
173 | # Note: Comment the next line if you want to checkin your web deploy settings,
174 | # but database connection strings (with potential passwords) will be unencrypted
175 | *.pubxml
176 | *.publishproj
177 |
178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
179 | # checkin your Azure Web App publish settings, but sensitive information contained
180 | # in these scripts will be unencrypted
181 | PublishScripts/
182 |
183 | # NuGet Packages
184 | *.nupkg
185 | # The packages folder can be ignored because of Package Restore
186 | **/[Pp]ackages/*
187 | # except build/, which is used as an MSBuild target.
188 | !**/[Pp]ackages/build/
189 | # Uncomment if necessary however generally it will be regenerated when needed
190 | #!**/[Pp]ackages/repositories.config
191 | # NuGet v3's project.json files produces more ignorable files
192 | *.nuget.props
193 | *.nuget.targets
194 |
195 | # Microsoft Azure Build Output
196 | csx/
197 | *.build.csdef
198 |
199 | # Microsoft Azure Emulator
200 | ecf/
201 | rcf/
202 |
203 | # Windows Store app package directories and files
204 | AppPackages/
205 | BundleArtifacts/
206 | Package.StoreAssociation.xml
207 | _pkginfo.txt
208 | *.appx
209 |
210 | # Visual Studio cache files
211 | # files ending in .cache can be ignored
212 | *.[Cc]ache
213 | # but keep track of directories ending in .cache
214 | !?*.[Cc]ache/
215 |
216 | # Others
217 | ClientBin/
218 | ~$*
219 | *~
220 | *.dbmdl
221 | *.dbproj.schemaview
222 | *.jfm
223 | *.pfx
224 | *.publishsettings
225 | orleans.codegen.cs
226 |
227 | # Including strong name files can present a security risk
228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
229 | #*.snk
230 |
231 | # Since there are multiple workflows, uncomment next line to ignore bower_components
232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
233 | #bower_components/
234 |
235 | # RIA/Silverlight projects
236 | Generated_Code/
237 |
238 | # Backup & report files from converting an old project file
239 | # to a newer Visual Studio version. Backup files are not needed,
240 | # because we have git ;-)
241 | _UpgradeReport_Files/
242 | Backup*/
243 | UpgradeLog*.XML
244 | UpgradeLog*.htm
245 | ServiceFabricBackup/
246 | *.rptproj.bak
247 |
248 | # SQL Server files
249 | *.mdf
250 | *.ldf
251 | *.ndf
252 |
253 | # Business Intelligence projects
254 | *.rdl.data
255 | *.bim.layout
256 | *.bim_*.settings
257 | *.rptproj.rsuser
258 | *- Backup*.rdl
259 |
260 | # Microsoft Fakes
261 | FakesAssemblies/
262 |
263 | # GhostDoc plugin setting file
264 | *.GhostDoc.xml
265 |
266 | # Node.js Tools for Visual Studio
267 | .ntvs_analysis.dat
268 | node_modules/
269 |
270 | # Visual Studio 6 build log
271 | *.plg
272 |
273 | # Visual Studio 6 workspace options file
274 | *.opt
275 |
276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
277 | *.vbw
278 |
279 | # Visual Studio LightSwitch build output
280 | **/*.HTMLClient/GeneratedArtifacts
281 | **/*.DesktopClient/GeneratedArtifacts
282 | **/*.DesktopClient/ModelManifest.xml
283 | **/*.Server/GeneratedArtifacts
284 | **/*.Server/ModelManifest.xml
285 | _Pvt_Extensions
286 |
287 | # Paket dependency manager
288 | .paket/paket.exe
289 | paket-files/
290 |
291 | # FAKE - F# Make
292 | .fake/
293 |
294 | # JetBrains Rider
295 | .idea/
296 | *.sln.iml
297 |
298 | # CodeRush personal settings
299 | .cr/personal
300 |
301 | # Python Tools for Visual Studio (PTVS)
302 | __pycache__/
303 | *.pyc
304 |
305 | # Cake - Uncomment if you are using it
306 | # tools/**
307 | # !tools/packages.config
308 |
309 | # Tabs Studio
310 | *.tss
311 |
312 | # Telerik's JustMock configuration file
313 | *.jmconfig
314 |
315 | # BizTalk build output
316 | *.btp.cs
317 | *.btm.cs
318 | *.odx.cs
319 | *.xsd.cs
320 |
321 | # OpenCover UI analysis results
322 | OpenCover/
323 |
324 | # Azure Stream Analytics local run output
325 | ASALocalRun/
326 |
327 | # MSBuild Binary and Structured Log
328 | *.binlog
329 |
330 | # NVidia Nsight GPU debugger configuration file
331 | *.nvuser
332 |
333 | # MFractors (Xamarin productivity tool) working folder
334 | .mfractor/
335 |
336 | # Local History for Visual Studio
337 | .localhistory/
338 |
339 | # BeatPulse healthcheck temp database
340 | healthchecksdb
--------------------------------------------------------------------------------
/DataLayer/DataLayer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.1
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/DataLayer/ExampleDbContext.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using EntityClasses;
5 | using GenericEventRunner.ForDbContext;
6 | using Microsoft.EntityFrameworkCore;
7 |
8 | namespace DataLayer
9 | {
10 | public class ExampleDbContext : DbContextWithEvents
11 | {
12 | public ExampleDbContext(DbContextOptions options,
13 | IEventsRunner eventRunner = null)
14 | : base(options, eventRunner)
15 | {
16 | }
17 |
18 | public DbSet Orders { get; set; }
19 | public DbSet LineItems { get; set; }
20 | public DbSet ProductStocks { get; set; }
21 | public DbSet TaxRates { get; set; }
22 | public DbSet Books { get; set; }
23 |
24 | protected override void OnModelCreating(ModelBuilder modelBuilder)
25 | {
26 | modelBuilder.Entity().HasKey(x => x.ProductName);
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/EntityClasses/Book.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using EntityClasses.DomainEvents;
8 | using EntityClasses.SupportClasses;
9 | using GenericEventRunner.DomainParts;
10 | using Microsoft.EntityFrameworkCore;
11 | using Microsoft.EntityFrameworkCore.ChangeTracking;
12 |
13 | namespace EntityClasses
14 | {
15 | public class Book : EntityEventsBase, ICreatedUpdated
16 | {
17 |
18 | private HashSet _reviews;
19 |
20 | public int BookId { get; private set; }
21 | public string Title { get; private set; }
22 |
23 | public DateTime WhenCreatedUtc { get; private set; }
24 | public DateTime LastUpdatedUtc { get; private set; }
25 | public void LogChange(bool added, EntityEntry entry)
26 | {
27 | var timeNow = DateTime.UtcNow;
28 | LastUpdatedUtc = timeNow;
29 | if (added)
30 | {
31 | WhenCreatedUtc = timeNow;
32 | }
33 | else
34 | {
35 | entry.Property(nameof(ICreatedUpdated.LastUpdatedUtc))
36 | .IsModified = true;
37 | }
38 | }
39 |
40 | public IReadOnlyCollection Reviews => _reviews?.ToList();
41 |
42 | private Book(){}
43 |
44 | public static Book CreateBookWithEvent(string title)
45 | {
46 | var result = new Book
47 | {
48 | Title = title,
49 | _reviews = new HashSet()
50 | };
51 | result.AddEvent(new NewBookEvent(), EventToSend.DuringSave);
52 | return result;
53 | }
54 |
55 | public void ChangeTitle(string newTitle)
56 | {
57 | Title = newTitle;
58 | }
59 |
60 | public void AddReview(int numStars, string comment, string voterName)
61 | {
62 | if (_reviews == null)
63 | throw new InvalidOperationException("The Reviews collection must be loaded before calling this method");
64 | _reviews.Add(new Review(numStars, comment, voterName));
65 | }
66 |
67 |
68 | //This works with the GenericServices' IncludeThen Attribute to pre-load the Reviews collection
69 | public void RemoveReview(int reviewId)
70 | {
71 | if (_reviews == null)
72 | throw new InvalidOperationException("The Reviews collection must be loaded before calling this method");
73 | var localReview = _reviews.SingleOrDefault(x => x.ReviewId == reviewId);
74 | if (localReview == null)
75 | throw new InvalidOperationException("The review with that key was not found in the book's Reviews.");
76 | _reviews.Remove(localReview);
77 | }
78 | }
79 | }
--------------------------------------------------------------------------------
/EntityClasses/DomainEvents/AllocateProductEvent.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using GenericEventRunner.DomainParts;
6 |
7 | namespace EntityClasses.DomainEvents
8 | {
9 | public class AllocateProductEvent : IEntityEvent
10 | {
11 | public AllocateProductEvent(string productName, int numOrdered)
12 | {
13 | ProductName = productName;
14 | NumOrdered = numOrdered;
15 | }
16 |
17 | public string ProductName { get; }
18 | public int NumOrdered { get; }
19 | }
20 | }
--------------------------------------------------------------------------------
/EntityClasses/DomainEvents/DeDupEvent.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using GenericEventRunner.DomainParts;
6 |
7 | namespace EntityClasses.DomainEvents
8 | {
9 | [RemoveDuplicateEvents]
10 | public class DeDupEvent : IEntityEvent
11 | {
12 | public DeDupEvent(Action actionToCall)
13 | {
14 | ActionToCall = actionToCall;
15 | }
16 |
17 | public Action ActionToCall { get; }
18 | }
19 | }
--------------------------------------------------------------------------------
/EntityClasses/DomainEvents/NewBookEvent.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using GenericEventRunner.DomainParts;
5 |
6 | namespace EntityClasses.DomainEvents
7 | {
8 | public class NewBookEvent : IEntityEvent
9 | {
10 | }
11 | }
--------------------------------------------------------------------------------
/EntityClasses/DomainEvents/NewBookEventButBeforeSave.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using GenericEventRunner.DomainParts;
5 |
6 | namespace EntityClasses.DomainEvents
7 | {
8 | [MakeDuringEventRunBeforeSaveChanges]
9 | public class NewBookEventButBeforeSave : IEntityEvent
10 | {
11 | }
12 | }
--------------------------------------------------------------------------------
/EntityClasses/DomainEvents/OrderCreatedEvent.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using GenericEventRunner.DomainParts;
6 |
7 | namespace EntityClasses.DomainEvents
8 | {
9 | public class OrderCreatedEvent : IEntityEvent
10 | {
11 | public OrderCreatedEvent(DateTime expectedDispatchDate, Action setTaxRatePercent)
12 | {
13 | ExpectedDispatchDate = expectedDispatchDate;
14 | SetTaxRatePercent = setTaxRatePercent;
15 | }
16 |
17 | public DateTime ExpectedDispatchDate { get; }
18 |
19 | public Action SetTaxRatePercent { get; }
20 | }
21 | }
--------------------------------------------------------------------------------
/EntityClasses/DomainEvents/OrderReadyToDispatchEvent.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using GenericEventRunner.DomainParts;
6 |
7 | namespace EntityClasses.DomainEvents
8 | {
9 | public class OrderReadyToDispatchEvent : IEntityEvent
10 | {
11 | public OrderReadyToDispatchEvent(DateTime actualDispatchDate, Action setTaxRatePercent)
12 | {
13 | ActualDispatchDate = actualDispatchDate;
14 | SetTaxRatePercent = setTaxRatePercent;
15 | }
16 |
17 | public DateTime ActualDispatchDate { get; }
18 |
19 | public Action SetTaxRatePercent { get; }
20 | }
21 | }
--------------------------------------------------------------------------------
/EntityClasses/DomainEvents/TaxRateChangedEvent.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using GenericEventRunner.DomainParts;
6 |
7 | namespace EntityClasses.DomainEvents
8 | {
9 | public class TaxRateChangedEvent : IEntityEvent
10 | {
11 | public TaxRateChangedEvent(decimal newTaxRate, Action refreshGrandTotalPrice)
12 | {
13 | NewTaxRate = newTaxRate;
14 | RefreshGrandTotalPrice = refreshGrandTotalPrice;
15 | }
16 |
17 | public decimal NewTaxRate { get; }
18 |
19 | public Action RefreshGrandTotalPrice { get; }
20 | }
21 | }
--------------------------------------------------------------------------------
/EntityClasses/EntityClasses.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.1
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/EntityClasses/LineItem.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 |
6 | namespace EntityClasses
7 | {
8 | public class LineItem
9 | {
10 | internal LineItem(int lineNum, string productName, decimal productPrice, int numOrdered)
11 | {
12 | LineNum = lineNum;
13 | ProductName = productName;
14 | ProductPrice = productPrice;
15 | NumOrdered = numOrdered;
16 | }
17 |
18 |
19 | public int LineItemId { get; private set; }
20 |
21 | public int LineNum { get; private set; }
22 |
23 | public string ProductName { get; private set; }
24 |
25 | public decimal ProductPrice { get; private set; }
26 |
27 | public int NumOrdered { get; private set; }
28 |
29 | //------------------------------------------
30 | //relationships
31 |
32 | public int OrderId { get; private set; }
33 | }
34 | }
--------------------------------------------------------------------------------
/EntityClasses/Order.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using EntityClasses.DomainEvents;
8 | using EntityClasses.SupportClasses;
9 | using GenericEventRunner.DomainParts;
10 |
11 | namespace EntityClasses
12 | {
13 | public class Order : EntityEventsBase
14 | {
15 | private HashSet _LineItems;
16 |
17 | public int OrderId { get; private set; }
18 | public string UserId { get; private set; }
19 |
20 | //The date we expect to dispatch the order
21 | public DateTime DispatchDate { get; private set; }
22 | public decimal TotalPriceNoTax { get; private set; }
23 |
24 | //Price and tax
25 | private decimal _taxRatePercent;
26 | public decimal TaxRatePercent
27 | {
28 | get => _taxRatePercent;
29 | private set
30 | {
31 | if (value != _taxRatePercent)
32 | AddEvent(new TaxRateChangedEvent(value, RefreshGrandTotalPrice));
33 | _taxRatePercent = value;
34 | }
35 | }
36 |
37 | private void RefreshGrandTotalPrice()
38 | {
39 | GrandTotalPrice = TotalPriceNoTax * (1 + TaxRatePercent / 100);
40 | }
41 |
42 | private void SetTaxRatePercent(decimal newValue)
43 | {
44 | TaxRatePercent = newValue;
45 | }
46 |
47 | public decimal GrandTotalPrice { get; private set; } // should be set by RefreshGrandTotalPrice method
48 |
49 | //----------------------------------------------
50 | //Relationships
51 |
52 | public IEnumerable LineItems => _LineItems.ToList();
53 |
54 | private Order() { } //For EF Core
55 |
56 | public Order(string userId, DateTime expectedDispatchDate, ICollection orderLines)
57 | {
58 | UserId = userId;
59 | DispatchDate = expectedDispatchDate;
60 | AddEvent(new OrderCreatedEvent(expectedDispatchDate, SetTaxRatePercent));
61 |
62 | var lineNum = 1;
63 | _LineItems = new HashSet(orderLines
64 | .Select(x => new LineItem(lineNum++, x.ProductName, x.ProductPrice, x.NumOrdered)));
65 |
66 | TotalPriceNoTax = 0;
67 | foreach (var basketItem in orderLines)
68 | {
69 | TotalPriceNoTax += basketItem.ProductPrice * basketItem.NumOrdered;
70 | AddEvent(new AllocateProductEvent(basketItem.ProductName, basketItem.NumOrdered));
71 | }
72 | }
73 |
74 | public void OrderReadyForDispatch(DateTime newDispatchDate)
75 | {
76 | if (OrderId == 0)
77 | throw new InvalidOperationException("You cannot call this method until the Order is written to the database.");
78 |
79 | DispatchDate = newDispatchDate;
80 | AddEvent(new OrderReadyToDispatchEvent(DispatchDate, SetTaxRatePercent), EventToSend.BeforeAndAfterSave);
81 | }
82 |
83 | }
84 | }
--------------------------------------------------------------------------------
/EntityClasses/ProductStock.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.ComponentModel.DataAnnotations;
5 |
6 | namespace EntityClasses
7 | {
8 | public class ProductStock
9 | {
10 | public ProductStock(string productName, int numInStock)
11 | {
12 | ProductName = productName;
13 | NumInStock = numInStock;
14 | NumAllocated = 0;
15 | }
16 |
17 | public string ProductName { get; set; }
18 |
19 | public int NumInStock { get; set; }
20 |
21 | ///
22 | /// This is used for checking the handling of concurrency issues.
23 | ///
24 | [ConcurrencyCheck]
25 | public int NumAllocated { get; set; }
26 | }
27 | }
--------------------------------------------------------------------------------
/EntityClasses/Review.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace EntityClasses
5 | {
6 | public class Review
7 | {
8 | private Review() { }
9 |
10 | internal Review(int numStars, string comment, string voterName, int bookId = default)
11 | {
12 | NumStars = numStars;
13 | Comment = comment;
14 | VoterName = voterName;
15 | BookId = bookId;
16 | }
17 |
18 | public int ReviewId { get; private set; }
19 |
20 | public string VoterName { get; private set; }
21 |
22 | public int NumStars { get; private set; }
23 | public string Comment { get; private set; }
24 |
25 | //-----------------------------------------
26 | //Relationships
27 |
28 | public int BookId { get; private set; }
29 | }
30 | }
--------------------------------------------------------------------------------
/EntityClasses/SupportClasses/BasketItemDto.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 |
6 | namespace EntityClasses.SupportClasses
7 | {
8 | public class BasketItemDto
9 | {
10 | public string ProductName { get; set; }
11 |
12 | public decimal ProductPrice { get; set; }
13 | public int NumOrdered { get; set; }
14 | }
15 | }
--------------------------------------------------------------------------------
/EntityClasses/SupportClasses/ICreatedUpdated.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using Microsoft.EntityFrameworkCore.ChangeTracking;
6 |
7 | namespace EntityClasses.SupportClasses
8 | {
9 | public interface ICreatedUpdated
10 | {
11 | DateTime WhenCreatedUtc { get; }
12 | DateTime LastUpdatedUtc { get; }
13 |
14 | void LogChange(bool added, EntityEntry entry);
15 | }
16 |
17 | }
--------------------------------------------------------------------------------
/EntityClasses/TaxRate.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using GenericEventRunner.DomainParts;
6 |
7 | namespace EntityClasses
8 | {
9 | public class TaxRate : EntityEventsBase
10 | {
11 | public TaxRate(DateTime effectiveFrom, decimal taxRatePercent)
12 | {
13 | EffectiveFrom = effectiveFrom;
14 | TaxRatePercent = taxRatePercent;
15 | }
16 |
17 | public int TaxRateId { get; set; }
18 | public DateTime EffectiveFrom { get; set; }
19 | public decimal TaxRatePercent { get; set; }
20 | }
21 | }
--------------------------------------------------------------------------------
/GenericEventRunner.DomainParts/EntityEventsBase.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.Collections.Generic;
5 | using System.Linq;
6 |
7 | namespace GenericEventRunner.DomainParts
8 | {
9 | ///
10 | /// This is a class that the EF Core entity classes inherit to add events
11 | ///
12 | public abstract class EntityEventsBase : IEntityWithBeforeSaveEvents, IEntityWithDuringSaveEvents, IEntityWithAfterSaveEvents
13 | {
14 | //Events are NOT stored in the database - they are transitory events
15 | //Events are created within a single DBContext and are cleared every time SaveChanges/SaveChangesAsync is called
16 |
17 | //This holds events that are run before SaveChanges is called
18 | private readonly List _beforeSaveEvents = new List();
19 |
20 | //This holds events that are run within a transaction containing a call to SaveChanges
21 | private readonly List _duringSaveEvents = new List();
22 |
23 | //This holds events that are run after SaveChanges finishes successfully
24 | private readonly List _afterSaveChangesEvents = new List();
25 |
26 | ///
27 | /// This allows an entity to add an event to this class
28 | ///
29 | /// This is the domain event you want to sent
30 | /// This allows you to send the event to either BeforeSave, DuringSave or AfterSave. Default is BeforeSave List
31 | public void AddEvent(IEntityEvent dEvent, EventToSend eventToSend = EventToSend.BeforeSave)
32 | {
33 | if (eventToSend == EventToSend.DuringSave)
34 | _duringSaveEvents.Add(dEvent);
35 | if (eventToSend == EventToSend.BeforeSave || eventToSend == EventToSend.BeforeAndAfterSave)
36 | _beforeSaveEvents.Add(dEvent);
37 | if (eventToSend == EventToSend.AfterSave || eventToSend == EventToSend.BeforeAndAfterSave)
38 | _afterSaveChangesEvents.Add(dEvent);
39 | }
40 |
41 | ///
42 | /// This gets all the events in the BeforeSaveEvents list, and clears that list at the same time
43 | ///
44 | public ICollection GetBeforeSaveEventsThenClear()
45 | {
46 | var eventCopy = _beforeSaveEvents.ToList();
47 | _beforeSaveEvents.Clear();
48 | return eventCopy;
49 | }
50 |
51 | ///
52 | /// This returns the events that should be run within a transaction containing a call to SaveChanges
53 | ///
54 | public ICollection GetDuringSaveEvents()
55 | {
56 | return _duringSaveEvents;
57 | }
58 |
59 | ///
60 | /// This clears all the during save events once the code within the transaction has finished
61 | ///
62 | public void ClearDuringSaveEvents()
63 | {
64 | _duringSaveEvents.Clear();
65 | }
66 |
67 | ///
68 | /// This gets all the events in the AfterSaveEvents list, and clears that list at the same time
69 | ///
70 | public ICollection GetAfterSaveEventsThenClear()
71 | {
72 | var eventCopy = _afterSaveChangesEvents.ToList();
73 | _afterSaveChangesEvents.Clear();
74 | return eventCopy;
75 | }
76 |
77 | }
78 | }
--------------------------------------------------------------------------------
/GenericEventRunner.DomainParts/EventToSend.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace GenericEventRunner.DomainParts
5 | {
6 | ///
7 | /// This allows you to control which list, the BeforeSave and AfterSave, to add the event to.
8 | ///
9 | public enum EventToSend
10 | {
11 | ///
12 | /// This puts an event into BeforeSaveEvents list
13 | ///
14 | BeforeSave,
15 | ///
16 | /// This puts an event into the DuringSaveEvents list
17 | ///
18 | DuringSave,
19 | ///
20 | /// This puts an event into AfterSaveEvents list
21 | ///
22 | AfterSave,
23 | ///
24 | /// This puts an event into both the BeforeSaveEvents list and the AfterSaveEvents list
25 | ///
26 | BeforeAndAfterSave
27 |
28 | }
29 | }
--------------------------------------------------------------------------------
/GenericEventRunner.DomainParts/GenericEventRunner.DomainParts.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 |
6 |
7 |
8 | true
9 | 2.2.1
10 | 2.2.1
11 | 2.2.1.0
12 | 2.2.1.0
13 | EfCore.GenericEventRunner.DomainParts
14 | Jon P Smith
15 | Selective Analytics
16 | EfCore.GenericEventRunner.DomainParts
17 | Defines basic interfaces/classes for EfCore.GenericEventRunner when using Clean Code architecture.
18 | Copyright (c) 2020 Jon P Smith
19 | https://github.com/JonPSmith/EfCore.GenericEventRunner/blob/master/LICENSE
20 | https://github.com/JonPSmith/EfCore.GenericEventRunner
21 | https://github.com/JonPSmith/EfCore.GenericEventRunner
22 | GitHub
23 | EfCore.GenericServices, EfCore.GenericEventRunner
24 |
25 | - New Feature: RemoveDuplicateEvents attribute allows you to mark an event so that duplicate events are rolled into one (see wiki for more info)
26 |
27 | https://raw.githubusercontent.com/JonPSmith/EfCore.GenericEventRunner/master/GenericEventsRunnerDomainNuGetIcon128.png
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/GenericEventRunner.DomainParts/GenericEventsRunnerDomainNuGetIcon128.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JonPSmith/EfCore.GenericEventRunner/e556e175b9d8ea9bf742974b8891a11b37cf5f4a/GenericEventRunner.DomainParts/GenericEventsRunnerDomainNuGetIcon128.png
--------------------------------------------------------------------------------
/GenericEventRunner.DomainParts/IEntityEvent.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | namespace GenericEventRunner.DomainParts
5 | {
6 | ///
7 | /// This is an empty interface that events should inherit
8 | ///
9 | public interface IEntityEvent { }
10 | }
--------------------------------------------------------------------------------
/GenericEventRunner.DomainParts/IEntityWithAfterSaveEvents.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.Collections.Generic;
5 |
6 | namespace GenericEventRunner.DomainParts
7 | {
8 | ///
9 | /// Add this interface to an entity class to support AfterSaveEvents
10 | ///
11 | public interface IEntityWithAfterSaveEvents
12 | {
13 | ///
14 | /// This gets all the events in the AfterSaveEvents list, and clears that list at the same time
15 | ///
16 | ICollection GetAfterSaveEventsThenClear();
17 | }
18 | }
--------------------------------------------------------------------------------
/GenericEventRunner.DomainParts/IEntityWithBeforeSaveEvents.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.Collections.Generic;
5 |
6 | namespace GenericEventRunner.DomainParts
7 | {
8 | ///
9 | /// Add this interface to an entity class to support BeforeSaveEvents
10 | ///
11 | public interface IEntityWithBeforeSaveEvents
12 | {
13 | ///
14 | /// This gets all the events in the BeforeSaveEvents list, and clears that list at the same time
15 | ///
16 | ICollection GetBeforeSaveEventsThenClear();
17 | }
18 | }
--------------------------------------------------------------------------------
/GenericEventRunner.DomainParts/IEntityWithDuringSaveEvents.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.Collections.Generic;
5 |
6 | namespace GenericEventRunner.DomainParts
7 | {
8 | ///
9 | /// Add this interface to an entity class to support tDuringSaveEvents
10 | ///
11 | public interface IEntityWithDuringSaveEvents
12 | {
13 | ///
14 | /// This returns the events that should be run within a transaction containing a call to SaveChanges
15 | ///
16 | ICollection GetDuringSaveEvents();
17 |
18 | ///
19 | /// This clears all the during save events once the code within the transaction has finished
20 | ///
21 | void ClearDuringSaveEvents();
22 | }
23 | }
--------------------------------------------------------------------------------
/GenericEventRunner.DomainParts/MakeDuringEventRunBeforeSaveChangesAttribute.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 |
6 | namespace GenericEventRunner.DomainParts
7 | {
8 | ///
9 | /// Add this attribute to a During to make the event handler run before SaveChanges
10 | ///
11 | [AttributeUsage(AttributeTargets.Class)]
12 | public class MakeDuringEventRunBeforeSaveChangesAttribute : Attribute
13 | {
14 | }
15 | }
--------------------------------------------------------------------------------
/GenericEventRunner.DomainParts/RemoveDuplicateEventsAttribute.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 |
6 | namespace GenericEventRunner.DomainParts
7 | {
8 | ///
9 | /// Add this attribute to a and the EventRunner will remove events that a) have the same type, and b) come from the same entity
10 | ///
11 | [AttributeUsage(AttributeTargets.Class)]
12 | public class RemoveDuplicateEventsAttribute : Attribute
13 | {
14 |
15 | }
16 | }
--------------------------------------------------------------------------------
/GenericEventRunner.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29424.173
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GenericEventRunner", "GenericEventRunner\GenericEventRunner.csproj", "{4F20200E-71FC-40FB-9E29-571081A50BC2}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityClasses", "EntityClasses\EntityClasses.csproj", "{D48D1BDB-6AB3-4A4D-88D6-0477CD9241B9}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DataLayer", "DataLayer\DataLayer.csproj", "{FA7550E5-9D97-46BF-B6E5-3A65C4AD9433}"
11 | EndProject
12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Infrastructure", "Infrastructure\Infrastructure.csproj", "{6EFA5E3F-2A46-4AC5-B636-A40D9CF40DB9}"
13 | EndProject
14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test", "Test\Test.csproj", "{2DB798EC-BC1A-496B-82C1-9542E34AA1E8}"
15 | EndProject
16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{DC1820DB-E4BC-4D89-91E3-12743A3A7C06}"
17 | ProjectSection(SolutionItems) = preProject
18 | GenericEventRunnerTypesOfEvents.png = GenericEventRunnerTypesOfEvents.png
19 | GenericEventsRunnerDomainNuGetIcon128.png = GenericEventsRunnerDomainNuGetIcon128.png
20 | GenericEventsRunnerNuGetIcon128.png = GenericEventsRunnerNuGetIcon128.png
21 | LICENSE = LICENSE
22 | README.md = README.md
23 | ReleaseNotes.md = ReleaseNotes.md
24 | EndProjectSection
25 | EndProject
26 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GenericEventRunner.DomainParts", "GenericEventRunner.DomainParts\GenericEventRunner.DomainParts.csproj", "{B8044A25-8009-41BB-B9AC-45D45DA47B21}"
27 | EndProject
28 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OnlyBeforeHandlers", "OnlyBeforeHandlers\OnlyBeforeHandlers.csproj", "{0824BF78-5361-437E-91BF-E650FDDDF634}"
29 | EndProject
30 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OnlyDuringHandlers", "OnlyDuringHandlers\OnlyDuringHandlers.csproj", "{F8156BEE-0161-4F6A-ADD4-D39F964C6E8D}"
31 | EndProject
32 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OnlyAfterHandlers", "OnlyAfterHandlers\OnlyAfterHandlers.csproj", "{FE2D69FF-5EE4-4986-ADE7-64842056ADA4}"
33 | EndProject
34 | Global
35 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
36 | Debug|Any CPU = Debug|Any CPU
37 | Release|Any CPU = Release|Any CPU
38 | EndGlobalSection
39 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
40 | {4F20200E-71FC-40FB-9E29-571081A50BC2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
41 | {4F20200E-71FC-40FB-9E29-571081A50BC2}.Debug|Any CPU.Build.0 = Debug|Any CPU
42 | {4F20200E-71FC-40FB-9E29-571081A50BC2}.Release|Any CPU.ActiveCfg = Release|Any CPU
43 | {4F20200E-71FC-40FB-9E29-571081A50BC2}.Release|Any CPU.Build.0 = Release|Any CPU
44 | {D48D1BDB-6AB3-4A4D-88D6-0477CD9241B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
45 | {D48D1BDB-6AB3-4A4D-88D6-0477CD9241B9}.Debug|Any CPU.Build.0 = Debug|Any CPU
46 | {D48D1BDB-6AB3-4A4D-88D6-0477CD9241B9}.Release|Any CPU.ActiveCfg = Release|Any CPU
47 | {D48D1BDB-6AB3-4A4D-88D6-0477CD9241B9}.Release|Any CPU.Build.0 = Release|Any CPU
48 | {FA7550E5-9D97-46BF-B6E5-3A65C4AD9433}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
49 | {FA7550E5-9D97-46BF-B6E5-3A65C4AD9433}.Debug|Any CPU.Build.0 = Debug|Any CPU
50 | {FA7550E5-9D97-46BF-B6E5-3A65C4AD9433}.Release|Any CPU.ActiveCfg = Release|Any CPU
51 | {FA7550E5-9D97-46BF-B6E5-3A65C4AD9433}.Release|Any CPU.Build.0 = Release|Any CPU
52 | {6EFA5E3F-2A46-4AC5-B636-A40D9CF40DB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
53 | {6EFA5E3F-2A46-4AC5-B636-A40D9CF40DB9}.Debug|Any CPU.Build.0 = Debug|Any CPU
54 | {6EFA5E3F-2A46-4AC5-B636-A40D9CF40DB9}.Release|Any CPU.ActiveCfg = Release|Any CPU
55 | {6EFA5E3F-2A46-4AC5-B636-A40D9CF40DB9}.Release|Any CPU.Build.0 = Release|Any CPU
56 | {2DB798EC-BC1A-496B-82C1-9542E34AA1E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
57 | {2DB798EC-BC1A-496B-82C1-9542E34AA1E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
58 | {2DB798EC-BC1A-496B-82C1-9542E34AA1E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
59 | {2DB798EC-BC1A-496B-82C1-9542E34AA1E8}.Release|Any CPU.Build.0 = Release|Any CPU
60 | {B8044A25-8009-41BB-B9AC-45D45DA47B21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
61 | {B8044A25-8009-41BB-B9AC-45D45DA47B21}.Debug|Any CPU.Build.0 = Debug|Any CPU
62 | {B8044A25-8009-41BB-B9AC-45D45DA47B21}.Release|Any CPU.ActiveCfg = Release|Any CPU
63 | {B8044A25-8009-41BB-B9AC-45D45DA47B21}.Release|Any CPU.Build.0 = Release|Any CPU
64 | {0824BF78-5361-437E-91BF-E650FDDDF634}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
65 | {0824BF78-5361-437E-91BF-E650FDDDF634}.Debug|Any CPU.Build.0 = Debug|Any CPU
66 | {0824BF78-5361-437E-91BF-E650FDDDF634}.Release|Any CPU.ActiveCfg = Release|Any CPU
67 | {0824BF78-5361-437E-91BF-E650FDDDF634}.Release|Any CPU.Build.0 = Release|Any CPU
68 | {F8156BEE-0161-4F6A-ADD4-D39F964C6E8D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
69 | {F8156BEE-0161-4F6A-ADD4-D39F964C6E8D}.Debug|Any CPU.Build.0 = Debug|Any CPU
70 | {F8156BEE-0161-4F6A-ADD4-D39F964C6E8D}.Release|Any CPU.ActiveCfg = Release|Any CPU
71 | {F8156BEE-0161-4F6A-ADD4-D39F964C6E8D}.Release|Any CPU.Build.0 = Release|Any CPU
72 | {FE2D69FF-5EE4-4986-ADE7-64842056ADA4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
73 | {FE2D69FF-5EE4-4986-ADE7-64842056ADA4}.Debug|Any CPU.Build.0 = Debug|Any CPU
74 | {FE2D69FF-5EE4-4986-ADE7-64842056ADA4}.Release|Any CPU.ActiveCfg = Release|Any CPU
75 | {FE2D69FF-5EE4-4986-ADE7-64842056ADA4}.Release|Any CPU.Build.0 = Release|Any CPU
76 | EndGlobalSection
77 | GlobalSection(SolutionProperties) = preSolution
78 | HideSolutionNode = FALSE
79 | EndGlobalSection
80 | GlobalSection(ExtensibilityGlobals) = postSolution
81 | SolutionGuid = {B80DB149-6811-4CA4-87C2-087E9AF5D5BC}
82 | EndGlobalSection
83 | EndGlobal
84 |
--------------------------------------------------------------------------------
/GenericEventRunner/ForDbContext/DbContextWithEvents.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using System.Linq;
6 | using System.Threading;
7 | using System.Threading.Tasks;
8 | using GenericEventRunner.DomainParts;
9 | using GenericEventRunner.ForHandlers;
10 | using Microsoft.EntityFrameworkCore;
11 | using StatusGeneric;
12 |
13 | namespace GenericEventRunner.ForDbContext
14 | {
15 | ///
16 | /// If you want to add GenericEventsRunner to your DbContext then inherit this instead of DbContext
17 | /// This overrides the base SaveChanges/SaveChangesAsync to add the event runner before and after the call the base SaveChanges/SaveChangesAsync
18 | ///
19 | /// If you don't like inheriting this class then you can copy this code directly into your own DbContext
20 | ///
21 | ///
22 | public class DbContextWithEvents : DbContext, IStatusFromLastSaveChanges where T : DbContext
23 | {
24 | private readonly IEventsRunner _eventsRunner;
25 |
26 | ///
27 | /// This returns the Status of last SaveChanges/Async and SaveChangesWithStatus/Async
28 | /// NOTE: This is null if no event handler is provided, or if none of the SaveChanges/Async etc. has not been called yet.
29 | ///
30 | public IStatusGeneric StatusFromLastSaveChanges { get; private set; }
31 |
32 |
33 | ///
34 | /// This sets up the DbContext options and adds the eventRunner
35 | ///
36 | /// normal EF Core options for a database
37 | /// The Generic Event Runner - can be null which will turn off domain event handling
38 | protected DbContextWithEvents(DbContextOptions options, IEventsRunner eventsRunner) : base(options)
39 | {
40 | _eventsRunner = eventsRunner;
41 | }
42 |
43 | ///
44 | /// This is a spacial form of SaveChanges that returns an status
45 | ///
46 | /// normal SaveChanges option
47 | /// Status, with a Result that is the number of updates down by SaveChanges
48 | public IStatusGeneric SaveChangesWithStatus(bool acceptAllChangesOnSuccess = true)
49 | {
50 | if (_eventsRunner == null)
51 | throw new GenericEventRunnerException($"The {nameof(SaveChangesWithStatus)} cannot be used unless the event runner is present");
52 |
53 | StatusFromLastSaveChanges = _eventsRunner.RunEventsBeforeDuringAfterSaveChanges(this,
54 | () => base.SaveChanges(acceptAllChangesOnSuccess));
55 |
56 | return StatusFromLastSaveChanges;
57 | }
58 |
59 | ///
60 | /// This is a spacial form of SaveChangesAsync that returns an status
61 | ///
62 | ///
63 | ///
64 | /// Status, with a Result that is the number of updates down by SaveChangesAsync
65 | public async Task> SaveChangesWithStatusAsync(bool acceptAllChangesOnSuccess = true,
66 | CancellationToken cancellationToken = default)
67 | {
68 | if (_eventsRunner == null)
69 | throw new GenericEventRunnerException($"The {nameof(SaveChangesWithStatusAsync)} cannot be used unless the event runner is present");
70 |
71 | StatusFromLastSaveChanges = await _eventsRunner.RunEventsBeforeDuringAfterSaveChangesAsync(this,
72 | () => base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken), cancellationToken).ConfigureAwait(false);
73 |
74 | return StatusFromLastSaveChanges;
75 | }
76 |
77 | //I only have to override these two version of SaveChanges, as the other two versions call these
78 |
79 | ///
80 | /// EF Core's SaveChanges, but with domain event handling added
81 | /// Throws an exception if any of the BeforeSave event handlers return a status with an error in it.
82 | ///
83 | ///
84 | /// number of writes done to the database
85 | public override int SaveChanges(bool acceptAllChangesOnSuccess)
86 | {
87 | if (_eventsRunner == null)
88 | return base.SaveChanges(acceptAllChangesOnSuccess);
89 |
90 | StatusFromLastSaveChanges = SaveChangesWithStatus(acceptAllChangesOnSuccess);
91 |
92 | if (StatusFromLastSaveChanges.IsValid)
93 | return StatusFromLastSaveChanges.Result;
94 |
95 | throw new GenericEventRunnerStatusException(StatusFromLastSaveChanges);
96 | }
97 |
98 | ///
99 | /// EF Core's SaveChanges, but with domain event handling added
100 | /// Throws an exception if any of the BeforeSave event handlers return a status with an error in it.
101 | ///
102 | ///
103 | ///
104 | ///
105 | public override async Task SaveChangesAsync(bool acceptAllChangesOnSuccess,
106 | CancellationToken cancellationToken = default)
107 | {
108 | if (_eventsRunner == null)
109 | return await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken).ConfigureAwait(false);
110 |
111 | StatusFromLastSaveChanges = await SaveChangesWithStatusAsync(acceptAllChangesOnSuccess, cancellationToken)
112 | .ConfigureAwait(false);
113 |
114 | if (StatusFromLastSaveChanges.IsValid)
115 | return StatusFromLastSaveChanges.Result;
116 |
117 | throw new GenericEventRunnerStatusException(StatusFromLastSaveChanges);
118 | }
119 | }
120 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForDbContext/GenericEventRunnerStatusException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License file in the project root for license information.
3 |
4 | using System;
5 | using StatusGeneric;
6 |
7 | namespace GenericEventRunner.ForDbContext
8 | {
9 | ///
10 | /// This exception is thrown in the overridden SaveChanges/Async method if any of the BeforeSave handlers return errors.
11 | ///
12 | public class GenericEventRunnerStatusException : Exception
13 | {
14 | ///
15 | /// This
16 | ///
17 | /// The status returned from the BeforeSave event handlers
18 | public GenericEventRunnerStatusException(IStatusGeneric status)
19 | : base($"{status.Message}{Environment.NewLine}{status.GetAllErrors()}")
20 | {
21 | }
22 |
23 | }
24 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForDbContext/IEventsRunner.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using System.Threading;
6 | using System.Threading.Tasks;
7 | using Microsoft.EntityFrameworkCore;
8 | using StatusGeneric;
9 |
10 | namespace GenericEventRunner.ForDbContext
11 | {
12 | ///
13 | /// This is the interface for the Events Runner that is in the DbContext
14 | ///
15 | public interface IEventsRunner
16 | {
17 | ///
18 | /// This Handles the running of the BeforeSave Event Handlers
19 | ///
20 | ///
21 | /// This calls the base SaveChanges.
22 | ///
23 | IStatusGeneric RunEventsBeforeDuringAfterSaveChanges(DbContext context,
24 | Func callBaseSaveChanges);
25 |
26 | ///
27 | /// This Handles the running of the BeforeSave Event Handlers
28 | ///
29 | ///
30 | /// This calls the base SaveChangesAsync.
31 | ///
32 | ///
33 | Task> RunEventsBeforeDuringAfterSaveChangesAsync(DbContext context,
34 | Func> callBaseSaveChangesAsync, CancellationToken cancellationToken);
35 | }
36 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForDbContext/IStatusFromLastSaveChanges.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License file in the project root for license information.
3 |
4 | using StatusGeneric;
5 |
6 | namespace GenericEventRunner.ForDbContext
7 | {
8 | ///
9 | /// Interface to access Status filled in by EventsRunner
10 | ///
11 | public interface IStatusFromLastSaveChanges
12 | {
13 | ///
14 | /// This returns the Status of last SaveChanges/Async and SaveChangesWithStatus/Async done by the GenericEventRunner
15 | /// Useful if you are capturing the GenericEventRunnerStatusException and want to get the Status that goes with it.
16 | /// NOTE: This is null if no event handler is provided, or SaveChanges/Async etc. have not been called yet.
17 | ///
18 | IStatusGeneric StatusFromLastSaveChanges { get; }
19 | }
20 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/EventHandlerConfigAttribute.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using Microsoft.Extensions.DependencyInjection;
6 |
7 | namespace GenericEventRunner.ForHandlers
8 | {
9 | ///
10 | /// TYou can add this attribute to a event handler to override some of the default or configuration settings
11 | ///
12 | [AttributeUsage(AttributeTargets.Class)]
13 | public class EventHandlerConfigAttribute : Attribute
14 | {
15 | ///
16 | /// This allows you to alter some of the aspects of a handler
17 | ///
18 | /// This controls the lifetime of a handler when registered in the DI. Default = Transient
19 | public EventHandlerConfigAttribute(ServiceLifetime handlerLifetime = ServiceLifetime.Transient)
20 | {
21 | HandlerLifetime = handlerLifetime;
22 | }
23 |
24 | ///
25 | /// This holds the Lifetime of the class when created by via DI
26 | ///
27 | public ServiceLifetime HandlerLifetime { get; }
28 |
29 | }
30 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/GenericEventRunnerException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using GenericEventRunner.DomainParts;
6 |
7 | namespace GenericEventRunner.ForHandlers
8 | {
9 | ///
10 | /// This is used to report any problems in the GenericEventRunner
11 | ///
12 | public class GenericEventRunnerException : Exception
13 | {
14 | ///
15 | /// This creates an exception just with a message
16 | ///
17 | ///
18 | public GenericEventRunnerException(string message)
19 | : base(message)
20 | {
21 | }
22 |
23 | ///
24 | /// This allows you to create an exception with the callingEntity and domainEvent type names
25 | ///
26 | ///
27 | ///
28 | ///
29 | public GenericEventRunnerException(string message, object callingEntity, IEntityEvent entityEvent)
30 | : base(message)
31 | {
32 | Data.Add("CallingEntityType", callingEntity.GetType().FullName);
33 | Data.Add("DomainEventType", entityEvent.GetType().FullName);
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/IAfterSaveEventHandler.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using GenericEventRunner.DomainParts;
5 |
6 | namespace GenericEventRunner.ForHandlers
7 | {
8 | ///
9 | /// Place this on any event handler that should be called after SaveChanges has updated the database
10 | ///
11 | /// This should be the domain event that this handler is looking for
12 | public interface IAfterSaveEventHandler where T : IEntityEvent
13 | {
14 | ///
15 | /// This is the method you must define to produce a AfterSave event handler
16 | ///
17 | ///
18 | ///
19 | void Handle(object callingEntity, T domainEvent);
20 | }
21 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/IAfterSaveEventHandlerAsync.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.Threading.Tasks;
5 | using GenericEventRunner.DomainParts;
6 |
7 | namespace GenericEventRunner.ForHandlers
8 | {
9 | ///
10 | /// Place this on any async event handler that should be called after SaveChanges has updated the database
11 | ///
12 | /// This should be the domain event that this handler is looking for
13 | public interface IAfterSaveEventHandlerAsync where T : IEntityEvent
14 | {
15 | ///
16 | /// This is the method you must define to produce a AfterSave event handler
17 | ///
18 | ///
19 | ///
20 | Task HandleAsync(object callingEntity, T domainEvent);
21 | }
22 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/IBeforeSaveEventHandler.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using GenericEventRunner.DomainParts;
5 | using StatusGeneric;
6 |
7 | namespace GenericEventRunner.ForHandlers
8 | {
9 | ///
10 | /// Place this on any event handler that should be called before SaveChanges has updated the database
11 | ///
12 | /// This should be the domain event that this handler is looking for
13 | public interface IBeforeSaveEventHandler where T : IEntityEvent
14 | {
15 | ///
16 | /// This is the method you must define to produce a BeforeSave event handler
17 | ///
18 | ///
19 | ///
20 | /// This can be null if you don't want to return a status, otherwise it should be a IStatusGeneric type
21 | IStatusGeneric Handle(object callingEntity, T domainEvent);
22 | }
23 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/IBeforeSaveEventHandlerAsync.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.Threading.Tasks;
5 | using GenericEventRunner.DomainParts;
6 | using StatusGeneric;
7 |
8 | namespace GenericEventRunner.ForHandlers
9 | {
10 | ///
11 | /// Place this on any async event handler that should be called before SaveChanges has updated the database
12 | ///
13 | /// This should be the domain event that this handler is looking for
14 | public interface IBeforeSaveEventHandlerAsync where T : IEntityEvent
15 | {
16 | ///
17 | /// This is the method you must define to produce a BeforeSave event handler
18 | ///
19 | ///
20 | ///
21 | /// This can be null if you don't want to return a status, otherwise it should be a IStatusGeneric type
22 | Task HandleAsync(object callingEntity, T domainEvent);
23 | }
24 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/IDuringSaveEventHandler.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using GenericEventRunner.DomainParts;
6 | using StatusGeneric;
7 |
8 | namespace GenericEventRunner.ForHandlers
9 | {
10 | ///
11 | /// Place this on any event handler that should be called within a transaction containing a call to SaveChanges
12 | ///
13 | /// This should be the domain event that this handler is looking for
14 | public interface IDuringSaveEventHandler where T : IEntityEvent
15 | {
16 | ///
17 | /// This is the method you must define to produce a AfterSave event handler
18 | ///
19 | ///
20 | ///
21 | /// A unique value per transaction. This allows you to detect retries of transactions
22 | /// You must return a IStatusGeneric. If has an error the transaction will be rolled back
23 | IStatusGeneric Handle(object callingEntity, T domainEvent, Guid uniqueKey);
24 | }
25 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/IDuringSaveEventHandlerAsync.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using System.Threading.Tasks;
6 | using GenericEventRunner.DomainParts;
7 | using StatusGeneric;
8 |
9 | namespace GenericEventRunner.ForHandlers
10 | {
11 | ///
12 | /// Place this on any event handler that should be called within a transaction containing a call to SaveChanges
13 | ///
14 | /// This should be the domain event that this handler is looking for
15 | public interface IDuringSaveEventHandlerAsync where T : IEntityEvent
16 | {
17 | ///
18 | /// This is the method you must define to produce a AfterSave event handler
19 | ///
20 | ///
21 | ///
22 | /// A unique value per transaction. This allows you to detect retries of transactions
23 | /// You must return a IStatusGeneric. If has an error the transaction will be rolled back
24 | Task HandleAsync(object callingEntity, T domainEvent, Guid uniqueKey);
25 | }
26 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/Internal/AfterEntityAndEvent.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using GenericEventRunner.DomainParts;
5 |
6 | namespace GenericEventRunner.ForHandlers.Internal
7 | {
8 | internal class AfterEntityAndEvent
9 | {
10 | public AfterEntityAndEvent(IEntityWithAfterSaveEvents callingEntity, IEntityEvent entityEvent)
11 | {
12 | CallingEntity = callingEntity;
13 | EntityEvent = entityEvent;
14 | }
15 |
16 | public IEntityWithAfterSaveEvents CallingEntity { get; }
17 | public IEntityEvent EntityEvent { get; }
18 | }
19 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/Internal/AfterSaveEventHandler.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.Runtime.Serialization;
5 | using GenericEventRunner.DomainParts;
6 |
7 | namespace GenericEventRunner.ForHandlers.Internal
8 | {
9 | internal abstract class AfterSaveEventHandler
10 | {
11 | public abstract void Handle(object callingEntity, IEntityEvent entityEvent);
12 | }
13 |
14 | internal class AfterSaveHandler : AfterSaveEventHandler
15 | where T : IEntityEvent
16 | {
17 | private readonly IAfterSaveEventHandler _handler;
18 |
19 | public AfterSaveHandler(IAfterSaveEventHandler handler)
20 | {
21 | _handler = handler;
22 | }
23 |
24 | public override void Handle(object callingEntity, IEntityEvent entityEvent)
25 | {
26 | _handler.Handle(callingEntity, (T)entityEvent);
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/Internal/AfterSaveEventHandlerAsync.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.Threading.Tasks;
5 | using GenericEventRunner.DomainParts;
6 |
7 | namespace GenericEventRunner.ForHandlers.Internal
8 | {
9 | internal abstract class AfterSaveEventHandlerAsync
10 | {
11 | public abstract Task HandleAsync(object callingEntity, IEntityEvent entityEvent);
12 | }
13 |
14 | internal class AfterSaveHandlerAsync : AfterSaveEventHandlerAsync
15 | where T : IEntityEvent
16 | {
17 | private readonly IAfterSaveEventHandlerAsync _handler;
18 |
19 | public AfterSaveHandlerAsync(IAfterSaveEventHandlerAsync handler)
20 | {
21 | _handler = handler;
22 | }
23 |
24 | public override Task HandleAsync(object callingEntity, IEntityEvent entityEvent)
25 | {
26 | return _handler.HandleAsync(callingEntity, (T)entityEvent);
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/Internal/AsyncHelper.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using System.Threading;
6 | using System.Threading.Tasks;
7 |
8 | namespace GenericEventRunner.ForHandlers.Internal
9 | {
10 | //Thanks to https://cpratt.co/async-tips-tricks/
11 | internal static class AsyncHelper
12 | {
13 | private static readonly TaskFactory TaskFactory = new
14 | TaskFactory(CancellationToken.None,
15 | TaskCreationOptions.None,
16 | TaskContinuationOptions.None,
17 | TaskScheduler.Default);
18 |
19 | public static TResult RunSync(Func> func)
20 | => TaskFactory
21 | .StartNew(func)
22 | .Unwrap()
23 | .GetAwaiter()
24 | .GetResult();
25 |
26 | public static void RunSync(Func func)
27 | => TaskFactory
28 | .StartNew(func)
29 | .Unwrap()
30 | .GetAwaiter()
31 | .GetResult();
32 | }
33 |
34 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/Internal/BeforeSaveEventHandler.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using GenericEventRunner.DomainParts;
5 | using StatusGeneric;
6 |
7 | namespace GenericEventRunner.ForHandlers.Internal
8 | {
9 | internal abstract class BeforeSaveEventHandler
10 | {
11 | public abstract IStatusGeneric Handle(object callingEntity, IEntityEvent entityEvent);
12 | }
13 |
14 | internal class BeforeSaveHandler : BeforeSaveEventHandler
15 | where T : IEntityEvent
16 | {
17 | private readonly IBeforeSaveEventHandler _handler;
18 |
19 | public BeforeSaveHandler(IBeforeSaveEventHandler handler)
20 | {
21 | _handler = handler;
22 | }
23 |
24 | public override IStatusGeneric Handle(object callingEntity, IEntityEvent entityEvent)
25 | {
26 | return _handler.Handle(callingEntity, (T)entityEvent);
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/Internal/BeforeSaveEventHandlerAsync.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.Threading.Tasks;
5 | using GenericEventRunner.DomainParts;
6 | using StatusGeneric;
7 |
8 | namespace GenericEventRunner.ForHandlers.Internal
9 | {
10 | internal abstract class BeforeSaveEventHandlerAsync
11 | {
12 | public abstract Task HandleAsync(object callingEntity, IEntityEvent entityEvent);
13 | }
14 |
15 | internal class BeforeSaveHandlerAsync : BeforeSaveEventHandlerAsync
16 | where T : IEntityEvent
17 | {
18 | private readonly IBeforeSaveEventHandlerAsync _handler;
19 |
20 | public BeforeSaveHandlerAsync(IBeforeSaveEventHandlerAsync handler)
21 | {
22 | _handler = handler;
23 | }
24 |
25 | public override Task HandleAsync(object callingEntity, IEntityEvent entityEvent)
26 | {
27 | return _handler.HandleAsync(callingEntity, (T)entityEvent);
28 | }
29 | }
30 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/Internal/DuringEventsExtensions.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System.Linq;
5 | using GenericEventRunner.DomainParts;
6 | using Microsoft.EntityFrameworkCore;
7 |
8 | namespace GenericEventRunner.ForHandlers.Internal
9 | {
10 | internal static class DuringEventsExtensions
11 | {
12 |
13 | public static void ClearDuringEvents(this DbContext context)
14 | {
15 | context.ChangeTracker.Entries().ToList()
16 | .ForEach(x => x.Entity.ClearDuringSaveEvents());
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/Internal/DuringSaveEventHandler.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using GenericEventRunner.DomainParts;
6 | using StatusGeneric;
7 |
8 | namespace GenericEventRunner.ForHandlers.Internal
9 | {
10 | internal abstract class DuringSaveEventHandler
11 | {
12 | public abstract IStatusGeneric Handle(object callingEntity, IEntityEvent entityEvent, Guid uniqueKey);
13 | }
14 |
15 | internal class DuringSaveHandler : DuringSaveEventHandler
16 | where T : IEntityEvent
17 | {
18 | private readonly IDuringSaveEventHandler _handler;
19 |
20 | public DuringSaveHandler(IDuringSaveEventHandler handler)
21 | {
22 | _handler = handler;
23 | }
24 |
25 | public override IStatusGeneric Handle(object callingEntity, IEntityEvent entityEvent, Guid uniqueKey)
26 | {
27 | return _handler.Handle(callingEntity, (T)entityEvent, uniqueKey);
28 | }
29 | }
30 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/Internal/DuringSaveEventHandlerAsync.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using System.Threading.Tasks;
6 | using GenericEventRunner.DomainParts;
7 | using StatusGeneric;
8 |
9 | namespace GenericEventRunner.ForHandlers.Internal
10 | {
11 | internal abstract class DuringSaveEventHandlerAsync
12 | {
13 | public abstract Task HandleAsync(object callingEntity, IEntityEvent entityEvent, Guid uniqueKey);
14 | }
15 |
16 | internal class DuringSaveHandlerAsync : DuringSaveEventHandlerAsync
17 | where T : IEntityEvent
18 | {
19 | private readonly IDuringSaveEventHandlerAsync _handler;
20 |
21 | public DuringSaveHandlerAsync(IDuringSaveEventHandlerAsync handler)
22 | {
23 | _handler = handler;
24 | }
25 |
26 | public override Task HandleAsync(object callingEntity, IEntityEvent entityEvent, Guid uniqueKey)
27 | {
28 | return _handler.HandleAsync(callingEntity, (T)entityEvent, uniqueKey);
29 | }
30 | }
31 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/Internal/EntityAndEvent.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2019 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using System.Reflection;
6 | using System.Runtime.CompilerServices;
7 | using GenericEventRunner.DomainParts;
8 |
9 | [assembly: InternalsVisibleTo("Test")]
10 |
11 | namespace GenericEventRunner.ForHandlers.Internal
12 | {
13 | internal class EntityAndEvent
14 | {
15 | public EntityAndEvent(object callingEntity, IEntityEvent entityEvent)
16 | {
17 | CallingEntity = callingEntity ?? throw new ArgumentNullException(nameof(callingEntity));
18 | EntityEvent = entityEvent ?? throw new ArgumentNullException(nameof(entityEvent));
19 | HasRemoveDuplicateAttribute = EntityEvent
20 | .GetType()
21 | .GetCustomAttribute() != null;
22 | HasDuringEventRunBeforeSave = EntityEvent
23 | .GetType()
24 | .GetCustomAttribute() != null;
25 | }
26 |
27 | public object CallingEntity { get; }
28 | public IEntityEvent EntityEvent { get; }
29 |
30 | public bool HasRemoveDuplicateAttribute { get; }
31 | public bool HasDuringEventRunBeforeSave { get; }
32 |
33 | private bool Equals(EntityAndEvent other)
34 | {
35 | //Only equal if class has the RemoveDuplicate attribute
36 | return HasRemoveDuplicateAttribute &&
37 | EntityEvent.GetType() == other.EntityEvent.GetType() &&
38 | ReferenceEquals(CallingEntity, other.CallingEntity);
39 | }
40 |
41 | public override bool Equals(object obj)
42 | {
43 | return obj is EntityAndEvent other && Equals(other);
44 | }
45 |
46 | //see https://stackoverflow.com/questions/21402465/iequalitycomparer-not-working-as-intended
47 | public override int GetHashCode()
48 | {
49 | return HashCode.Combine(CallingEntity, EntityEvent.GetType(), HasRemoveDuplicateAttribute);
50 | }
51 | }
52 | }
--------------------------------------------------------------------------------
/GenericEventRunner/ForHandlers/Internal/FindHandlers.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
2 | // Licensed under MIT license. See License.txt in the project root for license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Runtime.CompilerServices;
8 | using System.Xml.Schema;
9 | using Microsoft.Extensions.DependencyInjection;
10 | using Microsoft.Extensions.Logging;
11 |
12 | namespace GenericEventRunner.ForHandlers.Internal
13 | {
14 | internal class FindHandlers
15 | {
16 | private readonly IServiceProvider _serviceProvider;
17 | private readonly ILogger _logger;
18 |
19 | public FindHandlers(IServiceProvider serviceProvider, ILogger logger)
20 | {
21 | _serviceProvider = serviceProvider;
22 | _logger = logger;
23 | }
24 |
25 | public List GetHandlers(EntityAndEvent entityAndEvent, BeforeDuringOrAfter beforeDuringOrAfter, bool lookForAsyncHandlers)
26 | {
27 | var eventType = entityAndEvent.EntityEvent.GetType();
28 | var asyncHandlers = new List