├── .gitattributes ├── .gitignore ├── FineCollectionService ├── Controllers │ └── CollectionController.cs ├── DomainServices │ ├── HardCodedFineCalculator.cs │ └── IFineCalculator.cs ├── FineCollectionService.csproj ├── GlobalUsings.cs ├── Helpers │ └── EmailUtils.cs ├── Models │ ├── SpeedingViolation.cs │ └── VehicleInfo.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Proxies │ └── VehicleRegistrationService.cs ├── appsettings.Development.json ├── appsettings.json └── test.http ├── Infrastructure ├── consul │ ├── start-consul.ps1 │ ├── start-consul.sh │ ├── stop-consul.ps1 │ └── stop-consul.sh ├── maildev │ ├── start-maildev.ps1 │ ├── start-maildev.sh │ ├── stop-maildev.ps1 │ └── stop-maildev.sh ├── mosquitto │ ├── Dockerfile │ ├── build-dtc-mosquitto.ps1 │ ├── build-dtc-mosquitto.sh │ ├── mosquitto.conf │ ├── start-mosquitto.ps1 │ ├── start-mosquitto.sh │ ├── stop-mosquitto.ps1 │ └── stop-mosquitto.sh ├── rabbitmq │ ├── start-rabbitmq.ps1 │ ├── start-rabbitmq.sh │ ├── stop-rabbitmq.ps1 │ └── stop-rabbitmq.sh ├── start-all.ps1 ├── start-all.sh ├── stop-all.ps1 └── stop-all.sh ├── README.md ├── Simulation ├── CameraSimulation.cs ├── Events │ └── VehicleRegistered.cs ├── GlobalUsings.cs ├── Program.cs ├── Proxies │ ├── HttpTrafficControlService.cs │ └── ITrafficControlService.cs └── Simulation.csproj ├── TrafficControlService ├── Controllers │ └── TrafficController.cs ├── DomainServices │ ├── DefaultSpeedingViolationCalculator.cs │ └── ISpeedingViolationCalculator.cs ├── Events │ └── VehicleRegistered.cs ├── GlobalUsings.cs ├── Models │ ├── SpeedingViolation.cs │ └── VehicleState.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Repositories │ ├── IVehicleStateRepository.cs │ └── InMemoryVehicleStateRepository.cs ├── TrafficControlService.csproj ├── appsettings.Development.json ├── appsettings.json └── test.http ├── VehicleRegistrationService ├── Controllers │ └── VehicleInfoController.cs ├── GlobalUsings.cs ├── Models │ └── VehicleInfo.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Repositories │ ├── IVehicleRepository.cs │ └── InMemoryVehicleInfoRepository.cs ├── VehicleRegistrationService.csproj ├── apply-load.ps1 ├── appsettings.Development.json ├── appsettings.json └── test.http ├── dapr-workshop-csharp.code-workspace ├── dapr └── config │ └── config.yaml └── global.json /.gitattributes: -------------------------------------------------------------------------------- 1 | mosquitto.conf text eol=lf -------------------------------------------------------------------------------- /.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 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | 33 | # Visual Studio 2015/2017 cache/options directory 34 | .vs/ 35 | # Uncomment if you have tasks that create the project's static files in wwwroot 36 | #wwwroot/ 37 | 38 | # Visual Studio 2017 auto generated files 39 | Generated\ Files/ 40 | 41 | # MSTest test Results 42 | [Tt]est[Rr]esult*/ 43 | [Bb]uild[Ll]og.* 44 | 45 | # NUNIT 46 | *.VisualState.xml 47 | TestResult.xml 48 | 49 | # Build Results of an ATL Project 50 | [Dd]ebugPS/ 51 | [Rr]eleasePS/ 52 | dlldata.c 53 | 54 | # Benchmark Results 55 | BenchmarkDotNet.Artifacts/ 56 | 57 | # .NET Core 58 | project.lock.json 59 | project.fragment.lock.json 60 | artifacts/ 61 | 62 | # StyleCop 63 | StyleCopReport.xml 64 | 65 | # Files built by Visual Studio 66 | *_i.c 67 | *_p.c 68 | *_h.h 69 | *.ilk 70 | *.meta 71 | *.obj 72 | *.iobj 73 | *.pch 74 | *.pdb 75 | *.ipdb 76 | *.pgc 77 | *.pgd 78 | *.rsp 79 | *.sbr 80 | *.tlb 81 | *.tli 82 | *.tlh 83 | *.tmp 84 | *.tmp_proj 85 | *_wpftmp.csproj 86 | *.log 87 | *.vspscc 88 | *.vssscc 89 | .builds 90 | *.pidb 91 | *.svclog 92 | *.scc 93 | 94 | # Chutzpah Test files 95 | _Chutzpah* 96 | 97 | # Visual C++ cache files 98 | ipch/ 99 | *.aps 100 | *.ncb 101 | *.opendb 102 | *.opensdf 103 | *.sdf 104 | *.cachefile 105 | *.VC.db 106 | *.VC.VC.opendb 107 | 108 | # Visual Studio profiler 109 | *.psess 110 | *.vsp 111 | *.vspx 112 | *.sap 113 | 114 | # Visual Studio Trace Files 115 | *.e2e 116 | 117 | # TFS 2012 Local Workspace 118 | $tf/ 119 | 120 | # Guidance Automation Toolkit 121 | *.gpState 122 | 123 | # ReSharper is a .NET coding add-in 124 | _ReSharper*/ 125 | *.[Rr]e[Ss]harper 126 | *.DotSettings.user 127 | 128 | # JustCode is a .NET coding add-in 129 | .JustCode 130 | 131 | # TeamCity is a build add-in 132 | _TeamCity* 133 | 134 | # DotCover is a Code Coverage Tool 135 | *.dotCover 136 | 137 | # AxoCover is a Code Coverage Tool 138 | .axoCover/* 139 | !.axoCover/settings.json 140 | 141 | # Visual Studio code coverage results 142 | *.coverage 143 | *.coveragexml 144 | 145 | # NCrunch 146 | _NCrunch_* 147 | .*crunch*.local.xml 148 | nCrunchTemp_* 149 | 150 | # MightyMoose 151 | *.mm.* 152 | AutoTest.Net/ 153 | 154 | # Web workbench (sass) 155 | .sass-cache/ 156 | 157 | # Installshield output folder 158 | [Ee]xpress/ 159 | 160 | # DocProject is a documentation generator add-in 161 | DocProject/buildhelp/ 162 | DocProject/Help/*.HxT 163 | DocProject/Help/*.HxC 164 | DocProject/Help/*.hhc 165 | DocProject/Help/*.hhk 166 | DocProject/Help/*.hhp 167 | DocProject/Help/Html2 168 | DocProject/Help/html 169 | 170 | # Click-Once directory 171 | publish/ 172 | 173 | # Publish Web Output 174 | *.[Pp]ublish.xml 175 | *.azurePubxml 176 | # Note: Comment the next line if you want to checkin your web deploy settings, 177 | # but database connection strings (with potential passwords) will be unencrypted 178 | *.pubxml 179 | *.publishproj 180 | 181 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 182 | # checkin your Azure Web App publish settings, but sensitive information contained 183 | # in these scripts will be unencrypted 184 | PublishScripts/ 185 | 186 | # NuGet Packages 187 | *.nupkg 188 | # The packages folder can be ignored because of Package Restore 189 | **/[Pp]ackages/* 190 | # except build/, which is used as an MSBuild target. 191 | !**/[Pp]ackages/build/ 192 | # Uncomment if necessary however generally it will be regenerated when needed 193 | #!**/[Pp]ackages/repositories.config 194 | # NuGet v3's project.json files produces more ignorable files 195 | *.nuget.props 196 | *.nuget.targets 197 | 198 | # Microsoft Azure Build Output 199 | csx/ 200 | *.build.csdef 201 | 202 | # Microsoft Azure Emulator 203 | ecf/ 204 | rcf/ 205 | 206 | # Windows Store app package directories and files 207 | AppPackages/ 208 | BundleArtifacts/ 209 | Package.StoreAssociation.xml 210 | _pkginfo.txt 211 | *.appx 212 | *.appxbundle 213 | *.appxupload 214 | 215 | # Visual Studio cache files 216 | # files ending in .cache can be ignored 217 | *.[Cc]ache 218 | # but keep track of directories ending in .cache 219 | !?*.[Cc]ache/ 220 | 221 | # Others 222 | ClientBin/ 223 | ~$* 224 | *~ 225 | *.dbmdl 226 | *.dbproj.schemaview 227 | *.jfm 228 | *.pfx 229 | *.publishsettings 230 | orleans.codegen.cs 231 | 232 | # Including strong name files can present a security risk 233 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 234 | #*.snk 235 | 236 | # Since there are multiple workflows, uncomment next line to ignore bower_components 237 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 238 | #bower_components/ 239 | 240 | # RIA/Silverlight projects 241 | Generated_Code/ 242 | 243 | # Backup & report files from converting an old project file 244 | # to a newer Visual Studio version. Backup files are not needed, 245 | # because we have git ;-) 246 | _UpgradeReport_Files/ 247 | Backup*/ 248 | UpgradeLog*.XML 249 | UpgradeLog*.htm 250 | ServiceFabricBackup/ 251 | *.rptproj.bak 252 | 253 | # SQL Server files 254 | *.mdf 255 | *.ldf 256 | *.ndf 257 | 258 | # Business Intelligence projects 259 | *.rdl.data 260 | *.bim.layout 261 | *.bim_*.settings 262 | *.rptproj.rsuser 263 | *- Backup*.rdl 264 | 265 | # Microsoft Fakes 266 | FakesAssemblies/ 267 | 268 | # GhostDoc plugin setting file 269 | *.GhostDoc.xml 270 | 271 | # Node.js Tools for Visual Studio 272 | .ntvs_analysis.dat 273 | node_modules/ 274 | 275 | # Visual Studio 6 build log 276 | *.plg 277 | 278 | # Visual Studio 6 workspace options file 279 | *.opt 280 | 281 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 282 | *.vbw 283 | 284 | # Visual Studio LightSwitch build output 285 | **/*.HTMLClient/GeneratedArtifacts 286 | **/*.DesktopClient/GeneratedArtifacts 287 | **/*.DesktopClient/ModelManifest.xml 288 | **/*.Server/GeneratedArtifacts 289 | **/*.Server/ModelManifest.xml 290 | _Pvt_Extensions 291 | 292 | # Paket dependency manager 293 | .paket/paket.exe 294 | paket-files/ 295 | 296 | # FAKE - F# Make 297 | .fake/ 298 | 299 | # CodeRush personal settings 300 | .cr/personal 301 | 302 | # Python Tools for Visual Studio (PTVS) 303 | __pycache__/ 304 | *.pyc 305 | 306 | # Cake - Uncomment if you are using it 307 | # tools/** 308 | # !tools/packages.config 309 | 310 | # Tabs Studio 311 | *.tss 312 | 313 | # Telerik's JustMock configuration file 314 | *.jmconfig 315 | 316 | # BizTalk build output 317 | *.btp.cs 318 | *.btm.cs 319 | *.odx.cs 320 | *.xsd.cs 321 | 322 | # OpenCover UI analysis results 323 | OpenCover/ 324 | 325 | # Azure Stream Analytics local run output 326 | ASALocalRun/ 327 | 328 | # MSBuild Binary and Structured Log 329 | *.binlog 330 | 331 | # NVidia Nsight GPU debugger configuration file 332 | *.nvuser 333 | 334 | # MFractors (Xamarin productivity tool) working folder 335 | .mfractor/ 336 | 337 | # Local History for Visual Studio 338 | .localhistory/ 339 | 340 | # BeatPulse healthcheck temp database 341 | healthchecksdb 342 | 343 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 344 | MigrationBackup/ 345 | 346 | ## 347 | ## Visual studio for Mac 348 | ## 349 | 350 | 351 | # globs 352 | Makefile.in 353 | *.userprefs 354 | *.usertasks 355 | config.make 356 | config.status 357 | aclocal.m4 358 | install-sh 359 | autom4te.cache/ 360 | *.tar.gz 361 | tarballs/ 362 | test-results/ 363 | 364 | # Mac bundle stuff 365 | *.dmg 366 | *.app 367 | 368 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 369 | # General 370 | .DS_Store 371 | .AppleDouble 372 | .LSOverride 373 | 374 | # Icon must end with two \r 375 | Icon 376 | 377 | 378 | # Thumbnails 379 | ._* 380 | 381 | # Files that might appear in the root of a volume 382 | .DocumentRevisions-V100 383 | .fseventsd 384 | .Spotlight-V100 385 | .TemporaryItems 386 | .Trashes 387 | .VolumeIcon.icns 388 | .com.apple.timemachine.donotpresent 389 | 390 | # Directories potentially created on remote AFP share 391 | .AppleDB 392 | .AppleDesktop 393 | Network Trash Folder 394 | Temporary Items 395 | .apdisk 396 | 397 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 398 | # Windows thumbnail cache files 399 | Thumbs.db 400 | ehthumbs.db 401 | ehthumbs_vista.db 402 | 403 | # Dump file 404 | *.stackdump 405 | 406 | # Folder config file 407 | [Dd]esktop.ini 408 | 409 | # Recycle Bin used on file shares 410 | $RECYCLE.BIN/ 411 | 412 | # Windows Installer files 413 | *.cab 414 | *.msi 415 | *.msix 416 | *.msm 417 | *.msp 418 | 419 | # Windows shortcuts 420 | *.lnk 421 | 422 | # JetBrains Rider 423 | .idea/ 424 | *.sln.iml 425 | 426 | ## 427 | ## Visual Studio Code 428 | ## 429 | .vscode/* 430 | !.vscode/settings.json 431 | !.vscode/tasks.json 432 | !.vscode/launch.json 433 | !.vscode/extensions.json 434 | 435 | # MacOS 436 | .DS_Store -------------------------------------------------------------------------------- /FineCollectionService/Controllers/CollectionController.cs: -------------------------------------------------------------------------------- 1 | namespace FineCollectionService.Controllers; 2 | 3 | [ApiController] 4 | [Route("")] 5 | public class CollectionController : ControllerBase 6 | { 7 | private static string? _fineCalculatorLicenseKey = null; 8 | private readonly ILogger _logger; 9 | private readonly IFineCalculator _fineCalculator; 10 | private readonly VehicleRegistrationService _vehicleRegistrationService; 11 | 12 | public CollectionController(IConfiguration config, ILogger logger, 13 | IFineCalculator fineCalculator, VehicleRegistrationService vehicleRegistrationService) 14 | { 15 | _logger = logger; 16 | _fineCalculator = fineCalculator; 17 | _vehicleRegistrationService = vehicleRegistrationService; 18 | 19 | // set finecalculator component license-key 20 | if (_fineCalculatorLicenseKey == null) 21 | { 22 | _fineCalculatorLicenseKey = config.GetValue("fineCalculatorLicenseKey"); 23 | } 24 | } 25 | 26 | [Route("collectfine")] 27 | [HttpPost()] 28 | public async Task CollectFine(SpeedingViolation speedingViolation) 29 | { 30 | decimal fine = _fineCalculator.CalculateFine(_fineCalculatorLicenseKey!, speedingViolation.ViolationInKmh); 31 | 32 | // get owner info 33 | var vehicleInfo = await _vehicleRegistrationService.GetVehicleInfo(speedingViolation.VehicleId); 34 | 35 | // log fine 36 | string fineString = fine == 0 ? "tbd by the prosecutor" : $"{fine} Euro"; 37 | _logger.LogInformation($"Sent speeding ticket to {vehicleInfo.OwnerName}. " + 38 | $"Road: {speedingViolation.RoadId}, Licensenumber: {speedingViolation.VehicleId}, " + 39 | $"Vehicle: {vehicleInfo.Brand} {vehicleInfo.Model}, " + 40 | $"Violation: {speedingViolation.ViolationInKmh} Km/h, Fine: {fineString}, " + 41 | $"On: {speedingViolation.Timestamp.ToString("dd-MM-yyyy")} " + 42 | $"at {speedingViolation.Timestamp.ToString("hh:mm:ss")}."); 43 | 44 | // send fine by email 45 | // TODO 46 | 47 | return Ok(); 48 | } 49 | } -------------------------------------------------------------------------------- /FineCollectionService/DomainServices/HardCodedFineCalculator.cs: -------------------------------------------------------------------------------- 1 | namespace FineCollectionService.DomainServices; 2 | 3 | public class HardCodedFineCalculator : IFineCalculator 4 | { 5 | public int CalculateFine(string licenseKey, int violationInKmh) 6 | { 7 | if (licenseKey != "HX783-K2L7V-CRJ4A-5PN1G") 8 | { 9 | throw new InvalidOperationException("Invalid license-key specified."); 10 | } 11 | 12 | int fine = 9; // default administration fee 13 | if (violationInKmh < 5) 14 | { 15 | fine += 18; 16 | } 17 | else if (violationInKmh >= 5 && violationInKmh < 10) 18 | { 19 | fine += 31; 20 | } 21 | else if (violationInKmh >= 10 && violationInKmh < 15) 22 | { 23 | fine += 64; 24 | } 25 | else if (violationInKmh >= 15 && violationInKmh < 20) 26 | { 27 | fine += 121; 28 | } 29 | else if (violationInKmh >= 20 && violationInKmh < 25) 30 | { 31 | fine += 174; 32 | } 33 | else if (violationInKmh >= 25 && violationInKmh < 30) 34 | { 35 | fine += 232; 36 | } 37 | else if (violationInKmh >= 25 && violationInKmh < 35) 38 | { 39 | fine += 297; 40 | } 41 | else if (violationInKmh == 35) 42 | { 43 | fine += 372; 44 | } 45 | else 46 | { 47 | // violation above 35 KMh will be determined by the prosecutor 48 | return 0; 49 | } 50 | 51 | return fine; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /FineCollectionService/DomainServices/IFineCalculator.cs: -------------------------------------------------------------------------------- 1 | namespace FineCollectionService.DomainServices; 2 | 3 | public interface IFineCalculator 4 | { 5 | public int CalculateFine(string licenseKey, int violationInKmh); 6 | } 7 | -------------------------------------------------------------------------------- /FineCollectionService/FineCollectionService.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | 12 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /FineCollectionService/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using FineCollectionService.DomainServices; 2 | global using FineCollectionService.Helpers; 3 | global using FineCollectionService.Models; 4 | global using FineCollectionService.Proxies; 5 | global using Microsoft.AspNetCore.Mvc; 6 | -------------------------------------------------------------------------------- /FineCollectionService/Helpers/EmailUtils.cs: -------------------------------------------------------------------------------- 1 | namespace FineCollectionService.Helpers; 2 | 3 | public class EmailUtils 4 | { 5 | public static string CreateEmailBody( 6 | SpeedingViolation speedingViolation, 7 | VehicleInfo vehicleInfo, 8 | string fine) 9 | { 10 | return $@" 11 | 12 | 13 | 62 | 63 | 64 | 67 |
68 |

