├── .gitignore ├── LICENSE ├── README.md ├── SLIDES-CSharpChannels.pdf ├── digit-display ├── .gitignore ├── .vs │ └── DigitDisplay │ │ ├── DesignTimeBuild │ │ └── .dtbcache.v2 │ │ ├── project-colors.json │ │ ├── v16 │ │ └── .suo │ │ └── v17 │ │ ├── .futdcache.v1 │ │ └── .suo ├── Data │ └── train.csv ├── DigitDisplay.sln ├── digit-console │ ├── Configuration.cs │ ├── Display.cs │ ├── Program.cs │ └── digit-console.csproj ├── digit-display │ ├── App.xaml │ ├── App.xaml.cs │ ├── AssemblyInfo.cs │ ├── DetailControl.xaml │ ├── DetailControl.xaml.cs │ ├── DigitBitmap.cs │ ├── Globals.cs │ ├── ImageHelper.cs │ ├── MainWindow.xaml │ ├── MainWindow.xaml.cs │ ├── NonParallelRecognizerControl.cs │ ├── ParallelAwaitRecognizerControl.cs │ ├── ParallelChannelRecognizerControl.cs │ ├── ParallelForEachAsyncRecognizerControl.cs │ ├── ParallelTaskRecognizerControl.cs │ ├── RecognizerControl.xaml │ ├── RecognizerControl.xaml.cs │ └── digit-display.csproj └── recognizer │ ├── EuclideanClassifier.cs │ ├── K5EuclideanClassifier.cs │ ├── Loader.cs │ ├── ManhattanClassifier.cs │ ├── Predictions.cs │ ├── Recognize.cs │ └── recognizer.csproj └── people-demo ├── .vs ├── ChannelsDemo │ ├── DesignTimeBuild │ │ └── .dtbcache.v2 │ ├── config │ │ └── applicationhost.config │ ├── project-colors.json │ ├── v16 │ │ └── .suo │ └── v17 │ │ ├── .futdcache.v1 │ │ ├── .futdcache.v2 │ │ └── .suo └── ProjectEvaluation │ ├── channelsdemo.metadata.v2 │ ├── channelsdemo.metadata.v5.2 │ ├── channelsdemo.metadata.v6.1 │ ├── channelsdemo.metadata.v7.bin │ ├── channelsdemo.projects.v2 │ ├── channelsdemo.projects.v5.2 │ ├── channelsdemo.projects.v6.1 │ └── channelsdemo.projects.v7.bin ├── ChannelsDemo.sln ├── People.Service ├── Data │ ├── HardCodedPeopleProvider.cs │ ├── IPeopleProvider.cs │ └── Person.cs ├── Global.cs ├── People.Service.csproj ├── Program.cs ├── Properties │ └── launchSettings.json ├── appsettings.Development.json └── appsettings.json └── PeopleViewer ├── LocalExtensions.cs ├── PeopleViewer.csproj ├── PersonReader.cs └── Program.cs /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from `dotnet new gitignore` 5 | 6 | # dotenv files 7 | .env 8 | 9 | # User-specific files 10 | *.rsuser 11 | *.suo 12 | *.user 13 | *.userosscache 14 | *.sln.docstates 15 | 16 | # User-specific files (MonoDevelop/Xamarin Studio) 17 | *.userprefs 18 | 19 | # Mono auto generated files 20 | mono_crash.* 21 | 22 | # Build results 23 | [Dd]ebug/ 24 | [Dd]ebugPublic/ 25 | [Rr]elease/ 26 | [Rr]eleases/ 27 | x64/ 28 | x86/ 29 | [Ww][Ii][Nn]32/ 30 | [Aa][Rr][Mm]/ 31 | [Aa][Rr][Mm]64/ 32 | bld/ 33 | [Bb]in/ 34 | [Oo]bj/ 35 | [Ll]og/ 36 | [Ll]ogs/ 37 | 38 | # Visual Studio 2015/2017 cache/options directory 39 | .vs/ 40 | # Uncomment if you have tasks that create the project's static files in wwwroot 41 | #wwwroot/ 42 | 43 | # Visual Studio 2017 auto generated files 44 | Generated\ Files/ 45 | 46 | # MSTest test Results 47 | [Tt]est[Rr]esult*/ 48 | [Bb]uild[Ll]og.* 49 | 50 | # NUnit 51 | *.VisualState.xml 52 | TestResult.xml 53 | nunit-*.xml 54 | 55 | # Build Results of an ATL Project 56 | [Dd]ebugPS/ 57 | [Rr]eleasePS/ 58 | dlldata.c 59 | 60 | # Benchmark Results 61 | BenchmarkDotNet.Artifacts/ 62 | 63 | # .NET 64 | project.lock.json 65 | project.fragment.lock.json 66 | artifacts/ 67 | 68 | # Tye 69 | .tye/ 70 | 71 | # ASP.NET Scaffolding 72 | ScaffoldingReadMe.txt 73 | 74 | # StyleCop 75 | StyleCopReport.xml 76 | 77 | # Files built by Visual Studio 78 | *_i.c 79 | *_p.c 80 | *_h.h 81 | *.ilk 82 | *.meta 83 | *.obj 84 | *.iobj 85 | *.pch 86 | *.pdb 87 | *.ipdb 88 | *.pgc 89 | *.pgd 90 | *.rsp 91 | *.sbr 92 | *.tlb 93 | *.tli 94 | *.tlh 95 | *.tmp 96 | *.tmp_proj 97 | *_wpftmp.csproj 98 | *.log 99 | *.tlog 100 | *.vspscc 101 | *.vssscc 102 | .builds 103 | *.pidb 104 | *.svclog 105 | *.scc 106 | 107 | # Chutzpah Test files 108 | _Chutzpah* 109 | 110 | # Visual C++ cache files 111 | ipch/ 112 | *.aps 113 | *.ncb 114 | *.opendb 115 | *.opensdf 116 | *.sdf 117 | *.cachefile 118 | *.VC.db 119 | *.VC.VC.opendb 120 | 121 | # Visual Studio profiler 122 | *.psess 123 | *.vsp 124 | *.vspx 125 | *.sap 126 | 127 | # Visual Studio Trace Files 128 | *.e2e 129 | 130 | # TFS 2012 Local Workspace 131 | $tf/ 132 | 133 | # Guidance Automation Toolkit 134 | *.gpState 135 | 136 | # ReSharper is a .NET coding add-in 137 | _ReSharper*/ 138 | *.[Rr]e[Ss]harper 139 | *.DotSettings.user 140 | 141 | # TeamCity is a build add-in 142 | _TeamCity* 143 | 144 | # DotCover is a Code Coverage Tool 145 | *.dotCover 146 | 147 | # AxoCover is a Code Coverage Tool 148 | .axoCover/* 149 | !.axoCover/settings.json 150 | 151 | # Coverlet is a free, cross platform Code Coverage Tool 152 | coverage*.json 153 | coverage*.xml 154 | coverage*.info 155 | 156 | # Visual Studio code coverage results 157 | *.coverage 158 | *.coveragexml 159 | 160 | # NCrunch 161 | _NCrunch_* 162 | .*crunch*.local.xml 163 | nCrunchTemp_* 164 | 165 | # MightyMoose 166 | *.mm.* 167 | AutoTest.Net/ 168 | 169 | # Web workbench (sass) 170 | .sass-cache/ 171 | 172 | # Installshield output folder 173 | [Ee]xpress/ 174 | 175 | # DocProject is a documentation generator add-in 176 | DocProject/buildhelp/ 177 | DocProject/Help/*.HxT 178 | DocProject/Help/*.HxC 179 | DocProject/Help/*.hhc 180 | DocProject/Help/*.hhk 181 | DocProject/Help/*.hhp 182 | DocProject/Help/Html2 183 | DocProject/Help/html 184 | 185 | # Click-Once directory 186 | publish/ 187 | 188 | # Publish Web Output 189 | *.[Pp]ublish.xml 190 | *.azurePubxml 191 | # Note: Comment the next line if you want to checkin your web deploy settings, 192 | # but database connection strings (with potential passwords) will be unencrypted 193 | *.pubxml 194 | *.publishproj 195 | 196 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 197 | # checkin your Azure Web App publish settings, but sensitive information contained 198 | # in these scripts will be unencrypted 199 | PublishScripts/ 200 | 201 | # NuGet Packages 202 | *.nupkg 203 | # NuGet Symbol Packages 204 | *.snupkg 205 | # The packages folder can be ignored because of Package Restore 206 | **/[Pp]ackages/* 207 | # except build/, which is used as an MSBuild target. 208 | !**/[Pp]ackages/build/ 209 | # Uncomment if necessary however generally it will be regenerated when needed 210 | #!**/[Pp]ackages/repositories.config 211 | # NuGet v3's project.json files produces more ignorable files 212 | *.nuget.props 213 | *.nuget.targets 214 | 215 | # Microsoft Azure Build Output 216 | csx/ 217 | *.build.csdef 218 | 219 | # Microsoft Azure Emulator 220 | ecf/ 221 | rcf/ 222 | 223 | # Windows Store app package directories and files 224 | AppPackages/ 225 | BundleArtifacts/ 226 | Package.StoreAssociation.xml 227 | _pkginfo.txt 228 | *.appx 229 | *.appxbundle 230 | *.appxupload 231 | 232 | # Visual Studio cache files 233 | # files ending in .cache can be ignored 234 | *.[Cc]ache 235 | # but keep track of directories ending in .cache 236 | !?*.[Cc]ache/ 237 | 238 | # Others 239 | ClientBin/ 240 | ~$* 241 | *~ 242 | *.dbmdl 243 | *.dbproj.schemaview 244 | *.jfm 245 | *.pfx 246 | *.publishsettings 247 | orleans.codegen.cs 248 | 249 | # Including strong name files can present a security risk 250 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 251 | #*.snk 252 | 253 | # Since there are multiple workflows, uncomment next line to ignore bower_components 254 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 255 | #bower_components/ 256 | 257 | # RIA/Silverlight projects 258 | Generated_Code/ 259 | 260 | # Backup & report files from converting an old project file 261 | # to a newer Visual Studio version. Backup files are not needed, 262 | # because we have git ;-) 263 | _UpgradeReport_Files/ 264 | Backup*/ 265 | UpgradeLog*.XML 266 | UpgradeLog*.htm 267 | ServiceFabricBackup/ 268 | *.rptproj.bak 269 | 270 | # SQL Server files 271 | *.mdf 272 | *.ldf 273 | *.ndf 274 | 275 | # Business Intelligence projects 276 | *.rdl.data 277 | *.bim.layout 278 | *.bim_*.settings 279 | *.rptproj.rsuser 280 | *- [Bb]ackup.rdl 281 | *- [Bb]ackup ([0-9]).rdl 282 | *- [Bb]ackup ([0-9][0-9]).rdl 283 | 284 | # Microsoft Fakes 285 | FakesAssemblies/ 286 | 287 | # GhostDoc plugin setting file 288 | *.GhostDoc.xml 289 | 290 | # Node.js Tools for Visual Studio 291 | .ntvs_analysis.dat 292 | node_modules/ 293 | 294 | # Visual Studio 6 build log 295 | *.plg 296 | 297 | # Visual Studio 6 workspace options file 298 | *.opt 299 | 300 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 301 | *.vbw 302 | 303 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 304 | *.vbp 305 | 306 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 307 | *.dsw 308 | *.dsp 309 | 310 | # Visual Studio 6 technical files 311 | *.ncb 312 | *.aps 313 | 314 | # Visual Studio LightSwitch build output 315 | **/*.HTMLClient/GeneratedArtifacts 316 | **/*.DesktopClient/GeneratedArtifacts 317 | **/*.DesktopClient/ModelManifest.xml 318 | **/*.Server/GeneratedArtifacts 319 | **/*.Server/ModelManifest.xml 320 | _Pvt_Extensions 321 | 322 | # Paket dependency manager 323 | .paket/paket.exe 324 | paket-files/ 325 | 326 | # FAKE - F# Make 327 | .fake/ 328 | 329 | # CodeRush personal settings 330 | .cr/personal 331 | 332 | # Python Tools for Visual Studio (PTVS) 333 | __pycache__/ 334 | *.pyc 335 | 336 | # Cake - Uncomment if you are using it 337 | # tools/** 338 | # !tools/packages.config 339 | 340 | # Tabs Studio 341 | *.tss 342 | 343 | # Telerik's JustMock configuration file 344 | *.jmconfig 345 | 346 | # BizTalk build output 347 | *.btp.cs 348 | *.btm.cs 349 | *.odx.cs 350 | *.xsd.cs 351 | 352 | # OpenCover UI analysis results 353 | OpenCover/ 354 | 355 | # Azure Stream Analytics local run output 356 | ASALocalRun/ 357 | 358 | # MSBuild Binary and Structured Log 359 | *.binlog 360 | 361 | # NVidia Nsight GPU debugger configuration file 362 | *.nvuser 363 | 364 | # MFractors (Xamarin productivity tool) working folder 365 | .mfractor/ 366 | 367 | # Local History for Visual Studio 368 | .localhistory/ 369 | 370 | # Visual Studio History (VSHistory) files 371 | .vshistory/ 372 | 373 | # BeatPulse healthcheck temp database 374 | healthchecksdb 375 | 376 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 377 | MigrationBackup/ 378 | 379 | # Ionide (cross platform F# VS Code tools) working folder 380 | .ionide/ 381 | 382 | # Fody - auto-generated XML schema 383 | FodyWeavers.xsd 384 | 385 | # VS Code files for those working on multiple tools 386 | .vscode/* 387 | !.vscode/settings.json 388 | !.vscode/tasks.json 389 | !.vscode/launch.json 390 | !.vscode/extensions.json 391 | *.code-workspace 392 | 393 | # Local History for Visual Studio Code 394 | .history/ 395 | 396 | # Windows Installer files from build outputs 397 | *.cab 398 | *.msi 399 | *.msix 400 | *.msm 401 | *.msp 402 | 403 | # JetBrains Rider 404 | *.sln.iml 405 | .idea 406 | 407 | ## 408 | ## Visual studio for Mac 409 | ## 410 | 411 | 412 | # globs 413 | Makefile.in 414 | *.userprefs 415 | *.usertasks 416 | config.make 417 | config.status 418 | aclocal.m4 419 | install-sh 420 | autom4te.cache/ 421 | *.tar.gz 422 | tarballs/ 423 | test-results/ 424 | 425 | # Mac bundle stuff 426 | *.dmg 427 | *.app 428 | 429 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 430 | # General 431 | .DS_Store 432 | .AppleDouble 433 | .LSOverride 434 | 435 | # Icon must end with two \r 436 | Icon 437 | 438 | 439 | # Thumbnails 440 | ._* 441 | 442 | # Files that might appear in the root of a volume 443 | .DocumentRevisions-V100 444 | .fseventsd 445 | .Spotlight-V100 446 | .TemporaryItems 447 | .Trashes 448 | .VolumeIcon.icns 449 | .com.apple.timemachine.donotpresent 450 | 451 | # Directories potentially created on remote AFP share 452 | .AppleDB 453 | .AppleDesktop 454 | Network Trash Folder 455 | Temporary Items 456 | .apdisk 457 | 458 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 459 | # Windows thumbnail cache files 460 | Thumbs.db 461 | ehthumbs.db 462 | ehthumbs_vista.db 463 | 464 | # Dump file 465 | *.stackdump 466 | 467 | # Folder config file 468 | [Dd]esktop.ini 469 | 470 | # Recycle Bin used on file shares 471 | $RECYCLE.BIN/ 472 | 473 | # Windows Installer files 474 | *.cab 475 | *.msi 476 | *.msix 477 | *.msm 478 | *.msp 479 | 480 | # Windows shortcuts 481 | *.lnk 482 | 483 | # Vim temporary swap files 484 | *.swp 485 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Jeremy Clark 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Better Parallel Code with C# Channels 2 | 3 | ## Abstract 4 | Producer/consumer problems show up in a lot of programming scenarios, including data processing and machine learning. Channels were added to .NET Core 3.0 and give us a thread-safe way to communicate between producers and consumers, and we can run them all concurrently. In this presentation, we will explore channels by comparing parallel tasks with continuations to using a producer/consumer model. In the end, we'll have another tool in our toolbox to help us with concurrent programming. 5 | 6 | Recorded Presentation: [Using Channels in C# to Enhance Concurrent Code](https://www.youtube.com/watch?v=YxDORrTvIGM) - Dot Net North (May 2021) 7 | 8 | ## Project Layout 9 | To build and run the code, you will need to have .NET 8 installed on your machine. The demo project will run wherever .NET 8 will run (Windows, macOS, Linux). 10 | 11 | **/people-demo/PeopleViewer** contains a console application that uses channels program 12 | **/people-demo/People.Service** contains a service (used by the console application) 13 | 14 | The "PeopleViewer" program is a console application that calls the service and displays the output. In order to show concurrency, the application gets each record individually. 15 | 16 | ## Development Environments 17 | **Visual Studio 2022** 18 | The "ChannelsDemo.sln" contains both of the projects listed above. The solution is set to automatically start both the service and the console application. So, hit "F5" to start the application & service. 19 | 20 | **Visual Studio Code** 21 | In Visual Studio Code, you will want to start the service separately from the command line (see "Running the Service"). You can leave the service running while working with the console application. 22 | 23 | ## Running the Service 24 | The **.NET service** can be started from the command line by navigating to the ".../people-demo/People.Service" directory and typing `dotnet run`. This provides endpoints at the following locations: 25 | 26 | * http://localhost:9874/people 27 | Provides a list of "Person" objects. This service will delay for 3 seconds before responding. Sample result: 28 | 29 | ```json 30 | [{"id":1,"givenName":"John","familyName":"Koenig","startDate":"1975-10-17T00:00:00-07:00","rating":6,"formatString":null}, 31 | {"id":2,"givenName":"Dylan","familyName":"Hunt","startDate":"2000-10-02T00:00:00-07:00","rating":8,"formatString":null}, 32 | {...}] 33 | ``` 34 | 35 | * http://localhost:9874/people/ids 36 | Provides a list of "id" values for the collection. Sample: 37 | 38 | ```json 39 | [1,2,3,4,5,6,7,8,9] 40 | ``` 41 | 42 | * http://localhost:9874/people/1 43 | Provides an individual "Person" record based on the "id" value. This service will delay for 1 second before responding. Sample record: 44 | 45 | ```json 46 | {"id":1,"givenName":"John","familyName":"Koenig","startDate":"1975-10-17T00:00:00-07:00","rating":6,"formatString":null} 47 | ``` 48 | 49 | The Console Application 50 | --------------------- 51 | The **/people-demo/PeopleViewer** folder contains a console application that uses channels. The relevant code is in the "Program.cs" file. 52 | 53 | ## Additional Sample 54 | The "digit-display" folder contains an additional code sample. This application is a naive machine learning project that uses concurrent operations and channels. The version included here has a Windows-only user interface. 55 | 56 | For more additional information on this project (as well as a set of console applications that run cross-platform), visit the the main repository for the "digit-display" project: 57 | 58 | [Github: jeremybytes/digit-display](https://github.com/jeremybytes/digit-display) 59 | 60 | 61 | ## Resources 62 | * Recorded Presentation: [Using Channels in C# to Enhance Concurrent Code](https://www.youtube.com/watch?v=YxDORrTvIGM) - Dot Net North (May 2021) 63 | * [An Introduction to Channels in C#](https://jeremybytes.blogspot.com/2021/02/an-introduction-to-channels-in-c.html) - Jeremy Clark 64 | * [What's the Difference between Channel and ConcurrentQueue in C#](https://jeremybytes.blogspot.com/2021/02/whats-difference-between-channel-and.html) - Jeremy Clark 65 | * [An Introduction to System.Threading.Channels](https://devblogs.microsoft.com/dotnet/an-introduction-to-system-threading-channels/) - Stephen Toub 66 | * [Channel<T> Class](https://docs.microsoft.com/en-us/dotnet/api/system.threading.channels.channel-1?view=net-5.0) - Microsoft Docs 67 | 68 | ## Additional Repositories 69 | * [Channel Exceptions](https://github.com/jeremybytes/channel-exceptions) 70 | Samples that explore exception handling for producers and consumers in parallel code. 71 | * [I'll Get Back to You: Task, Await, and Asynchronous Methods in C#](https://github.com/jeremybytes/using-task-core3) 72 | Presentation resources for understanding Task & await. Includes slides, code, videos, and articles 73 | * [Understanding Asynchronous Programming in C# - Virtual Training](https://github.com/jeremybytes/understanding-async-programming) 74 | Virtual training resources for understanding Task, await, and parallel programming. Includes slides, code samples, and articles 75 | * [Workshop: Asynchronous and Parallel Programming in C#](https://github.com/jeremybytes/async-workshop-2024) 76 | Workshop resources for understanding Task, await, and parallel programming (including self-guided, hands-on labs). Includes slides, code samples, labs, and articles 77 | -------------------------------------------------------------------------------- /SLIDES-CSharpChannels.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremybytes/csharp-channels-presentation/40f41376fc25224120c9697c30ca01bf84c9f0dd/SLIDES-CSharpChannels.pdf -------------------------------------------------------------------------------- /digit-display/.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 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # Tye 66 | .tye/ 67 | 68 | # ASP.NET Scaffolding 69 | ScaffoldingReadMe.txt 70 | 71 | # StyleCop 72 | StyleCopReport.xml 73 | 74 | # Files built by Visual Studio 75 | *_i.c 76 | *_p.c 77 | *_h.h 78 | *.ilk 79 | *.meta 80 | *.obj 81 | *.iobj 82 | *.pch 83 | *.pdb 84 | *.ipdb 85 | *.pgc 86 | *.pgd 87 | *.rsp 88 | *.sbr 89 | *.tlb 90 | *.tli 91 | *.tlh 92 | *.tmp 93 | *.tmp_proj 94 | *_wpftmp.csproj 95 | *.log 96 | *.vspscc 97 | *.vssscc 98 | .builds 99 | *.pidb 100 | *.svclog 101 | *.scc 102 | 103 | # Chutzpah Test files 104 | _Chutzpah* 105 | 106 | # Visual C++ cache files 107 | ipch/ 108 | *.aps 109 | *.ncb 110 | *.opendb 111 | *.opensdf 112 | *.sdf 113 | *.cachefile 114 | *.VC.db 115 | *.VC.VC.opendb 116 | 117 | # Visual Studio profiler 118 | *.psess 119 | *.vsp 120 | *.vspx 121 | *.sap 122 | 123 | # Visual Studio Trace Files 124 | *.e2e 125 | 126 | # TFS 2012 Local Workspace 127 | $tf/ 128 | 129 | # Guidance Automation Toolkit 130 | *.gpState 131 | 132 | # ReSharper is a .NET coding add-in 133 | _ReSharper*/ 134 | *.[Rr]e[Ss]harper 135 | *.DotSettings.user 136 | 137 | # TeamCity is a build add-in 138 | _TeamCity* 139 | 140 | # DotCover is a Code Coverage Tool 141 | *.dotCover 142 | 143 | # AxoCover is a Code Coverage Tool 144 | .axoCover/* 145 | !.axoCover/settings.json 146 | 147 | # Coverlet is a free, cross platform Code Coverage Tool 148 | coverage*.json 149 | coverage*.xml 150 | coverage*.info 151 | 152 | # Visual Studio code coverage results 153 | *.coverage 154 | *.coveragexml 155 | 156 | # NCrunch 157 | _NCrunch_* 158 | .*crunch*.local.xml 159 | nCrunchTemp_* 160 | 161 | # MightyMoose 162 | *.mm.* 163 | AutoTest.Net/ 164 | 165 | # Web workbench (sass) 166 | .sass-cache/ 167 | 168 | # Installshield output folder 169 | [Ee]xpress/ 170 | 171 | # DocProject is a documentation generator add-in 172 | DocProject/buildhelp/ 173 | DocProject/Help/*.HxT 174 | DocProject/Help/*.HxC 175 | DocProject/Help/*.hhc 176 | DocProject/Help/*.hhk 177 | DocProject/Help/*.hhp 178 | DocProject/Help/Html2 179 | DocProject/Help/html 180 | 181 | # Click-Once directory 182 | publish/ 183 | 184 | # Publish Web Output 185 | *.[Pp]ublish.xml 186 | *.azurePubxml 187 | # Note: Comment the next line if you want to checkin your web deploy settings, 188 | # but database connection strings (with potential passwords) will be unencrypted 189 | *.pubxml 190 | *.publishproj 191 | 192 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 193 | # checkin your Azure Web App publish settings, but sensitive information contained 194 | # in these scripts will be unencrypted 195 | PublishScripts/ 196 | 197 | # NuGet Packages 198 | *.nupkg 199 | # NuGet Symbol Packages 200 | *.snupkg 201 | # The packages folder can be ignored because of Package Restore 202 | **/[Pp]ackages/* 203 | # except build/, which is used as an MSBuild target. 204 | !**/[Pp]ackages/build/ 205 | # Uncomment if necessary however generally it will be regenerated when needed 206 | #!**/[Pp]ackages/repositories.config 207 | # NuGet v3's project.json files produces more ignorable files 208 | *.nuget.props 209 | *.nuget.targets 210 | 211 | # Microsoft Azure Build Output 212 | csx/ 213 | *.build.csdef 214 | 215 | # Microsoft Azure Emulator 216 | ecf/ 217 | rcf/ 218 | 219 | # Windows Store app package directories and files 220 | AppPackages/ 221 | BundleArtifacts/ 222 | Package.StoreAssociation.xml 223 | _pkginfo.txt 224 | *.appx 225 | *.appxbundle 226 | *.appxupload 227 | 228 | # Visual Studio cache files 229 | # files ending in .cache can be ignored 230 | *.[Cc]ache 231 | # but keep track of directories ending in .cache 232 | !?*.[Cc]ache/ 233 | 234 | # Others 235 | ClientBin/ 236 | ~$* 237 | *~ 238 | *.dbmdl 239 | *.dbproj.schemaview 240 | *.jfm 241 | *.pfx 242 | *.publishsettings 243 | orleans.codegen.cs 244 | 245 | # Including strong name files can present a security risk 246 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 247 | #*.snk 248 | 249 | # Since there are multiple workflows, uncomment next line to ignore bower_components 250 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 251 | #bower_components/ 252 | 253 | # RIA/Silverlight projects 254 | Generated_Code/ 255 | 256 | # Backup & report files from converting an old project file 257 | # to a newer Visual Studio version. Backup files are not needed, 258 | # because we have git ;-) 259 | _UpgradeReport_Files/ 260 | Backup*/ 261 | UpgradeLog*.XML 262 | UpgradeLog*.htm 263 | ServiceFabricBackup/ 264 | *.rptproj.bak 265 | 266 | # SQL Server files 267 | *.mdf 268 | *.ldf 269 | *.ndf 270 | 271 | # Business Intelligence projects 272 | *.rdl.data 273 | *.bim.layout 274 | *.bim_*.settings 275 | *.rptproj.rsuser 276 | *- [Bb]ackup.rdl 277 | *- [Bb]ackup ([0-9]).rdl 278 | *- [Bb]ackup ([0-9][0-9]).rdl 279 | 280 | # Microsoft Fakes 281 | FakesAssemblies/ 282 | 283 | # GhostDoc plugin setting file 284 | *.GhostDoc.xml 285 | 286 | # Node.js Tools for Visual Studio 287 | .ntvs_analysis.dat 288 | node_modules/ 289 | 290 | # Visual Studio 6 build log 291 | *.plg 292 | 293 | # Visual Studio 6 workspace options file 294 | *.opt 295 | 296 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 297 | *.vbw 298 | 299 | # Visual Studio LightSwitch build output 300 | **/*.HTMLClient/GeneratedArtifacts 301 | **/*.DesktopClient/GeneratedArtifacts 302 | **/*.DesktopClient/ModelManifest.xml 303 | **/*.Server/GeneratedArtifacts 304 | **/*.Server/ModelManifest.xml 305 | _Pvt_Extensions 306 | 307 | # Paket dependency manager 308 | .paket/paket.exe 309 | paket-files/ 310 | 311 | # FAKE - F# Make 312 | .fake/ 313 | 314 | # CodeRush personal settings 315 | .cr/personal 316 | 317 | # Python Tools for Visual Studio (PTVS) 318 | __pycache__/ 319 | *.pyc 320 | 321 | # Cake - Uncomment if you are using it 322 | # tools/** 323 | # !tools/packages.config 324 | 325 | # Tabs Studio 326 | *.tss 327 | 328 | # Telerik's JustMock configuration file 329 | *.jmconfig 330 | 331 | # BizTalk build output 332 | *.btp.cs 333 | *.btm.cs 334 | *.odx.cs 335 | *.xsd.cs 336 | 337 | # OpenCover UI analysis results 338 | OpenCover/ 339 | 340 | # Azure Stream Analytics local run output 341 | ASALocalRun/ 342 | 343 | # MSBuild Binary and Structured Log 344 | *.binlog 345 | 346 | # NVidia Nsight GPU debugger configuration file 347 | *.nvuser 348 | 349 | # MFractors (Xamarin productivity tool) working folder 350 | .mfractor/ 351 | 352 | # Local History for Visual Studio 353 | .localhistory/ 354 | 355 | # BeatPulse healthcheck temp database 356 | healthchecksdb 357 | 358 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 359 | MigrationBackup/ 360 | 361 | # Ionide (cross platform F# VS Code tools) working folder 362 | .ionide/ 363 | 364 | # Fody - auto-generated XML schema 365 | FodyWeavers.xsd 366 | 367 | ## 368 | ## Visual studio for Mac 369 | ## 370 | 371 | 372 | # globs 373 | Makefile.in 374 | *.userprefs 375 | *.usertasks 376 | config.make 377 | config.status 378 | aclocal.m4 379 | install-sh 380 | autom4te.cache/ 381 | *.tar.gz 382 | tarballs/ 383 | test-results/ 384 | 385 | # Mac bundle stuff 386 | *.dmg 387 | *.app 388 | 389 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 390 | # General 391 | .DS_Store 392 | .AppleDouble 393 | .LSOverride 394 | 395 | # Icon must end with two \r 396 | Icon 397 | 398 | 399 | # Thumbnails 400 | ._* 401 | 402 | # Files that might appear in the root of a volume 403 | .DocumentRevisions-V100 404 | .fseventsd 405 | .Spotlight-V100 406 | .TemporaryItems 407 | .Trashes 408 | .VolumeIcon.icns 409 | .com.apple.timemachine.donotpresent 410 | 411 | # Directories potentially created on remote AFP share 412 | .AppleDB 413 | .AppleDesktop 414 | Network Trash Folder 415 | Temporary Items 416 | .apdisk 417 | 418 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 419 | # Windows thumbnail cache files 420 | Thumbs.db 421 | ehthumbs.db 422 | ehthumbs_vista.db 423 | 424 | # Dump file 425 | *.stackdump 426 | 427 | # Folder config file 428 | [Dd]esktop.ini 429 | 430 | # Recycle Bin used on file shares 431 | $RECYCLE.BIN/ 432 | 433 | # Windows Installer files 434 | *.cab 435 | *.msi 436 | *.msix 437 | *.msm 438 | *.msp 439 | 440 | # Windows shortcuts 441 | *.lnk 442 | 443 | # JetBrains Rider 444 | .idea/ 445 | *.sln.iml 446 | 447 | ## 448 | ## Visual Studio Code 449 | ## 450 | .vscode/* 451 | !.vscode/settings.json 452 | !.vscode/tasks.json 453 | !.vscode/launch.json 454 | !.vscode/extensions.json 455 | -------------------------------------------------------------------------------- /digit-display/.vs/DigitDisplay/DesignTimeBuild/.dtbcache.v2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremybytes/csharp-channels-presentation/40f41376fc25224120c9697c30ca01bf84c9f0dd/digit-display/.vs/DigitDisplay/DesignTimeBuild/.dtbcache.v2 -------------------------------------------------------------------------------- /digit-display/.vs/DigitDisplay/project-colors.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": 1, 3 | "ProjectMap": { 4 | "ac8b6f47-0dee-47b2-ac39-7ff591b92b1b": { 5 | "ProjectGuid": "ac8b6f47-0dee-47b2-ac39-7ff591b92b1b", 6 | "DisplayName": "digit-display", 7 | "ColorIndex": 0 8 | }, 9 | "b378c036-3fb5-4147-9f45-d9648da8c155": { 10 | "ProjectGuid": "b378c036-3fb5-4147-9f45-d9648da8c155", 11 | "DisplayName": "recognizers", 12 | "ColorIndex": 1 13 | }, 14 | "5420ab9f-cdd2-40e5-88ad-c2efc39bc7e5": { 15 | "ProjectGuid": "5420ab9f-cdd2-40e5-88ad-c2efc39bc7e5", 16 | "DisplayName": "recognizer", 17 | "ColorIndex": 2 18 | }, 19 | "e5d6fa00-d30c-4037-9009-65778090d9fb": { 20 | "ProjectGuid": "e5d6fa00-d30c-4037-9009-65778090d9fb", 21 | "DisplayName": "recognizer", 22 | "ColorIndex": 3 23 | }, 24 | "992ef0c6-b214-421e-821a-b37e741a6d3f": { 25 | "ProjectGuid": "992ef0c6-b214-421e-821a-b37e741a6d3f", 26 | "DisplayName": "digit-console", 27 | "ColorIndex": 4 28 | } 29 | }, 30 | "NextColorIndex": 5 31 | } -------------------------------------------------------------------------------- /digit-display/.vs/DigitDisplay/v16/.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremybytes/csharp-channels-presentation/40f41376fc25224120c9697c30ca01bf84c9f0dd/digit-display/.vs/DigitDisplay/v16/.suo -------------------------------------------------------------------------------- /digit-display/.vs/DigitDisplay/v17/.futdcache.v1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremybytes/csharp-channels-presentation/40f41376fc25224120c9697c30ca01bf84c9f0dd/digit-display/.vs/DigitDisplay/v17/.futdcache.v1 -------------------------------------------------------------------------------- /digit-display/.vs/DigitDisplay/v17/.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremybytes/csharp-channels-presentation/40f41376fc25224120c9697c30ca01bf84c9f0dd/digit-display/.vs/DigitDisplay/v17/.suo -------------------------------------------------------------------------------- /digit-display/DigitDisplay.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "digit-display", "digit-display\digit-display.csproj", "{AC8B6F47-0DEE-47B2-AC39-7FF591B92B1B}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "recognizer", "recognizer\recognizer.csproj", "{E5D6FA00-D30C-4037-9009-65778090D9FB}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "digit-console", "digit-console\digit-console.csproj", "{992EF0C6-B214-421E-821A-B37E741A6D3F}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {AC8B6F47-0DEE-47B2-AC39-7FF591B92B1B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {AC8B6F47-0DEE-47B2-AC39-7FF591B92B1B}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {AC8B6F47-0DEE-47B2-AC39-7FF591B92B1B}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {AC8B6F47-0DEE-47B2-AC39-7FF591B92B1B}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {E5D6FA00-D30C-4037-9009-65778090D9FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {E5D6FA00-D30C-4037-9009-65778090D9FB}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {E5D6FA00-D30C-4037-9009-65778090D9FB}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {E5D6FA00-D30C-4037-9009-65778090D9FB}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {992EF0C6-B214-421E-821A-B37E741A6D3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {992EF0C6-B214-421E-821A-B37E741A6D3F}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {992EF0C6-B214-421E-821A-B37E741A6D3F}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {992EF0C6-B214-421E-821A-B37E741A6D3F}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {FF539E09-68FA-4B35-AF8D-D68CA46B8FF0} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /digit-display/digit-console/Configuration.cs: -------------------------------------------------------------------------------- 1 | using CommandLine; 2 | 3 | namespace digit_console; 4 | 5 | internal class Configuration 6 | { 7 | [Option(shortName: 'o', longName: "offset", Required = false, HelpText = "Offset in the data set (default: 1000)", Default = 1000)] 8 | public int Offset { get; set; } 9 | 10 | [Option(shortName: 'c', longName: "count", Required = false, HelpText = "Number of records to process (default: 100)", Default = 100)] 11 | public int Count { get; set; } 12 | 13 | [Option(longName: "classifier", Required = false, HelpText = "Classifier to use (default: 'euclidean')", Default = "euclidean")] 14 | public string Classifier { get; set; } 15 | 16 | [Option(shortName: 't', longName: "threads", Required = false, HelpText = "Number of threads to use (default: 6)", Default = 6)] 17 | public int Threads { get; set; } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /digit-display/digit-console/Display.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | namespace digit_console; 4 | 5 | public class Display 6 | { 7 | public static void GetImagesAsString(StringBuilder result, int[] image1, int[] image2) 8 | { 9 | var first = GetImageAsArray(image1); 10 | var second = GetImageAsArray(image2); 11 | for (int i = 0; i < 28; i++) 12 | { 13 | result.Append(first[i]); 14 | result.Append(" | "); 15 | result.AppendLine(second[i]); 16 | } 17 | } 18 | 19 | public static string[] GetImageAsArray(int[] image) 20 | { 21 | List result = new(); 22 | StringBuilder line = new(); 23 | for (int i = 0; i < image.Length; i++) 24 | { 25 | if (i % 28 == 0 && i != 0) 26 | { 27 | result.Add(line.ToString()); 28 | line.Clear(); 29 | } 30 | var output_char = GetDisplayCharForPixel(image[i]); 31 | line.Append(output_char); 32 | line.Append(output_char); 33 | } 34 | result.Add(line.ToString()); 35 | return result.ToArray(); 36 | } 37 | 38 | private static char GetDisplayCharForPixel(int pixel) 39 | { 40 | return pixel switch 41 | { 42 | > 16 and < 32 => '.', 43 | >= 32 and < 64 => ':', 44 | >= 64 and < 160 => 'o', 45 | >= 160 and < 224 => 'O', 46 | >= 224 => '@', 47 | _ => ' ', 48 | }; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /digit-display/digit-console/Program.cs: -------------------------------------------------------------------------------- 1 | using digits; 2 | using digit_console; 3 | using System.Threading.Channels; 4 | using CommandLine; 5 | using System.Text; 6 | using System.Diagnostics; 7 | 8 | int offset = 0; 9 | int count = 10; 10 | string classifier_option = ""; 11 | int threads = 6; 12 | 13 | CommandLine.Parser.Default.ParseArguments(args) 14 | .WithParsed(c => 15 | { 16 | offset = c.Offset; 17 | count = c.Count; 18 | threads = c.Threads; 19 | classifier_option = c.Classifier.ToLower() 20 | switch 21 | { 22 | "euclidean" => "euclidean", 23 | "manhattan" => "manhattan", 24 | _ => "euclidean", 25 | }; 26 | }).WithNotParsed(c => 27 | { 28 | Environment.Exit(0); 29 | }); 30 | 31 | List errors = new(); 32 | 33 | var (training, validation) = FileLoader.GetData("train.csv", offset, count); 34 | Console.Clear(); 35 | Console.WriteLine("Data Load Complete..."); 36 | 37 | Classifier classifier = classifier_option 38 | switch 39 | { 40 | "euclidean" => new EuclideanClassifier(training), 41 | "manhattan" => new ManhattanClassifier(training), 42 | _ => new EuclideanClassifier(training), 43 | }; 44 | 45 | var timer = new Stopwatch(); 46 | timer.Start(); 47 | 48 | var channel = Channel.CreateUnbounded(); 49 | var listener = Listen(channel.Reader, errors); 50 | 51 | var producer = Produce(channel.Writer, classifier, validation, threads); 52 | await producer; 53 | 54 | await listener; 55 | 56 | timer.Stop(); 57 | var elapsed = timer.Elapsed; 58 | 59 | PrintSummary(classifier, offset, count, elapsed, errors.Count); 60 | Console.WriteLine("Press any key to show errors..."); 61 | Console.ReadLine(); 62 | 63 | foreach (var item in errors) 64 | { 65 | DisplayImages(item, true); 66 | } 67 | 68 | PrintSummary(classifier, offset, count, elapsed, errors.Count); 69 | 70 | 71 | 72 | static void DisplayImages(Prediction prediction, bool scroll) 73 | { 74 | if (!scroll) 75 | { 76 | Console.SetCursorPosition(0, 0); 77 | } 78 | StringBuilder output = new(); 79 | output.Append($"Actual: {prediction.Actual.Value} "); 80 | output.Append(' ', 46); 81 | output.AppendLine($" | Predicted: {prediction.Predicted.Value}"); 82 | Display.GetImagesAsString(output, prediction.Actual.Image, prediction.Predicted.Image); 83 | output.Append('=', 115); 84 | Console.WriteLine(output); 85 | } 86 | 87 | static void PrintSummary(Classifier classifier, int offset, int count, TimeSpan elapsed, int total_errors) 88 | { 89 | Console.WriteLine($"Using {classifier.Name} -- Offset: {offset} Count: {count}"); 90 | Console.WriteLine($"Total time: {elapsed}"); 91 | Console.WriteLine($"Total errors: {total_errors}"); 92 | } 93 | 94 | static async Task Produce(ChannelWriter writer, 95 | Classifier classifier, Record[] validation, int threads) 96 | { 97 | await Parallel.ForEachAsync( 98 | validation, 99 | new ParallelOptions() { MaxDegreeOfParallelism = threads }, 100 | async (imageData, token) => 101 | { 102 | var result = await classifier.Predict(new(imageData.Value, imageData.Image)); 103 | await writer.WriteAsync(result, token); 104 | }); 105 | 106 | writer.Complete(); 107 | } 108 | 109 | static async Task Listen(ChannelReader reader, 110 | List log) 111 | { 112 | await foreach (Prediction prediction in reader.ReadAllAsync()) 113 | { 114 | DisplayImages(prediction, false); 115 | if (prediction.Actual.Value != prediction.Predicted.Value) 116 | { 117 | log.Add(prediction); 118 | } 119 | } 120 | } 121 | 122 | 123 | -------------------------------------------------------------------------------- /digit-display/digit-console/digit-console.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | digit_console 7 | enable 8 | enable 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /digit-display/digit-display/App.xaml: -------------------------------------------------------------------------------- 1 |  6 | 7 | 10 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /digit-display/digit-display/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | 3 | namespace DigitDisplay; 4 | 5 | public partial class App : Application 6 | { 7 | } 8 | -------------------------------------------------------------------------------- /digit-display/digit-display/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | 3 | [assembly: ThemeInfo( 4 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located 5 | //(used if a resource is not found in the page, 6 | // or application resource dictionaries) 7 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located 8 | //(used if a resource is not found in the page, 9 | // app, or any theme specific resource dictionaries) 10 | )] 11 | -------------------------------------------------------------------------------- /digit-display/digit-display/DetailControl.xaml: -------------------------------------------------------------------------------- 1 |  9 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 23 | 25 | 27 | 29 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /digit-display/digit-display/DetailControl.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Drawing; 2 | using System.Windows.Controls; 3 | 4 | namespace DigitDisplay; 5 | 6 | public record DetailRecord(int Prediction, int Actual, Bitmap Image); 7 | 8 | public partial class DetailControl : UserControl 9 | { 10 | private DetailRecord? data; 11 | public DetailRecord? Data 12 | { 13 | get { return data; } 14 | set 15 | { 16 | data = value; 17 | UpdateUI(); 18 | } 19 | } 20 | 21 | 22 | public DetailControl(DetailRecord record) 23 | { 24 | InitializeComponent(); 25 | Data = record; 26 | } 27 | 28 | private void UpdateUI() 29 | { 30 | var multiplier = 4; 31 | DigitImage.Source = data!.Image.ToWpfBitmap(); 32 | DigitImage.Width = DigitImage.Source.Width * multiplier; 33 | DigitImage.Height = DigitImage.Source.Height * multiplier; 34 | 35 | Prediction.Text = $"{data.Prediction}"; 36 | Prediction.Height = DigitImage.Height; 37 | Prediction.Width = DigitImage.Width; 38 | 39 | Actual.Text = $"Actual: {data.Actual}"; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /digit-display/digit-display/DigitBitmap.cs: -------------------------------------------------------------------------------- 1 | using System.Drawing; 2 | 3 | namespace DigitDisplay; 4 | 5 | public class DigitBitmap 6 | { 7 | public static int[][] GenerateDigitArray(int[] input) 8 | { 9 | var output = new int[28][]; 10 | for (int i = 0; i < 28; i++) 11 | { 12 | output[i] = input 13 | .Skip(i * 28) 14 | .Take(28) 15 | .ToArray(); 16 | } 17 | return output; 18 | } 19 | 20 | public static Bitmap GetBitmapFromRawData(int[] input) 21 | { 22 | var digitArray = GenerateDigitArray(input); 23 | 24 | var digitBitmap = new Bitmap(28, 28); 25 | 26 | for (int i = 0; i < 28; i++) 27 | for (int j = 0; j < 28; j++) 28 | { 29 | var colorValue = 255 - digitArray[i][j]; 30 | digitBitmap.SetPixel(j, i, 31 | Color.FromArgb(colorValue, colorValue, colorValue)); 32 | } 33 | digitBitmap.MakeTransparent(Color.White); 34 | return digitBitmap; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /digit-display/digit-display/Globals.cs: -------------------------------------------------------------------------------- 1 | global using System.Windows; 2 | global using System.Windows.Controls; 3 | global using System.Windows.Input; 4 | -------------------------------------------------------------------------------- /digit-display/digit-display/ImageHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Drawing; 2 | using System.Drawing.Imaging; 3 | using System.IO; 4 | using System.Windows.Media.Imaging; 5 | 6 | namespace DigitDisplay; 7 | 8 | public static class ImageHelper 9 | { 10 | public static BitmapSource ToWpfBitmap(this Bitmap bitmap) 11 | { 12 | using MemoryStream stream = new(); 13 | bitmap.Save(stream, ImageFormat.Png); 14 | 15 | stream.Position = 0; 16 | BitmapImage result = new(); 17 | result.BeginInit(); 18 | // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed." 19 | // Force the bitmap to load right now so we can dispose the stream. 20 | result.CacheOption = BitmapCacheOption.OnLoad; 21 | result.StreamSource = stream; 22 | result.EndInit(); 23 | result.Freeze(); 24 | return result; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /digit-display/digit-display/MainWindow.xaml: -------------------------------------------------------------------------------- 1 |  6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 19 | 20 | 21 | 22 | 24 | 25 | 26 | 27 | 29 | 30 | 31 | 32 |