Central Fine Collection Agency

69 |
 
70 |
71 |

The Hague, {DateTime.Now.ToLongDateString()}

72 | 73 |

Dear Mr. / Miss / Mrs. {vehicleInfo.OwnerName},

74 | 75 |

We hereby inform you of the fact that a speeding violation was detected with a 76 | vehicle that is registered to you.

77 | 78 |

The violation was detected by a speeding camera. We have a digital image of your 79 | vehicle committing the violation on record in our system. If requested by your 80 | solicitor, we will provide this image to you.

81 | 82 |
83 | 84 |

Below you can find all the details of the violation.

85 | 86 |

87 | Vehicle information: 88 | 89 | 90 | 91 | 92 |
License number{vehicleInfo.VehicleId}
Brand{vehicleInfo.Brand}
Model{vehicleInfo.Model}
93 |

94 | 95 |

96 | Conditions during the violation: 97 | 98 | 99 | 100 | 101 |
Road{speedingViolation.RoadId}
Date{speedingViolation.Timestamp.ToString("dd-MM-yyyy")}
Time of day{speedingViolation.Timestamp.ToString("hh:mm:ss")}
102 |

103 | 104 |

105 | Sanction: 106 | 107 | 108 | 109 |
Maximum speed violation{speedingViolation.ViolationInKmh} KMh
Sanction amount
{fine}
110 |

111 | 112 |
113 | 114 |

Sanction handling:

115 | 116 |

If the amount of the fine is to be determined by the prosecutor, you will receive a notice 117 | to appear in court shortly.

118 | 119 |

Otherwise, you must pay the sanctioned fine within 8 weeks after the date of this 120 | email. If you fail to pay within 8 weeks, you will receive a first reminder email and the 121 | fine will be increased to 1.5x the original fine amount. If you fail to pay within 8 weeks 122 | after the first reminder, you will receive a second and last reminder email and the fine 123 | will be increased to 3x the original fine amount. If you fail to pay within 8 weeks 124 | after the second reminder, the case is turned over to the prosecutor and you will receive a 125 | notice to appear in court.

126 | 127 |
128 | 129 |

130 | Yours sincerely,
131 | The Central Fine Collection Agency 132 |

133 | 134 | 135 | "; 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /FineCollectionService/Models/SpeedingViolation.cs: -------------------------------------------------------------------------------- 1 | namespace FineCollectionService.Models; 2 | 3 | public record struct SpeedingViolation(string VehicleId, string RoadId, int ViolationInKmh, DateTime Timestamp); 4 | -------------------------------------------------------------------------------- /FineCollectionService/Models/VehicleInfo.cs: -------------------------------------------------------------------------------- 1 | namespace FineCollectionService.Models; 2 | 3 | public record struct VehicleInfo(string VehicleId, string Brand, string Model, string OwnerName, string OwnerEmail); -------------------------------------------------------------------------------- /FineCollectionService/Program.cs: -------------------------------------------------------------------------------- 1 | // create web-app 2 | var builder = WebApplication.CreateBuilder(args); 3 | 4 | builder.Services.AddSingleton(); 5 | 6 | builder.Services.AddHttpClient(); 7 | builder.Services.AddSingleton(); 8 | 9 | builder.Services.AddControllers(); 10 | 11 | var app = builder.Build(); 12 | 13 | // configure web-app 14 | if (app.Environment.IsDevelopment()) 15 | { 16 | app.UseDeveloperExceptionPage(); 17 | } 18 | 19 | // configure routing 20 | app.MapControllers(); 21 | 22 | // let's go! 23 | app.Run("http://localhost:6001"); 24 | -------------------------------------------------------------------------------- /FineCollectionService/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:24157", 8 | "sslPort": 44335 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "FineCollectionService": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "https://localhost:6001;http://localhost:6000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /FineCollectionService/Proxies/VehicleRegistrationService.cs: -------------------------------------------------------------------------------- 1 | namespace FineCollectionService.Proxies; 2 | 3 | public class VehicleRegistrationService 4 | { 5 | private HttpClient _httpClient; 6 | 7 | public VehicleRegistrationService(HttpClient httpClient) 8 | { 9 | _httpClient = httpClient; 10 | } 11 | 12 | public async Task GetVehicleInfo(string licenseNumber) 13 | { 14 | return await _httpClient.GetFromJsonAsync( 15 | $"http://localhost:6002/vehicleinfo/{licenseNumber}"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /FineCollectionService/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /FineCollectionService/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*", 10 | "fineCalculatorLicenseKey": "HX783-K2L7V-CRJ4A-5PN1G" 11 | } 12 | -------------------------------------------------------------------------------- /FineCollectionService/test.http: -------------------------------------------------------------------------------- 1 | 2 | // Publish speeding violation 3 | POST http://127.0.0.1:6001/collectfine 4 | Content-Type: application/json 5 | 6 | { "vehicleId": "RT-318-K", "roadId": "A12", "violationInKmh": 15, "timestamp": "2020-09-20T08:33:41" } 7 | -------------------------------------------------------------------------------- /Infrastructure/consul/start-consul.ps1: -------------------------------------------------------------------------------- 1 | docker run -d -p 8500:8500 -p 8600:8600/udp --name dtc-consul consul:1.15 agent -dev -client '0.0.0.0' 2 | -------------------------------------------------------------------------------- /Infrastructure/consul/start-consul.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | docker run -d -p 8500:8500 -p 8600:8600/udp --name dtc-consul consul:1.15 agent -dev -client '0.0.0.0' 4 | 5 | -------------------------------------------------------------------------------- /Infrastructure/consul/stop-consul.ps1: -------------------------------------------------------------------------------- 1 | docker rm dtc-consul -f -------------------------------------------------------------------------------- /Infrastructure/consul/stop-consul.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | docker rm dtc-consul -f -------------------------------------------------------------------------------- /Infrastructure/maildev/start-maildev.ps1: -------------------------------------------------------------------------------- 1 | docker run -d -p 4000:1080 -p 4025:1025 --name dtc-maildev maildev/maildev:2.0.5 2 | -------------------------------------------------------------------------------- /Infrastructure/maildev/start-maildev.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | docker run -d -p 4000:1080 -p 4025:1025 --name dtc-maildev maildev/maildev:2.0.5 5 | -------------------------------------------------------------------------------- /Infrastructure/maildev/stop-maildev.ps1: -------------------------------------------------------------------------------- 1 | docker rm dtc-maildev -f -------------------------------------------------------------------------------- /Infrastructure/maildev/stop-maildev.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | docker rm dtc-maildev -f 5 | -------------------------------------------------------------------------------- /Infrastructure/mosquitto/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM eclipse-mosquitto:2.0.11 2 | 3 | COPY ./mosquitto.conf /mosquitto/config/mosquitto.conf 4 | -------------------------------------------------------------------------------- /Infrastructure/mosquitto/build-dtc-mosquitto.ps1: -------------------------------------------------------------------------------- 1 | docker build -t dapr-trafficcontrol/mosquitto:1.0 . -------------------------------------------------------------------------------- /Infrastructure/mosquitto/build-dtc-mosquitto.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | docker build -t dapr-trafficcontrol/mosquitto:1.0 . -------------------------------------------------------------------------------- /Infrastructure/mosquitto/mosquitto.conf: -------------------------------------------------------------------------------- 1 | listener 1883 2 | protocol mqtt 3 | 4 | listener 9001 5 | protocol websockets 6 | 7 | allow_anonymous true 8 | -------------------------------------------------------------------------------- /Infrastructure/mosquitto/start-mosquitto.ps1: -------------------------------------------------------------------------------- 1 | # First we build a custom Mosquitto docker image (based on the official eclipse image) that 2 | # contains the custom configuration file we need for Dapr traffic-control (see mosquitto.conf). 3 | 4 | docker build -t dapr-trafficcontrol/mosquitto:1.0 . 5 | docker run -d -p 1883:1883 -p 9001:9001 --name dtc-mosquitto dapr-trafficcontrol/mosquitto:1.0 6 | -------------------------------------------------------------------------------- /Infrastructure/mosquitto/start-mosquitto.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | # First we build a custom Mosquitto docker image (based on the official eclipse image) that 5 | # contains the custom configuration file we need for Dapr traffic-control (see mosquitto.conf). 6 | 7 | docker build -t dapr-trafficcontrol/mosquitto:1.0 . 8 | docker run -d -p 1883:1883 -p 9001:9001 --name dtc-mosquitto dapr-trafficcontrol/mosquitto:1.0 -------------------------------------------------------------------------------- /Infrastructure/mosquitto/stop-mosquitto.ps1: -------------------------------------------------------------------------------- 1 | docker rm dtc-mosquitto -f -------------------------------------------------------------------------------- /Infrastructure/mosquitto/stop-mosquitto.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | docker rm dtc-mosquitto -f 5 | -------------------------------------------------------------------------------- /Infrastructure/rabbitmq/start-rabbitmq.ps1: -------------------------------------------------------------------------------- 1 | docker run -d -p 5672:5672 -p 15672:15672 --name dtc-rabbitmq rabbitmq:3-management-alpine 2 | -------------------------------------------------------------------------------- /Infrastructure/rabbitmq/start-rabbitmq.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | docker run -d -p 5672:5672 -p 15672:15672 --name dtc-rabbitmq rabbitmq:3-management-alpine 5 | -------------------------------------------------------------------------------- /Infrastructure/rabbitmq/stop-rabbitmq.ps1: -------------------------------------------------------------------------------- 1 | docker rm dtc-rabbitmq -f -------------------------------------------------------------------------------- /Infrastructure/rabbitmq/stop-rabbitmq.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | docker rm dtc-rabbitmq -f 5 | -------------------------------------------------------------------------------- /Infrastructure/start-all.ps1: -------------------------------------------------------------------------------- 1 | Push-Location -Path consul 2 | & ./start-consul.ps1 3 | Pop-Location 4 | 5 | Push-Location -Path mosquitto 6 | & ./start-mosquitto.ps1 7 | Pop-Location 8 | 9 | Push-Location -Path rabbitmq 10 | & ./start-rabbitmq.ps1 11 | Pop-Location 12 | 13 | Push-Location -Path maildev 14 | & ./start-maildev.ps1 15 | Pop-Location -------------------------------------------------------------------------------- /Infrastructure/start-all.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | basedir=$(dirname $0) 4 | 5 | pushd consul 6 | ./start-consul.sh 7 | popd 8 | 9 | pushd ${basedir}/rabbitmq 10 | ./start-rabbitmq.sh 11 | popd 12 | 13 | pushd ${basedir}/mosquitto 14 | ./start-mosquitto.sh 15 | popd 16 | 17 | pushd ${basedir}/maildev 18 | ./start-maildev.sh 19 | popd 20 | 21 | -------------------------------------------------------------------------------- /Infrastructure/stop-all.ps1: -------------------------------------------------------------------------------- 1 | & ./mosquitto/stop-mosquitto.ps1 2 | & ./rabbitmq/stop-rabbitmq.ps1 3 | & ./maildev/stop-maildev.ps1 4 | & ./consul/stop-consul.ps1 5 | -------------------------------------------------------------------------------- /Infrastructure/stop-all.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | basedir=$(dirname $0) 5 | 6 | pushd ${basedir}/rabbitmq 7 | ./stop-rabbitmq.sh 8 | popd 9 | 10 | pushd ${basedir}/mosquitto 11 | ./stop-mosquitto.sh 12 | popd 13 | 14 | pushd ${basedir}/maildev 15 | ./stop-maildev.sh 16 | popd 17 | 18 | pushd consul 19 | ./stop-consul.sh 20 | popd 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Dapr workshop .NET 2 | 3 | The Dapr workshop is a workshop that teaches you how to apply [Dapr](https://dapr.io) to a microservices application. This repository contains the source-code that forms the starting point of the C# (.NET) version of the workshop. With each workshop assignment you will expand the application with a Dapr building block. 4 | 5 | See the [Dapr workshop repository](https://github.com/edwinvw/dapr-workshop) for more information and instructions on how to get started. 6 | -------------------------------------------------------------------------------- /Simulation/CameraSimulation.cs: -------------------------------------------------------------------------------- 1 | namespace Simulation; 2 | 3 | public class CameraSimulation 4 | { 5 | private readonly ITrafficControlService _trafficControlService; 6 | private Random _rnd; 7 | private int _camNumber; 8 | private int _minEntryDelayInMS = 50; 9 | private int _maxEntryDelayInMS = 5000; 10 | private int _minExitDelayInS = 4; 11 | private int _maxExitDelayInS = 10; 12 | 13 | public CameraSimulation(int camNumber, ITrafficControlService trafficControlService) 14 | { 15 | _rnd = new Random(); 16 | _camNumber = camNumber; 17 | _trafficControlService = trafficControlService; 18 | } 19 | 20 | public Task Start() 21 | { 22 | Console.WriteLine($"Start camera {_camNumber} simulation."); 23 | 24 | while (true) 25 | { 26 | try 27 | { 28 | // simulate entry 29 | TimeSpan entryDelay = TimeSpan.FromMilliseconds(_rnd.Next(_minEntryDelayInMS, _maxEntryDelayInMS) + _rnd.NextDouble()); 30 | Task.Delay(entryDelay).Wait(); 31 | 32 | Task.Run(async () => 33 | { 34 | // simulate entry 35 | DateTime entryTimestamp = DateTime.Now; 36 | var vehicleRegistered = new VehicleRegistered 37 | { 38 | Lane = _camNumber, 39 | LicenseNumber = GenerateRandomLicenseNumber(), 40 | Timestamp = entryTimestamp 41 | }; 42 | await _trafficControlService.SendVehicleEntryAsync(vehicleRegistered); 43 | Console.WriteLine($"Simulated ENTRY of vehicle with license-number {vehicleRegistered.LicenseNumber} in lane {vehicleRegistered.Lane}"); 44 | 45 | 46 | // simulate exit 47 | TimeSpan exitDelay = TimeSpan.FromSeconds(_rnd.Next(_minExitDelayInS, _maxExitDelayInS) + _rnd.NextDouble()); 48 | Task.Delay(exitDelay).Wait(); 49 | vehicleRegistered.Timestamp = DateTime.Now; 50 | vehicleRegistered.Lane = _rnd.Next(1, 4); 51 | await _trafficControlService.SendVehicleExitAsync(vehicleRegistered); 52 | Console.WriteLine($"Simulated EXIT of vehicle with license-number {vehicleRegistered.LicenseNumber} in lane {vehicleRegistered.Lane}"); 53 | }).Wait(); 54 | } 55 | catch (Exception ex) 56 | { 57 | Console.WriteLine($"Camera {_camNumber} error: {ex.Message}"); 58 | } 59 | } 60 | } 61 | 62 | #region Private helper methods 63 | 64 | private string _validLicenseNumberChars = "DFGHJKLNPRSTXYZ"; 65 | 66 | private string GenerateRandomLicenseNumber() 67 | { 68 | int type = _rnd.Next(1, 9); 69 | string kenteken = string.Empty; 70 | switch (type) 71 | { 72 | case 1: // 99-AA-99 73 | kenteken = string.Format("{0:00}-{1}-{2:00}", _rnd.Next(1, 99), GenerateRandomCharacters(2), _rnd.Next(1, 99)); 74 | break; 75 | case 2: // AA-99-AA 76 | kenteken = string.Format("{0}-{1:00}-{2}", GenerateRandomCharacters(2), _rnd.Next(1, 99), GenerateRandomCharacters(2)); 77 | break; 78 | case 3: // AA-AA-99 79 | kenteken = string.Format("{0}-{1}-{2:00}", GenerateRandomCharacters(2), GenerateRandomCharacters(2), _rnd.Next(1, 99)); 80 | break; 81 | case 4: // 99-AA-AA 82 | kenteken = string.Format("{0:00}-{1}-{2}", _rnd.Next(1, 99), GenerateRandomCharacters(2), GenerateRandomCharacters(2)); 83 | break; 84 | case 5: // 99-AAA-9 85 | kenteken = string.Format("{0:00}-{1}-{2}", _rnd.Next(1, 99), GenerateRandomCharacters(3), _rnd.Next(1, 10)); 86 | break; 87 | case 6: // 9-AAA-99 88 | kenteken = string.Format("{0}-{1}-{2:00}", _rnd.Next(1, 9), GenerateRandomCharacters(3), _rnd.Next(1, 10)); 89 | break; 90 | case 7: // AA-999-A 91 | kenteken = string.Format("{0}-{1:000}-{2}", GenerateRandomCharacters(2), _rnd.Next(1, 999), GenerateRandomCharacters(1)); 92 | break; 93 | case 8: // A-999-AA 94 | kenteken = string.Format("{0}-{1:000}-{2}", GenerateRandomCharacters(1), _rnd.Next(1, 999), GenerateRandomCharacters(2)); 95 | break; 96 | } 97 | 98 | return kenteken; 99 | } 100 | 101 | private string GenerateRandomCharacters(int aantal) 102 | { 103 | char[] chars = new char[aantal]; 104 | for (int i = 0; i < aantal; i++) 105 | { 106 | chars[i] = _validLicenseNumberChars[_rnd.Next(_validLicenseNumberChars.Length - 1)]; 107 | } 108 | return new string(chars); 109 | } 110 | 111 | #endregion 112 | } 113 | -------------------------------------------------------------------------------- /Simulation/Events/VehicleRegistered.cs: -------------------------------------------------------------------------------- 1 | namespace Simulation.Events; 2 | 3 | public record struct VehicleRegistered(int Lane, string LicenseNumber, DateTime Timestamp); 4 | -------------------------------------------------------------------------------- /Simulation/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using System.Text.Json; 2 | global using System.Net.Http.Json; 3 | global using Simulation.Proxies; 4 | global using Simulation.Events; 5 | global using Simulation; 6 | -------------------------------------------------------------------------------- /Simulation/Program.cs: -------------------------------------------------------------------------------- 1 | int lanes = 3; 2 | CameraSimulation[] cameras = new CameraSimulation[lanes]; 3 | var httpClient = new HttpClient(); 4 | for (var i = 0; i < lanes; i++) 5 | { 6 | int camNumber = i + 1; 7 | var trafficControlService = new HttpTrafficControlService(httpClient); 8 | cameras[i] = new CameraSimulation(camNumber, trafficControlService); 9 | } 10 | Parallel.ForEach(cameras, cam => cam.Start()); 11 | 12 | Task.Run(() => Thread.Sleep(Timeout.Infinite)).Wait(); -------------------------------------------------------------------------------- /Simulation/Proxies/HttpTrafficControlService.cs: -------------------------------------------------------------------------------- 1 | namespace Simulation.Proxies; 2 | 3 | public class HttpTrafficControlService : ITrafficControlService 4 | { 5 | private HttpClient _httpClient; 6 | 7 | public HttpTrafficControlService(HttpClient httpClient) 8 | { 9 | _httpClient = httpClient; 10 | } 11 | 12 | public async Task SendVehicleEntryAsync(VehicleRegistered vehicleRegistered) 13 | { 14 | var eventJson = JsonSerializer.Serialize(vehicleRegistered); 15 | var message = JsonContent.Create(vehicleRegistered); 16 | await _httpClient.PostAsync("http://localhost:6000/entrycam", message); 17 | } 18 | 19 | public async Task SendVehicleExitAsync(VehicleRegistered vehicleRegistered) 20 | { 21 | var eventJson = JsonSerializer.Serialize(vehicleRegistered); 22 | var message = JsonContent.Create(vehicleRegistered); 23 | await _httpClient.PostAsync("http://localhost:6000/exitcam", message); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Simulation/Proxies/ITrafficControlService.cs: -------------------------------------------------------------------------------- 1 | namespace Simulation.Proxies; 2 | 3 | public interface ITrafficControlService 4 | { 5 | public Task SendVehicleEntryAsync(VehicleRegistered vehicleRegistered); 6 | public Task SendVehicleExitAsync(VehicleRegistered vehicleRegistered); 7 | } 8 | -------------------------------------------------------------------------------- /Simulation/Simulation.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | 12 7 | enable 8 | enable 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /TrafficControlService/Controllers/TrafficController.cs: -------------------------------------------------------------------------------- 1 | namespace TrafficControlService.Controllers; 2 | 3 | [ApiController] 4 | [Route("")] 5 | public class TrafficController : ControllerBase 6 | { 7 | private readonly HttpClient _httpClient; 8 | private readonly IVehicleStateRepository _vehicleStateRepository; 9 | private readonly ILogger _logger; 10 | private readonly ISpeedingViolationCalculator _speedingViolationCalculator; 11 | private readonly string _roadId; 12 | 13 | public TrafficController( 14 | ILogger logger, 15 | HttpClient httpClient, 16 | IVehicleStateRepository vehicleStateRepository, 17 | ISpeedingViolationCalculator speedingViolationCalculator) 18 | { 19 | _logger = logger; 20 | _httpClient = httpClient; 21 | _vehicleStateRepository = vehicleStateRepository; 22 | _speedingViolationCalculator = speedingViolationCalculator; 23 | _roadId = speedingViolationCalculator.GetRoadId(); 24 | } 25 | 26 | [HttpPost("entrycam")] 27 | public async Task VehicleEntry(VehicleRegistered msg) 28 | { 29 | try 30 | { 31 | // log entry 32 | _logger.LogInformation($"ENTRY detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")} " + 33 | $"of vehicle with license-number {msg.LicenseNumber}."); 34 | 35 | // store vehicle state 36 | var vehicleState = new VehicleState 37 | { 38 | LicenseNumber = msg.LicenseNumber, 39 | EntryTimestamp = msg.Timestamp 40 | }; 41 | await _vehicleStateRepository.SaveVehicleStateAsync(vehicleState); 42 | 43 | return Ok(); 44 | } 45 | catch 46 | { 47 | return StatusCode(500); 48 | } 49 | } 50 | 51 | [HttpPost("exitcam")] 52 | public async Task VehicleExit(VehicleRegistered msg) 53 | { 54 | try 55 | { 56 | // get vehicle state 57 | var vehicleState = await _vehicleStateRepository.GetVehicleStateAsync(msg.LicenseNumber); 58 | if (!vehicleState.HasValue) 59 | { 60 | return NotFound(); 61 | } 62 | 63 | // log exit 64 | _logger.LogInformation($"EXIT detected in lane {msg.Lane} at {msg.Timestamp.ToString("hh:mm:ss")} " + 65 | $"of vehicle with license-number {msg.LicenseNumber}."); 66 | 67 | // update state 68 | vehicleState = vehicleState.Value with { ExitTimestamp = msg.Timestamp }; 69 | await _vehicleStateRepository.SaveVehicleStateAsync(vehicleState.Value); 70 | 71 | // handle possible speeding violation 72 | int violation = _speedingViolationCalculator.DetermineSpeedingViolationInKmh( 73 | vehicleState.Value.EntryTimestamp, vehicleState.Value.ExitTimestamp.Value); 74 | if (violation > 0) 75 | { 76 | _logger.LogInformation($"Speeding violation detected ({violation} KMh) of vehicle" + 77 | $"with license-number {vehicleState.Value.LicenseNumber}."); 78 | 79 | var speedingViolation = new SpeedingViolation 80 | { 81 | VehicleId = msg.LicenseNumber, 82 | RoadId = _roadId, 83 | ViolationInKmh = violation, 84 | Timestamp = msg.Timestamp 85 | }; 86 | 87 | // publish speedingviolation 88 | var message = JsonContent.Create(speedingViolation); 89 | await _httpClient.PostAsync("http://localhost:6001/collectfine", message); 90 | } 91 | 92 | return Ok(); 93 | } 94 | catch 95 | { 96 | return StatusCode(500); 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /TrafficControlService/DomainServices/DefaultSpeedingViolationCalculator.cs: -------------------------------------------------------------------------------- 1 | namespace TrafficControlService.DomainServices; 2 | 3 | public class DefaultSpeedingViolationCalculator : ISpeedingViolationCalculator 4 | { 5 | private readonly string _roadId; 6 | private readonly int _sectionLengthInKm; 7 | private readonly int _maxAllowedSpeedInKmh; 8 | private readonly int _legalCorrectionInKmh; 9 | 10 | public DefaultSpeedingViolationCalculator(string roadId, int sectionLengthInKm, int maxAllowedSpeedInKmh, int legalCorrectionInKmh) 11 | { 12 | _roadId = roadId; 13 | _sectionLengthInKm = sectionLengthInKm; 14 | _maxAllowedSpeedInKmh = maxAllowedSpeedInKmh; 15 | _legalCorrectionInKmh = legalCorrectionInKmh; 16 | } 17 | 18 | public int DetermineSpeedingViolationInKmh(DateTime entryTimestamp, DateTime exitTimestamp) 19 | { 20 | double elapsedMinutes = exitTimestamp.Subtract(entryTimestamp).TotalSeconds; // 1 sec. == 1 min. in simulation 21 | double avgSpeedInKmh = Math.Round((_sectionLengthInKm / elapsedMinutes) * 60); 22 | int violation = Convert.ToInt32(avgSpeedInKmh - _maxAllowedSpeedInKmh - _legalCorrectionInKmh); 23 | return violation; 24 | } 25 | 26 | public string GetRoadId() 27 | { 28 | return _roadId; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /TrafficControlService/DomainServices/ISpeedingViolationCalculator.cs: -------------------------------------------------------------------------------- 1 | namespace TrafficControlService.DomainServices; 2 | 3 | public interface ISpeedingViolationCalculator 4 | { 5 | int DetermineSpeedingViolationInKmh(DateTime entryTimestamp, DateTime exitTimestamp); 6 | string GetRoadId(); 7 | } 8 | -------------------------------------------------------------------------------- /TrafficControlService/Events/VehicleRegistered.cs: -------------------------------------------------------------------------------- 1 | namespace TrafficControlService.Events; 2 | 3 | public record struct VehicleRegistered(int Lane, string LicenseNumber, DateTime Timestamp); -------------------------------------------------------------------------------- /TrafficControlService/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using TrafficControlService.DomainServices; 2 | global using TrafficControlService.Repositories; 3 | global using TrafficControlService.Models; 4 | global using TrafficControlService.Events; 5 | global using Microsoft.AspNetCore.Mvc; 6 | global using System.Collections.Concurrent; -------------------------------------------------------------------------------- /TrafficControlService/Models/SpeedingViolation.cs: -------------------------------------------------------------------------------- 1 | namespace TrafficControlService.Models; 2 | 3 | public record struct SpeedingViolation(string VehicleId, string RoadId, int ViolationInKmh, DateTime Timestamp); -------------------------------------------------------------------------------- /TrafficControlService/Models/VehicleState.cs: -------------------------------------------------------------------------------- 1 | namespace TrafficControlService.Models; 2 | 3 | public record struct VehicleState 4 | { 5 | public string LicenseNumber { get; init; } 6 | public DateTime EntryTimestamp { get; init; } 7 | public DateTime? ExitTimestamp { get; set; } 8 | 9 | public VehicleState(string licenseNumber, DateTime entryTimestamp, DateTime? exitTimestamp = null) 10 | { 11 | this.LicenseNumber = licenseNumber; 12 | this.EntryTimestamp = entryTimestamp; 13 | this.ExitTimestamp = exitTimestamp; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /TrafficControlService/Program.cs: -------------------------------------------------------------------------------- 1 | // create web-app 2 | var builder = WebApplication.CreateBuilder(args); 3 | 4 | builder.Services.AddSingleton( 5 | new DefaultSpeedingViolationCalculator("A12", 10, 100, 5)); 6 | builder.Services.AddHttpClient(); 7 | builder.Services.AddSingleton(); 8 | builder.Services.AddControllers(); 9 | 10 | var app = builder.Build(); 11 | 12 | // configure web-app 13 | if (app.Environment.IsDevelopment()) 14 | { 15 | app.UseDeveloperExceptionPage(); 16 | } 17 | 18 | // configure routing 19 | app.MapControllers(); 20 | 21 | // let's go! 22 | app.Run("http://localhost:6000"); 23 | -------------------------------------------------------------------------------- /TrafficControlService/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:56156", 8 | "sslPort": 44374 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "TrafficControlService": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "https://localhost:6001;http://localhost:6000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /TrafficControlService/Repositories/IVehicleStateRepository.cs: -------------------------------------------------------------------------------- 1 | namespace TrafficControlService.Repositories; 2 | 3 | public interface IVehicleStateRepository 4 | { 5 | Task SaveVehicleStateAsync(VehicleState vehicleState); 6 | Task GetVehicleStateAsync(string licenseNumber); 7 | } 8 | -------------------------------------------------------------------------------- /TrafficControlService/Repositories/InMemoryVehicleStateRepository.cs: -------------------------------------------------------------------------------- 1 | namespace TrafficControlService.Repositories; 2 | 3 | public class InMemoryVehicleStateRepository : IVehicleStateRepository 4 | { 5 | private readonly ConcurrentDictionary _state; 6 | 7 | public InMemoryVehicleStateRepository() 8 | { 9 | _state = new ConcurrentDictionary(); 10 | } 11 | public Task GetVehicleStateAsync(string licenseNumber) 12 | { 13 | VehicleState state; 14 | if (!_state.TryGetValue(licenseNumber, out state)) 15 | { 16 | return Task.FromResult(null); 17 | } 18 | return Task.FromResult(state); 19 | } 20 | 21 | public Task SaveVehicleStateAsync(VehicleState vehicleState) 22 | { 23 | _state.AddOrUpdate(vehicleState.LicenseNumber, vehicleState, 24 | (k, s) => vehicleState); 25 | return Task.CompletedTask; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /TrafficControlService/TrafficControlService.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | 12 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /TrafficControlService/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /TrafficControlService/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } -------------------------------------------------------------------------------- /TrafficControlService/test.http: -------------------------------------------------------------------------------- 1 | // Register entry 2 | POST http://127.0.0.1:6000/entrycam 3 | Content-Type: application/json 4 | 5 | { "lane": 1, "licenseNumber": "XT-346-Y", "timestamp": "2020-09-10T10:38:47" } 6 | 7 | ### 8 | 9 | // Register exit 10 | POST http://127.0.0.1:6000/exitcam 11 | Content-Type: application/json 12 | 13 | { "lane": 1, "licenseNumber": "XT-346-Y", "timestamp": "2020-09-10T10:38:52" } 14 | -------------------------------------------------------------------------------- /VehicleRegistrationService/Controllers/VehicleInfoController.cs: -------------------------------------------------------------------------------- 1 | namespace VehicleRegistrationService.Controllers; 2 | 3 | [ApiController] 4 | [Route("[controller]")] 5 | public class VehicleInfoController : ControllerBase 6 | { 7 | private readonly ILogger _logger; 8 | private readonly IVehicleInfoRepository _vehicleInfoRepository; 9 | 10 | public VehicleInfoController(ILogger logger, IVehicleInfoRepository vehicleInfoRepository) 11 | { 12 | _logger = logger; 13 | _vehicleInfoRepository = vehicleInfoRepository; 14 | } 15 | 16 | [HttpGet("{licenseNumber}")] 17 | public ActionResult GetVehicleInfo(string licenseNumber) 18 | { 19 | _logger.LogInformation($"Retrieving vehicle-info for licensenumber {licenseNumber}"); 20 | VehicleInfo info = _vehicleInfoRepository.GetVehicleInfo(licenseNumber); 21 | return info; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /VehicleRegistrationService/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Microsoft.AspNetCore.Mvc; 2 | global using VehicleRegistrationService.Models; 3 | global using VehicleRegistrationService.Repositories; 4 | global using RandomNameGeneratorLibrary; -------------------------------------------------------------------------------- /VehicleRegistrationService/Models/VehicleInfo.cs: -------------------------------------------------------------------------------- 1 | namespace VehicleRegistrationService.Models; 2 | 3 | public record struct VehicleInfo(string VehicleId, string Brand, string Model, string OwnerName, string OwnerEmail); -------------------------------------------------------------------------------- /VehicleRegistrationService/Program.cs: -------------------------------------------------------------------------------- 1 | // create web-app 2 | var builder = WebApplication.CreateBuilder(args); 3 | 4 | builder.Services.AddScoped(); 5 | 6 | builder.Services.AddControllers(); 7 | 8 | var app = builder.Build(); 9 | 10 | // configure web-app 11 | if (app.Environment.IsDevelopment()) 12 | { 13 | app.UseDeveloperExceptionPage(); 14 | } 15 | 16 | // configure routing 17 | app.MapControllers(); 18 | 19 | // let's go! 20 | app.Run("http://localhost:6002"); 21 | -------------------------------------------------------------------------------- /VehicleRegistrationService/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:24157", 8 | "sslPort": 44335 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "FineCollectionService": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "https://localhost:6002;http://localhost:6002", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /VehicleRegistrationService/Repositories/IVehicleRepository.cs: -------------------------------------------------------------------------------- 1 | namespace VehicleRegistrationService.Repositories; 2 | 3 | public interface IVehicleInfoRepository 4 | { 5 | VehicleInfo GetVehicleInfo(string licenseNumber); 6 | } 7 | -------------------------------------------------------------------------------- /VehicleRegistrationService/Repositories/InMemoryVehicleInfoRepository.cs: -------------------------------------------------------------------------------- 1 | namespace VehicleRegistrationService.Repositories; 2 | 3 | public class InMemoryVehicleInfoRepository : IVehicleInfoRepository 4 | { 5 | private Random _rnd; 6 | 7 | private PersonNameGenerator _nameGenerator; 8 | 9 | private readonly string[] _vehicleBrands = new string[] { 10 | "Mercedes", "Toyota", "Audi", "Volkswagen", "Seat", "Renault", "Skoda", 11 | "Kia", "Citroën", "Suzuki", "Mitsubishi", "Fiat", "Opel" }; 12 | 13 | private Dictionary _models = new Dictionary 14 | { 15 | { "Mercedes", new string[] { "A Class", "B Class", "C Class", "E Class", "SLS", "SLK" } }, 16 | { "Toyota", new string[] { "Yaris", "Avensis", "Rav 4", "Prius", "Celica" } }, 17 | { "Audi", new string[] { "A3", "A4", "A6", "A8", "Q5", "Q7" } }, 18 | { "Volkswagen", new string[] { "Golf", "Pasat", "Tiguan", "Caddy" } }, 19 | { "Seat", new string[] { "Leon", "Arona", "Ibiza", "Alhambra" } }, 20 | { "Renault", new string[] { "Megane", "Clio", "Twingo", "Scenic", "Captur" } }, 21 | { "Skoda", new string[] { "Octavia", "Fabia", "Superb", "Karoq", "Kodiaq" } }, 22 | { "Kia", new string[] { "Picanto", "Rio", "Ceed", "XCeed", "Niro", "Sportage" } }, 23 | { "Citroën", new string[] { "C1", "C2", "C3", "C4", "C4 Cactus", "Berlingo" } }, 24 | { "Suzuki", new string[] { "Ignis", "Swift", "Vitara", "S-Cross", "Swace", "Jimny" } }, 25 | { "Mitsubishi", new string[] { "Space Star", "ASX", "Eclipse Cross", "Outlander PHEV" } }, 26 | { "Ford", new string[] { "Focus", "Ka", "C-Max", "Fusion", "Fiesta", "Mondeo", "Kuga" } }, 27 | { "BMW", new string[] { "1 Serie", "2 Serie", "3 Serie", "5 Serie", "7 Serie", "X5" } }, 28 | { "Fiat", new string[] { "500", "Panda", "Punto", "Tipo", "Multipla" } }, 29 | { "Opel", new string[] { "Karl", "Corsa", "Astra", "Crossland X", "Insignia" } } 30 | }; 31 | 32 | public InMemoryVehicleInfoRepository() 33 | { 34 | _rnd = new Random(); 35 | _nameGenerator = new PersonNameGenerator(_rnd); 36 | } 37 | 38 | public VehicleInfo GetVehicleInfo(string licenseNumber) 39 | { 40 | // simulate slow IO 41 | Thread.Sleep(_rnd.Next(5, 200)); 42 | 43 | // get random vehicle info 44 | string brand = GetRandomBrand(); 45 | string model = GetRandomModel(brand); 46 | 47 | // get random owner info 48 | var ownerName = _nameGenerator.GenerateRandomFirstAndLastName(); 49 | var ownerEmail = $"{ownerName.ToLowerInvariant().Replace(' ', '.')}@outlook.com"; 50 | 51 | // return info 52 | return new VehicleInfo 53 | { 54 | VehicleId = licenseNumber, 55 | Brand = brand, 56 | Model = model, 57 | OwnerName = ownerName, 58 | OwnerEmail = ownerEmail 59 | }; 60 | } 61 | 62 | private string GetRandomBrand() 63 | { 64 | return _vehicleBrands[_rnd.Next(_vehicleBrands.Length)]; 65 | } 66 | 67 | private string GetRandomModel(string brand) 68 | { 69 | string[] models = _models[brand]; 70 | return models[_rnd.Next(models.Length)]; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /VehicleRegistrationService/VehicleRegistrationService.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | 12 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /VehicleRegistrationService/apply-load.ps1: -------------------------------------------------------------------------------- 1 | # This script uses Apache Bench to simulate concurrent load. 2 | # Download the Windows zip for apache (from https://www.apachelounge.com/download/) 3 | # and extract ab.exe from the zip file. 4 | 5 | ab -k -l -d -S ` 6 | -c 10 ` 7 | -n 100 ` 8 | http://localhost:3602/v1.0/invoke/vehicleregistrationservice/method/rdw/vehicle/21-KTG-4 9 | -------------------------------------------------------------------------------- /VehicleRegistrationService/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /VehicleRegistrationService/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /VehicleRegistrationService/test.http: -------------------------------------------------------------------------------- 1 | // Get vehicle info by license-number 2 | GET http://127.0.0.1:6002/vehicleinfo/KZ-49-VX 3 | -------------------------------------------------------------------------------- /dapr-workshop-csharp.code-workspace: -------------------------------------------------------------------------------- 1 | { 2 | "folders": [ 3 | { 4 | "path": "FineCollectionService" 5 | }, 6 | { 7 | "path": "Infrastructure" 8 | }, 9 | { 10 | "path": "Simulation" 11 | }, 12 | { 13 | "path": "TrafficControlService" 14 | }, 15 | { 16 | "path": "VehicleRegistrationService" 17 | } 18 | ], 19 | "settings": {} 20 | } -------------------------------------------------------------------------------- /dapr/config/config.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: dapr.io/v1alpha1 2 | kind: Configuration 3 | metadata: 4 | name: daprConfig 5 | spec: 6 | tracing: 7 | samplingRate: "1" 8 | zipkin: 9 | endpointAddress: "http://localhost:9411/api/v2/spans" 10 | nameResolution: 11 | component: "consul" 12 | configuration: 13 | selfRegister: true -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "8.0.0", 4 | "rollForward": "latestMinor" 5 | } 6 | } --------------------------------------------------------------------------------