<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jacobs Data Solutions on Medium]]></title>
        <description><![CDATA[Stories by Jacobs Data Solutions on Medium]]></description>
        <link>https://medium.com/@jacobsdatasolutions?source=rss-a80f78e022fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Tmfj54HXEkc4VXVb.jpg</url>
            <title>Stories by Jacobs Data Solutions on Medium</title>
            <link>https://medium.com/@jacobsdatasolutions?source=rss-a80f78e022fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 18:32:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jacobsdatasolutions/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[City of Chicago and Cook County: Playing by Our Own Rules]]></title>
            <link>https://medium.com/the-hr-professionals-guide/city-of-chicago-and-cook-county-playing-by-our-own-rules-0084b11be316?source=rss-a80f78e022fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/0084b11be316</guid>
            <category><![CDATA[human-resources]]></category>
            <category><![CDATA[chicago]]></category>
            <category><![CDATA[illinois]]></category>
            <category><![CDATA[employment-law]]></category>
            <category><![CDATA[hr]]></category>
            <dc:creator><![CDATA[Jacobs Data Solutions]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 18:50:23 GMT</pubDate>
            <atom:updated>2024-01-28T18:50:23.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_bIUOQW0bYFwl6Pv6kVFg.jpeg" /><figcaption>Photo by 𝓢𝓱𝓪𝓷𝓮 𝓦𝓮𝓼𝓽 ™: <a href="https://www.pexels.com/photo/view-of-the-kennedy-expressway-and-skyline-of-chicago-illinois-united-states-17956592/">https://www.pexels.com/photo/view-of-the-kennedy-expressway-and-skyline-of-chicago-illinois-united-states-17956592/</a></figcaption></figure><p>In my previous article, I talked about significant laws taking effect in this new year of 2024 for employees/employers doing business in Illinois, including the monumental Paid Leave for All Workers (PLAW) Act. You should be aware that (in classic Chicago fashion) both Cook County and the City of Chicago have their own paid leave ordinances that supersede PLAW. Again, I am not a lawyer, so please consult the legal counsel at your organization and do your own research to verify this information.</p><h3>Dare to be Different</h3><p>For the most part, the Cook County ordinance is identical to PLAW except that it includes an individual right of action. The City of Chicago ordinance seems to be more beneficial to employees in that it differentiates between Paid Leave and Paid Sick Leave. Additionally, the accrual rate is 1 hour per 35 hours worked vs. 1 hour per 40 hours worked under the other laws. The City of Chicago ordinance includes a cure period from July 1st, 2025 to June 30th, 2026. Also, this ordinance mandates payout of unused leave for medium and large employers, which the other laws do not. Lastly, the City of Chicago ordinance raises fines for damages and underpayment.</p><p>For more information, you can check out the links below:</p><ul><li>Cook County <a href="https://www.cookcountyil.gov/service/paid-leave-ordinance-and-regulations">Paid Leave Ordinance and Regulations</a></li><li>Cook County Paid Leave Ordinance <a href="https://www.cookcountyil.gov/news/cook-county-paid-leave-ordinance-officially-effect">Officially in Effect</a></li><li>Illinois <a href="https://labor.illinois.gov/">Department of Labor</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0084b11be316" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-hr-professionals-guide/city-of-chicago-and-cook-county-playing-by-our-own-rules-0084b11be316">City of Chicago and Cook County: Playing by Our Own Rules</a> was originally published in <a href="https://medium.com/the-hr-professionals-guide">The HR Professional’s Guide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Illinois Laws That May Be Relevant to HR Professionals in 2024]]></title>
            <link>https://medium.com/the-hr-professionals-guide/illinois-laws-that-may-be-relevant-to-hr-professionals-in-2024-2141e60ace34?source=rss-a80f78e022fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/2141e60ace34</guid>
            <category><![CDATA[employment]]></category>
            <category><![CDATA[employee-benefits]]></category>
            <category><![CDATA[employment-law]]></category>
            <category><![CDATA[hr]]></category>
            <category><![CDATA[human-resources]]></category>
            <dc:creator><![CDATA[Jacobs Data Solutions]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 12:01:39 GMT</pubDate>
            <atom:updated>2024-01-23T03:05:28.412Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xm9FaKdkGRfod4yrMluc5w.jpeg" /><figcaption>Photo by KATRIN BOLOVTSOVA: <a href="https://www.pexels.com/photo/lady-justice-and-a-gavel-6077123/">https://www.pexels.com/photo/lady-justice-and-a-gavel-6077123/</a></figcaption></figure><p>In this article, I will present a number of new laws that are taking effect or have taken effect in 2024 that are likely relevant to small, medium, and large businesses domiciled in Illinois or that have employees in Illinois. I hope this information is useful to the HR professional, entrepreneur, or anybody else who is curious. Please allow me to take this opportunity to state that I am a humble computer geek (more specifically, a Software Solutions Architect) and that law is not my primary profession. In other words, <strong>I am not a lawyer</strong>. Please consult the legal team at your organization or other legal counsel to confirm the accuracy of the information presented here, especially before acting upon it. I’ve chosen to focus on the dozen or so laws that I think are likely to be most important to HR professionals, however, this list is non-exhaustive and I strongly encourage you to do your research and fact-checking.</p><h3>Illinois Paid Leave for All Workers Act (PLAW)</h3><p>Front and center is the <a href="https://ilga.gov/legislation/ilcs/ilcs3.asp?ActID=4351&amp;amp;ChapterID=68">Paid Leave for All Workers Act</a>, or PLAW Act. This important new piece of legislation, which took effect on January 1, 2024, brings significant changes to employment regulations in the state. Here are the major highlights:</p><ul><li>Leave Accrual and Usage: Employees accrue one hour of paid leave for every 40 hours worked, up to a maximum of 40 hours in a 12-month period. This leave can be used for any reason, and employers cannot require employees to provide a basis for their time off request​​​​​​ (820 ILCS 192/15).</li><li>Eligibility: The Act applies to most employees in Illinois, including full-time and part-time workers, with some exclusions like temporary part-time student employees at state colleges and universities (820 ILCS 192/10). Employers of any size are covered, including most state and local government employers. However, it does not preempt local ordinances like the Chicago Minimum Wage and Paid Sick Leave Ordinance or the Cook County Earned Sick Leave Ordinance​​​​ (820 ILCS 192/15 subsection (p)).</li><li>Carryover and Front-loading Options: Employers can choose between an accrual system or a front-loading system for leave. Under the accrual system, unused paid leave can be carried over to the next year, while in the front-loading system, 40 hours of paid leave are provided at the start of the period, without a requirement for carryover​​​​ (820 ILCS 192/15 subsections (c) and (i)).</li><li>Pay Requirements: Employees must be paid their normal hourly rate during leave. For employees earning gratuities or commissions, the pay rate will be at least the minimum wage. Employers are not required to pay out unused leave upon separation unless it has been credited to the employee’s paid time off or vacation banks​​​​ (820 ILCS 192/15 subsections (f) and (l)).</li><li>Notice and Recordkeeping Requirements: Employers are required to provide notice of the Act’s requirements in the workplace and in employee handbooks. They must also keep records of hours worked, paid leave accrued and taken, and remaining paid leave balance for at least three years​​​​ (820 ILCS 192/20).</li><li>Enforcement and Remedies: The Illinois Department of Labor (IDOL) is responsible for administering and enforcing the Act. Violations can result in civil suits and penalties, including compensatory damages and fines (820 ILCS 192/30)​​.</li><li>Employee Notice and Documentation: Employers may require up to seven days’ notice for foreseeable leave, or as soon as practicable for unforeseeable leave. They cannot require employees to provide documentation for leave or to find a replacement worker​​ (820 ILCS 192/15 subsection (h)).</li></ul><p>This Act represents a significant step in employee rights and workplace flexibility in Illinois, mandating paid leave for virtually all workers for any reason, thus promoting a healthier work-life balance. If you are an HR professional or small business owner and you have employees in Illinois, <em>even those who are working remotely</em>, then you owe it to yourself and your organization to consult with legal counsel and to understand the implications of this monumental law.</p><h3>Related Links:</h3><ul><li>Illinois General Assembly <a href="https://ilga.gov/legislation/ilcs/ilcs2.asp?ChapterID=68">Chapter 820</a> — EMPLOYMENT</li><li>Illinois Department of Labor — <a href="https://labor.illinois.gov/laws-rules/paidleave.html">Paid Leave for All Workers Act Notice</a></li><li>Illinois Department of Labor — <a href="https://labor.illinois.gov/faqs/paidleavefaq.html">Paid Leave for All Workers Act FAQ</a></li></ul><h3>Additional Illinois Employment Acts Taking Effect That You Should Probably Know About</h3><p>The following is a non-exhaustive list of bills that involve labor law or that you may otherwise be interested in. All are effective 1/1/2024.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0282">HB 1363</a></p><p>Provides an employer may be liable for the actions of an employee if they were performing their employment duties and during it they caused injuries to another under the gender violence act. Establishes a 4-year statute of limitation to bring a claim of gender related violence.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0272">HB 1540</a></p><p>Prohibits the use of electronic cigarettes in public places and within 15 feet of entrances.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0291">HB 2068</a></p><p>Allows full-time employees in Cook County to use pre-tax dollars, via payroll deduction, for the purchase of a transit pass.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0428">HB 2102</a></p><p>Provides the names of various offenses that do not bar an individual from being hired by a health care employer.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0026">HB 2145</a></p><p>Directs the Department of Financial and Professional Regulation to refuse to issue or renew, or suspend the professional license of any individual or entity which has been found by the Workers’ Compensation Commission or Department of Insurance to not have obtained workers’ compensation insurance coverage.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0106">HB 2296</a></p><p>Ensures that rate increases on accident and health insurance for all individual and small groups must be subject to review and approvals by the Department of Insurance.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0314">HB 2493</a></p><p>Provides two weeks of unpaid leave for employees whose family or household member was killed in a crime of violence.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0040">HB 2907</a></p><p>Provides that in a labor dispute, a court should not grant an award for money damages except in the case of damage to an employer’s personal property as a result of conduct prohibited by law.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0343">HB 3301</a></p><p>Expands newly hired employees to include individuals under an independent contractor arrangement for the purposes of tracking non-custodial parents who are not paying child support.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0450">HB 3516</a></p><p>Allows employees up to 10 days of paid leave in any 12 month period to serve as an organ donor. Applicable for employees of any unit of local government, board of election commissioners, or any private employer in Illinois with 51 or more employees.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0356">HB 3699</a></p><p>Allows Illinois Department of Employment Security to collaborate with the Illinois Department of Healthcare and Family Services to identify employment opportunities for individuals who are in arrears on child support obligations.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0201">HB 3733</a></p><p>Provides for updated and modernized procedures, including allowing for electronic payment of fines for violation of labor laws, electronic copies of personnel records and electronic posting of labor rights information for remote employees.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0395">SB 2017</a></p><p>Clarifies that education support personnel employees may not be required to work on legal school holidays and that no deduction may be made from time or compensation on account of a holiday on which the employee would have otherwise worked.</p><p><a href="https://ilga.gov/legislation/publicacts/fulltext.asp?Name=103-0466">SB 2034</a></p><p>Provides extended bereavement leave to employees who have lost a child to suicide or homicide. For employers with 250 or more full-time employees, employees are provided twelve weeks of unpaid leave.</p><h3>Related Links:</h3><ul><li><a href="https://www.illinoissenatedemocrats.com/images/PDFS/2023/bills-taking-effect-2024.pdf">Illinois Bills Going Into Effect in 2024</a></li><li>Illinois General Assembly — <a href="https://ilga.gov/legislation/publicacts/default.asp">Public Acts</a></li></ul><h3>Conclusion</h3><p>The state of Illinois has made many changes to employment and labor law going into 2024, the most notable of which is the Illinois Paid Leave for All Workers Act (PLAW). If you are an HR professional, small business owner or other interested party, this involves you. It pays to be informed, consult with legal counsel, and take appropriate action to make sure that you are abiding by the law and your business runs smoothly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2141e60ace34" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-hr-professionals-guide/illinois-laws-that-may-be-relevant-to-hr-professionals-in-2024-2141e60ace34">Illinois Laws That May Be Relevant to HR Professionals in 2024</a> was originally published in <a href="https://medium.com/the-hr-professionals-guide">The HR Professional’s Guide</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your Software Engineering Laptop]]></title>
            <link>https://medium.com/software-alchemy/supercharge-your-software-engineering-laptop-a7e82ff6a954?source=rss-a80f78e022fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7e82ff6a954</guid>
            <category><![CDATA[laptop]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[hardware]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Jacobs Data Solutions]]></dc:creator>
            <pubDate>Wed, 18 Aug 2021 11:42:14 GMT</pubDate>
            <atom:updated>2021-08-18T11:42:14.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*HRoevyZb_dpveJtN.jpg" /></figure><h3>Introduction</h3><p>In this blog entry, I’m going to take a break from talking about software engineering topics and instead discuss computer hardware. Specifically, I’m going to provide a detailed walkthrough of how I upgraded the RAM and Solid State Drive on my LG Gram ultrabook. As I stated at the <a href="https://blog.jacobsdata.com/2019/08/26/foundational-concepts-series-getting-started-as-a-microsoft-net-stack-developer#prerequisites">very beginning</a>, the computer that you use for your software development work matters. I chose to purchase the LG Gram 17&quot; <a href="https://www.lg.com/us/laptops/lg-17Z990-RAAS7U1-ultra-slim-laptop">2019 model</a> [no affiliate relationship with LG at this time] because it’s a rockin’ laptop for software engineers. The original laptop came with 16GB of RAM and a 256GB SSD, which I thought was upgradable to 20GB and 512GB, respectively. Little did I know, the laptop supports much more, and there is a popular modification out on the Internet to upgrade the RAM to 40GB and SSD to 1TB using high-quality Samsung components! For a few hundred bucks more and a moderate time investment, it was a deal I couldn’t refuse!</p><p>In what follows, I’ll provide the steps I took to perform this mod on my laptop. Even if you don’t have this same laptop, or are running on a desktop, you may still benefit from learning about the process I underwent to do the upgrade, the preparations I took, and potential pitfalls to avoid. Hopefully, this guide will help you develop a solid process for your computer hardware projects.</p><h3>Disclaimer</h3><p>I’m a software engineer by profession. I don’t claim to be the foremost expert on computer hardware. I’m just a humble nerd and, like you, I do a lot of research and reading of blogs. In that vein, let me state vociferously that I will not be held liable for any damages or losses, financial or otherwise, that you incur as a result of following the guidance provided in this blog entry. I’ve done my best to identify best practices but at the end of the day, YOU are responsible for your own equipment.</p><h3>Words of Wisdom</h3><blockquote><em>“Words of wisdom: Drop that zero and get with the hero.” -Vanilla Ice</em></blockquote><p>What follows are some pieces of sage advice that you may or not may find on other blogs or YouTube videos regarding this modification. I’ve saved you the effort of having to dig through the comment sections.</p><ol><li>What I describe here applies to the LG Gram 17&quot; 2019 model. You can similarly modify the LG Gram 17&quot; 2020 model, however, the specs are newer so you’ll need to use different hardware. Specifically, the 2020 model supports 3200Mhz RAM, whereas the 2019 model supports slower 2666Mhz RAM.</li><li>The RAM and SSD inside the 2021 model of the Gram are soldered onto the mainboard, so that model is NOT upgradeable. As far as I know, more than a few people have complained to LG about this.</li><li>As soon as you pull the backplate off of your laptop, you’ve voided the warranty. Just something to be aware of. Since I have the 2019 model, I don’t care because my laptop is already two years old.</li><li>Changing out the components in your laptop WILL affect the heat profile of your computer and the battery life as well. This is a given because laptops have a small form factor, and the trade-off for that small size, especially in a thin laptop like the LG Gram, is that it’s extremely difficult to manage the heat generated by various components such as the SSD. Laptops don’t have the luxury of extra space to mount heat sinks, etc. Everything is compact and every square centimeter has to count.</li><li>Building off of point #4, depending on the particular RAM and SSD that you decide to put in you may experience unexpected performance, as components will down-throttle to prevent hardware damage if they get too hot. In extreme cases, components may simply cook outright, though IMHO that’s more likely to happen with older hardware. After modding your laptop, you may need to take additional measures like purchasing a laptop cooling pad to help manage the additional heat generated.</li><li>Benchmarking certain hardware components such as your SSD will decrease the life of those components. Just so you’re aware. <a href="https://crystalmark.info/en/software/crystaldiskmark/">CrystalDiskMark</a>, for example, gives you this warning.</li><li>The RAM chip you purchase must be laptop RAM (DDR4 SODIMM). Regular form RAM chips for desktop computers won’t work.</li><li>The SSD should be NVMe M.2 2280, PCIe generation 3.0. My research indicates that PCIe 4.0 will NOT work, as laptops don’t currently support this and an additional heat sink would be required anyway, which wouldn’t fit inside a laptop.</li></ol><h3>Credit Where Credit Is Due</h3><p>In performing this upgrade of my laptop, I primarily followed the instructions from <a href="https://jaychen.dev/2020-2019-lg-gram-17-storage-ram-upgrade/">a blog entry</a> by technologist Jay Chen, however, there are several other great resources out there such as <a href="https://www.pcworld.com/">PC World</a>, <a href="https://www.tomshardware.com/">Tom’s Hardware</a>, <a href="https://www.reddit.com/r/laptops/">r/laptops</a>, <a href="https://www.reddit.com/r/techsupport/">r/techsupport</a>, or <a href="https://www.reddit.com/r/buildapc/">r/buildapc</a>. There are also some great YouTube videos out there, such as this one by <a href="https://www.youtube.com/watch?v=iiaeK1GHAls">TinkerForward</a>.</p><h3>The Parts</h3><p>I purchased the parts from Jay Chen’s blog post, which seems to be what most people use for this mod. These are:</p><ul><li><a href="https://www.newegg.com/samsung-970-evo-plus-1tb/p/N82E16820147743?Item=N82E16820147743">Samsung 970 EVO Plus 1TB Solid State Drive (SSD)</a></li><li><a href="https://www.amazon.com/gp/product/B07N124XDS/">Samsung 32GB DDR4 2666MHz RAM Memory Module for Laptop Computers</a></li><li><a href="https://www.amazon.com/gp/product/B01MRNIFR6/">iFixit Essentials Toolkit</a> (optional)</li></ul><p>[At the time of this writing, I don’t have any affiliate relationships with the products or vendors mentioned.]</p><h3>Pre-preparation</h3><p>Do not pass GO. Do not collect $200. Before doing anything to your computer, here are a few essential steps that most hardware tutorials overlook. However, you’ll be really glad you did them.</p><h3>Preliminary Step 1: Back Your S*** Up</h3><p>It should go without saying: back your stuff up. Your important data. Your pictures. Your code — even if you check most of your projects into Git repos, you probably have snippets and other files related to your work laying around that aren’t checked in. Back it all up. For less than $100 you can get a nice external hard drive to back everything up onto. Even a thumb drive is better than nothing. Just make sure your important files and documents are saved somewhere else before performing this or any other upgrade on your computer.</p><h3>Preliminary Step 2: Create Emergency Rescue/Repair Media</h3><p>If you are on Windows 10, follow <a href="https://support.microsoft.com/en-us/windows/create-an-iso-file-for-windows-10-38547366-1dcb-7afd-1726-9eb222d72705">these instructions</a>, to create an ISO bootable USB thumb drive. You must have a USB thumb drive with a minimum of 8GB (16 is better). There are alternative guides you can follow <a href="https://support.microsoft.com/en-us/windows/create-installation-media-for-windows-99a58364-8c02-206f-aa6f-40c3b507420d">here</a> or <a href="https://www.msn.com/en-us/news/technology/two-ways-to-create-a-windows-10-usb-bootable-media-with-uefi-support/ar-BB1azLGk">here</a>, as well as any number of third-party tools to create bootable rescue media. The point is to have an emergency reinstallation/repair method available in case something goes wrong.</p><p>After you have created your emergency restore USB, leave it plugged in and reboot your computer to test it to make sure it works. Hold F10 during the boot sequence to get to the Windows 10 boot menu. It should look like what you see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*pdj1eXoiTlqa66fW.jpg" /></figure><p>When you get to the Windows Setup screen, click on “Next”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*TXHxGZzqp4DiScZ6.jpg" /></figure><p>Click the “Repair your computer” link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*8GuNuvMkENAsP0wT.jpg" /></figure><p>Choose the “Troubleshoot” option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*pkMn4GXdx32mkwMT.jpg" /></figure><p>You now have advanced options at your disposal, including a command prompt that gives you access to important tools like DISKPART and the like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*PPa0tS4MC76VwFz5.jpg" /></figure><p>When you are satisfied that your emergency repair media is working, proceed to the next step.</p><h3>Preliminary Step 3: Baseline Your System</h3><p>Before performing this or any other upgrade, it’s a good idea to baseline your system. This is another step that seems to get neglected in a lot of how-to’s. At the very least, you want a tool that will show you the temperature of the components inside your computer. I like using <a href="https://www.cpuid.com/softwares/hwmonitor.html">CPUID HWMonitor</a>. Use it alongside a tool like <a href="https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer">SysInternals Process Explorer</a> so you can see what processes are running and if necessary, stop them. Take a screenshot of your temps while your computer is idle, like what I’ve shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*vK6FZb7o_6lX3-lA.png" /></figure><p>Now, download a tool like <a href="https://www.mersenne.org/download/">Prime95</a> so that you can push your processor to its limit and get a good benchmark. Note: some hardware buffs on the Net may claim that using a tool like Prime95 on a laptop isn’t a good idea. My stance is that the likelihood of causing hardware damage is low, especially if you’re only running it for less than a minute. Again, see my disclaimer above.</p><p>Here’s what it looked like on my machine when I ran the various Prime95 tests against the original LG Gram hardware.</p><h3>Test 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/0*3bBUwlDXNPXnS_SP.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*pfuLt2TBYxe4tAVR.png" /></figure><h3>Test 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/0*fvrTBKy2NwnAlYem.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*_Ne3unWIp22uNYyB.png" /></figure><h3>Test 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/0*0QqiQyPt0gK6uf7T.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*jZPB0sUfaNSDFxPF.png" /></figure><p>As you can see from the various screenshots, the CPU tends to idle around 55°C (130°F) with little to no load. Pushing it a little bit, it goes up to around 85°C (185°F) to 90°C (194°F). Above 90°C, and you start to have a problem. At such higher temperatures, the CPU should begin to down throttle to prevent hardware damage and if it can’t cool down quickly enough (airflow is blocked, the heat sink isn’t properly seated or thermal paste was applied improperly) then you risk cooking your CPU.</p><p>Just as an aside, laptop components such as CPUs are made to run hotter than desktop ones. This makes sense, taking into consideration what I said earlier about heat management being an issue inside the smaller form factor of a laptop. For example, I have a micro-ATX Xeon server that I built a few years ago sitting in a spare room in my home. At this point, I just use it to donate processing power to scientific projects, like discovering new medical treatments for Covid at IBM’s <a href="https://www.worldcommunitygrid.org/discover.action">World Community Grid</a>. The server’s cores are all pegged at 100%, non-stop 24/7, and they still rarely go above 50–60°C. However, if you look inside you can see that there’s a massive heat sink sitting on top of the CPU and multiple fans providing ample airflow across the cores and the memory chips. There’s no such luxury with a laptop, as we’ll see when we open up our LG Gram and look inside.</p><p>Assuming that you purchased the Samsung SSD, then you should also download <a href="https://samsung.com/magician">Samsung Magician</a> so you can benchmark your SSD. It’s interesting to note that the 256GB SATA stays around 42–52°C, even after running a bunch of heavy read/write operations against it. Such will not be the case after installing the Samsung 970 Evo Plus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*TAA_obaT-8wpMHb1.png" /></figure><p>So why does all this matter? We’re not upgrading the CPU, correct? A few reasons:</p><ol><li>The Gram doesn’t seem to have many heat sensors inside it, aside from those on the CPU. We must use what we have.</li><li>Changing around the other hardware <em>may</em> affect how the CPU runs.</li><li>The heat generated by the new RAM chip and SSD is likely to flow across the CPU, as you can see in the picture below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*M2JaFJMqMdBSX06h.jpg" /></figure><h3>Apples to Apples</h3><p>Another point to take into consideration is the ambient temperature of your physical space when performing these tests and the power plan of your laptop, typically determined by whether or not your laptop is plugged in and how much battery is left. If you’re going to go through the effort of doing this prep work, why not be as scientific as possible, right? Try to keep all other variables constant when doing before/after comparisons. In my case, I had the air conditioning going so that the temperature of the room was about 20.6–21°C (69–70°F) both before and after the tests, and my laptop was plugged in and at 100% battery.</p><h3>Upgrade Preparation</h3><p>Arrange your laptop and parts for the upgrade on a clean, non-conductive surface. I recommend wearing an anti-static band while you work, latex gloves if you’re super paranoid about static electricity zapping your components and/or laptop. Don’t do something boneheaded like perform the upgrade on a wool rug while wearing flannel pants, etc. Make sure the laptop is unplugged. When everything is ready, we can start the upgrade.</p><p>Here you see everything laid out in my workspace, ready to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*2u_3mDLhdSclyG0r.jpg" /></figure><h3>Step 1: Pry Out the Rubber Footings and Remove the Screws From the Laptop Backplate</h3><p>This is all pretty much the same as what Jay Chen did in his blog entry that I used as a guide. Removing the rubber footings and screw covers is fairly straightforward. There is adhesive binding the rubber footings to the backplate, so it will take some effort to pry them out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*pEUKZb2DWl5oJkcr.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*aPbq9RW-WTRI4cGJ.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*uavf-6oOF6NKaYJJ.jpg" /></figure><h3>Step 2: Remove the Backplate</h3><p>I found this step to be surprisingly difficult. Use the knife to pry around the edges and ideally do it with an old microfiber cloth around it so you don’t damage the paint. Don’t use too much force or you could bend or break the backplate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*kXWnv353Io1_gyAq.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*MhktjCKV5XI_Ac3_.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*8FotBODH-hLKJcqb.jpg" /></figure><p>If you were successful in removing the backplate, then you should have access to the RAM and SSD, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*a2XWXp_nW4V6-YRN.jpg" /></figure><h3>Step 3: Install the New RAM Chip</h3><p>Pull the side latches to disengage the old RAM chip and remove it at a 45-degree angle. Insert the new RAM chip at a 45-degree angle and press down gently to latch it into place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*Cat9Tzi1pDBJZUvP.jpg" /></figure><h3>Step 4: Boot the Laptop Post RAM Upgrade</h3><p>Here’s where I differ from other tutorials of this kind in that I err on the conservative side. I recommend you put the backplate back on temporarily (don’t put the screws back in yet), turn it right side up, and then boot up to make sure that the laptop accepts the new memory.</p><p>First, hold F2 at boot time to get into the BIOS. It may take a little longer to boot the first time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*lmxRT2_iWSBjeeJc.jpg" /></figure><p>The BIOS recognizes our new memory. Hooray!</p><p>After that, boot to Windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*Acw8be7CDuZUvOFa.png" /></figure><p>ProcMon shows us that the operating system recognizes and can utilize all the memory. Awesome!</p><h3>Step 5: Install the New SSD</h3><p>We are now going to install the new solid-state drive. Remove the backplate from the laptop again and unscrew the screw from the empty SATA x2 slot. Insert the new SSD at a 45-degree angle, gently press down, and then replace the screw to hold it into place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*czX7dysZk1NL8LMP.jpg" /></figure><p>Both SSDs are now installed. Put the backplate back on temporarily again. Turn back on the laptop and boot into Windows.</p><h3>Step 6: Use Samsung Software to Copy Over the Image of Your Operating System</h3><p>Our goal here is to move EVERYTHING onto the new SSD so that we can swap out the old one and move the new, better one into the faster SATA x4 slot. To do this, we need to copy over:</p><ul><li>The Windows (C:) partition.</li><li>The EFI boot partition.</li><li>The OEM operating system recovery partition.</li></ul><p>If you go into Disk Management in Windows, you should see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*J2xoXHjh5XcTUq7p.png" /></figure><p>We want to copy over all of them. If you purchased a Samsung SSD then you should be able to copy over the Windows partition EFI boot partition and recovery partition from the OEM SSD that came installed in the LG Gram by using the Samsung Data Migration tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*ZQK5UPHVb6_9Rmtp.png" /></figure><p>At first, I thought that it would only copy over the Windows OS partition since the tool refers to the SSD as C: (a logical partition name). However, it will copy over the entire SSD contents.</p><p>Once you have copied over the partitions from the old SSD to the new one, you should see something like this on the new SSD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*0TGumby3xQnN2yhy.png" /></figure><p>As stated in the comment section of Jay Chen’s blog post, if you try to boot your laptop with two SSDs in it, each of which has a Windows system partition on it, then your laptop won’t boot and you’ll get an error like what you see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*ZoBMUpoWBat86BY_.jpg" /></figure><p>You can either boot to a recovery USB stick at this point and wipe out the partitions on your old SSD, or you can just remove the old SSD and keep it around somewhere as a backup, which is what I chose to do. The final step, then, is to open up the laptop one last time and move the new SSD to the faster SATA x4 slot.</p><h3>Step 7: Remove Old SSD and Move New One to the SATA x4 Slot</h3><p>Open up the laptop again and gently unscrew the screws securing the SSDs into their respective slots. Remove the old SSD from the primary (SATA x4) slot and set it aside. Insert the new SSD into the SATA x4 slot at a 45-degree angle, gently press it down into place, and then replace the fastener screw. Your hardware should now look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*zEXpdNOnziH0iC9B.jpg" /></figure><p>If you choose to keep the old SSD in the secondary slot so that you have more storage, just be aware that this will affect the heat generated in your laptop (see the airflow diagram above).</p><h3>Step 8: Benchmark the New Hardware</h3><p>Here comes the fun part. Now that both the new RAM and SSD are installed, we’re going to benchmark the new hardware. Put the backplate back on temporarily (don’t screw it back together yet, just in case) and boot up the laptop.</p><p>First, we’ll test the 970 Evo Plus SSD using Samsung Magician and compare the results to the original 256 GB SSD that came with the laptop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*7KOSqP6D-hNxQDEa.png" /></figure><p>Awesome! What a difference in performance! Let’s compare the two…</p><ul><li>Sequential read: 3182 MB/s vs. 530 MB/s</li><li>Sequential write: 2980 MB/s vs. 459 MB/s</li><li>Random Read: 175292 IOPS vs. 62011 IOPS</li><li>Random Write: 105468 IOPS vs. 49316 IOPS</li></ul><p>That’s a non-trivial improvement. Just looking at sequential read/write, that’s roughly 6x better performance!</p><p>However, that performance boost comes at a cost…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*3JI27VnZB4fYqZKf.png" /></figure><p>Holy cow, the SSD benchmark test cranked the heat of the SSD up to 71°C (160°F)! Hopefully, you won’t be hammering your new SSD like this all the time, but be aware that heat is now something you need to be mindful of.</p><p>What does the baseline CPU temperature look like with the new hardware in there?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*20dOfXhWH-6TtglY.png" /></figure><p>At first glance, it seems to be pretty comparable to the temperate profile with the original hardware, however, keep in mind that it WILL run hotter, just because of the hot air from the SSD blowing across the CPU, among other factors.</p><p>What about our Prime95 tests?</p><h3>Test 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*aqsK5aHzv0ORZVV_.png" /></figure><h3>Test 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*207goOKMgU9gL-B7.png" /></figure><h3>Test 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*ww_J7l-c_NaKZDqj.png" /></figure><p>Again, slamming on the processor yields results that are somewhat comparable to our tests from the original hardware. Nothing to be too alarmed about here.</p><h3>Step 9: Clean Up</h3><p>Only AFTER you’ve tested your new hardware and are confident that your shiny new RAM and SSD won’t cook like an egg, THEN go ahead and reattach the backplate by putting the screws back in and replacing the rubber footings. Your ultra-modded software engineer’s laptop is good to go.</p><h3>What’s Next?</h3><h3>Be Mindful of Heat, Be Kind to Your Laptop</h3><p>As I’ve reiterated many times, heat may now be an issue for your laptop. You can mitigate that by:</p><ul><li>Only using the laptop on a flat surface, like your desk.</li><li>Maintaining good airflow. Do not block the air vents on the back!</li><li>Keeping it clean. Periodically clean dust out of the vents using an air duster can or vacuum cleaner with gentle suction.</li><li>Purchasing a cooling pad. This may provide marginal improvements in temperature control. I purchased a <a href="https://www.newegg.com/cooler-master-r9-nbc-xsli-gp/p/N82E16834992853">Cooler Master</a> cooling pad with a fan [No affiliate relationship] and I’m fairly happy with it. I don’t use it all the time, but it’s there if I need it.</li></ul><h3>“Do Work, Son!”</h3><p>Put it to good use and go write some serious code! You should already be seeing some productivity gains from the SSD alone. What about the memory? Even at this time, in the back half of 2021, 40 GB of RAM is truly sick! What are you going to do with all that? If you’re writing code, have sixty browser windows open, and are running a development database on your local machine, you’re likely to not even come close to utilizing all that memory! You could try running video editing software or something, but honestly, the LG Gram isn’t really built for that and its other limitations (like lack of a dedicated graphics card) alone are going to bottleneck you to the point that it’s not worth it.</p><p>So, you can utilize some of that abundant memory by configuring a RAM disk and going to town. Even a “mere” 8GB RAM disk can be fun to play with and help you boost your productivity. In case this is unfamiliar to you, a RAM disk is a virtual partition that your operating system <em>thinks</em> is a hard drive or SSD, but reads to/writes from system RAM. The performance you get from it is <em>orders of magnitude</em> better than an ordinary hard drive, but the caveat is that it is temporary, and any files on your RAM disk are lost when you power down your laptop. To set one up on Windows, you can download the <a href="https://sourceforge.net/projects/imdisk-toolkit/">ImDisk</a> virtual hardware driver and toolkit, or get it from Chocolately:</p><pre>choco install imdisk<br>choco install imdisk-toolkit</pre><p>Here are a couple of screenshots showing the performance of an 8GB RAM disk vs. our new Samsung Evo 970 SSD using CrystalDiskMark.</p><p>SSD:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/0*vNm2i_mS5Cx6-UZ3.png" /></figure><p>RAM Disk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/0*vO57EpmYKnnG8fi6.png" /></figure><p>You can see that the RAM disk beats even our high-end SSD on sequential read/write tests, though oddly, it’s a toss-up on the random read/write tests.</p><h3>Conclusion</h3><p>In this blog entry, I discussed the steps I took to upgrade my venerable LG Gram 17&quot; [2019 model] laptop and laid out a basic process you can follow for any hardware upgrade project. This one, in particular, is a fairly well-known mod that many people on the Internet have accomplished, however, there are some pitfalls to watch out for, which not all bloggers mention. I talked about the importance of backing up your data and creating emergency restoration media in case something goes wrong. Then I talked about the value of benchmarking your system <em>before</em> you upgrade it so that you can have an apples-to-apples comparison against the new hardware. I went through the steps I did to perform the upgrade and posted relevant pictures, then I provided some post-upgrade data to see what improvements we got out of it. I went over some of the issues you might encounter with heat management, having replaced OEM parts in your laptop, and a few measures you can take to help mitigate them. Finally, I briefly touched on RAM disks and how you can have fun with them now that you have 40 whopping gigabytes of RAM to play with.</p><p>In future blog entries, I’ll get back to talking about software, but I hope you enjoyed this detour and got a lot out of it!</p><h3>Experts / Authorities / Resources</h3><h3>LG Gram Laptop, Hardware Components</h3><ul><li><a href="https://www.lg.com/us/laptops/lg-17Z990-RAAS7U1-ultra-slim-laptop">LG Gram 17&quot; 2019 Model</a></li><li><a href="https://www.newegg.com/samsung-970-evo-plus-1tb/p/N82E16820147743?Item=N82E16820147743">Samsung 970 EVO Plus 1TB Solid State Drive (SSD)</a></li><li><a href="https://www.amazon.com/gp/product/B07N124XDS/">Samsung 32GB DDR4 2666MHz RAM Memory Module for Laptop Computers</a></li><li><a href="https://www.amazon.com/gp/product/B01MRNIFR6/">iFixit Essentials Toolkit</a></li></ul><h3>Blogs, YouTube Videos, Forums</h3><ul><li><a href="https://jaychen.dev/2020-2019-lg-gram-17-storage-ram-upgrade/">Jay Chen</a></li><li><a href="https://www.pcworld.com/">PC World</a></li><li><a href="https://www.tomshardware.com/">Tom’s Hardware</a></li><li><a href="https://www.reddit.com/r/laptops/">r/laptops</a></li><li><a href="https://www.reddit.com/r/techsupport/">r/techsupport</a></li><li><a href="https://www.reddit.com/r/buildapc/">r/buildapc</a></li><li><a href="https://www.youtube.com/watch?v=iiaeK1GHAls">TinkerForward</a></li></ul><h3>Testing, Benchmarking</h3><ul><li><a href="https://crystalmark.info/en/software/crystaldiskmark/">CrystalDiskMark</a></li><li><a href="https://www.mersenne.org/download/">Prime95</a></li><li><a href="https://www.cpuid.com/softwares/hwmonitor.html">CPUID HWMonitor</a></li><li><a href="https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer">SysInternals Process Explorer</a></li><li><a href="https://samsung.com/magician">Samsung Magician</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7e82ff6a954" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-alchemy/supercharge-your-software-engineering-laptop-a7e82ff6a954">Supercharge Your Software Engineering Laptop</a> was originally published in <a href="https://medium.com/software-alchemy">Software Alchemy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain-Driven Design Workflow Patterns]]></title>
            <link>https://medium.com/software-alchemy/domain-driven-design-workflow-patterns-350085c53e5f?source=rss-a80f78e022fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/350085c53e5f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[bruce-lee]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Jacobs Data Solutions]]></dc:creator>
            <pubDate>Sun, 11 Apr 2021 18:07:02 GMT</pubDate>
            <atom:updated>2021-04-11T18:07:02.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*n--PpZRxqgGeaw22.jpg" /></figure><p><em>Image by </em><a href="https://pixabay.com/users/kreatikar-8562930/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4828146"><em>Mudassar Iqbal</em></a><em> from </em><a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4828146"><em>Pixabay</em></a></p><h3>Introduction</h3><p>Previously, I discussed our intention to maintain a separation between Presentation (View Model), Domain, and Persistence entities in our architecture. I talked about some of the difficulties this design decision presents, and how we can mitigate those obstacles using an elegant, methodical entity-mapping strategy. In this blog entry, I build off of that discussion and elaborate on some of the high-level architectural patterns which emerge as a result. This is especially relevant if you are using CQRS, although that is not a prerequisite, and these patterns will apply just as readily to other approaches, including traditional N-layered architectures. Let’s dig in!</p><h3>General Philosophy On Software And Life</h3><p>What I’m about to present are high-level architectural design patterns that seem to emerge when implementing CQRS workflows in a Clean Domain-Driven Design solution. I present these as suggestion and inspiration for your solutions, and not as a dogmatic, prescriptive approach which must be followed to the letter. As is often the case in software development, this is more of an art than a science, and the appropriateness of any of these patterns must be evaluated in the context of the particular problem you are trying to solve. YOU are the architect.</p><p>I remember (back in the day) when I was going through my <em>Design Patterns Phase</em>, as we all did when we were mid-level. I had this perfectionistic approach in which I sought to find the ideal pattern to apply to every different situation, as if there is some Rosetta stone for software development that indicates THE design pattern for every class of problem you run across (spoiler: there isn’t one). Then I stumbled across a blog posting that asserted that the best book on programming, bar none, is <a href="https://bookshop.org/books/tao-of-jeet-kune-do/9780897502023">Tao of Jeet Kune Do</a>, a book on martial arts by the legendary martial artist, Bruce Lee. I promptly bought the book, read it cover to cover, and then realized that the blogger was basically correct. (FYI — I would link to the original blog entry I read but it was over ten years ago and I’m having trouble finding it.) My entire worldview and general philosophy on software development were irrevocably altered from that point on.</p><blockquote><em>“Use only that which works, and take it from any place you can find it.”</em></blockquote><blockquote><em>― Bruce Lee, Tao of Jeet Kune Do</em></blockquote><p>Getting back to the discussion at hand, remember that at the end of the day our goal is to build and ship a product that solves a hard problem, either for somebody else or for ourselves. The essential principle is to <strong>do what is necessary</strong> to get the job done while staying mindful of core <a href="https://blog.jacobsdata.com/2020/01/27/basic-concepts-of-software-design-and-architecture#patterns-practices-principles-conventions">patterns and practices</a> that are conducive to scalability and maintainability.</p><p>As stated before, I noticed these patterns while using CQRS with Clean Domain-Driven Design. However, you may find that they work just as well when building a DDD system using some other approach, like the Repository pattern or a service-based methodology. Heck, these will probably work just fine in a traditional N-layered (ex: 3-tiered) application.</p><p>Alongside the patterns themselves, I present <strong>estimates</strong> of the frequency of which you may find yourself applying each of them in a typical enterprise business application. I want to emphasize that these are estimates, and your mileage may vary regarding your own use case.</p><p>As always, I will try to present code samples where appropriate, and refer back to the <a href="https://github.com/JacobsDataSolutions/OrgManager">demo application</a> if it helps clarify certain concepts.</p><h3>Basic Guidelines</h3><p>If you read my previous blog entry about <a href="https://blog.jacobsdata.com/2020/09/25/scaffold-your-clean-ddd-web-application-part-3-persistence-tenancy-and-the-data-model">Persistence</a> you’ll recall that we are using both Entity Framework Core and Dapper together to read from/write to an underlying database. Like a martial artist’s right arm and left leg, each is very different and suited to different purposes; however, when working together, they are complementary and synergize to yield highly effective results. Furthermore, there is an inherent <a href="https://blog.jacobsdata.com/2020/02/19/a-brief-intro-to-clean-architecture-clean-ddd-and-cqrs#cqrs-primer">asymmetry</a> in the needs of Command (Write) operations vs. Query (Read) operations, which will also influence the appropriateness of any given pattern. With that in mind, here are some general guidelines for use.</p><h3>1. Bypassing the Persistence and/or Domain Layers (Fast)</h3><p>Some patterns will want to cut past the Persistence and/or Domain layers entirely. This is common in most queries that simply hydrate View Models directly. Dapper is a no-brainer for this. If there were some mandate that I only use either Dapper or EF Core to build an entire software solution, I’d probably choose Dapper — and make no mistake, I’ve been a HUGE fan of Entity Framework for years, even going back to the .NET Framework days. Why is this? Quite simply, because Dapper is simple to use and it is a beast, performance-wise. Here are some common scenarios in which we’ll generally want to lean on it.</p><ul><li>Frequently-called queries (need for speed). Dapper is fast. Period.</li><li>Need to project data model into more complex shapes, like composite View Models. In this regard, Dapper also provides a degree of flexibility.</li><li>Simplistic updates, like hard (or soft) deletes. This has traditionally been an Achilles’ heel for Entity Framework, and trying to go the EF route would hurt performance more than it’d help in any other regard.</li></ul><h3>2. Going Through the Persistence Layer (Fluent)</h3><p>In other situations, especially those going <em>down</em> the stack, it makes sense to go through the Persistence layer. In general, these will lean on Entity Framework Core, although we can use Dapper to hydrate Persistence (EF) entities directly. Here are some such scenarios:</p><ul><li>Need to set up and orchestrate complex entity configurations. In this case, the <strong>fluency</strong> of the EF Core syntax works in our favor, along with the compiler checking we get from using it. One of the big downsides to using Dapper, or any other micro-ORM tool like it, is that if we make drastic changes to the underlying database schema, then we need to go back and modify SQL queries in our code, which is tedious and error-prone.</li><li>The workflow would benefit from the readability and elegance of LINQ. Again, by leveraging the simplicity and correctness of a <strong>declarative</strong> programming style, we can manage complexity inside workflows with a lot of moving pieces, and the fact that EF is built on classes rather than SQL code gives us a compile-time safety net when refactoring the data model.</li></ul><p>Another non-trivial benefit to using EF is that it greatly simplifies architecting the database and running migrations against it as it evolves. Being able to use our native language (C#) to build out the data model is a massive productivity boost.</p><h3>3. Asymmetry</h3><p>As stated earlier, Queries will slant toward CRUD reads and bypass the domain layer more often than not (with a few notable exceptions). Commands will slant toward using the Domain layer for validation and orchestration of business logic (with notable exceptions as well). This is simply the nature of the beast for most software applications. The <a href="https://en.wikipedia.org/wiki/Pareto_principle">Pareto Principle</a> (80/20 Rule) often applies to each.</p><h3>4. Questions to Ask Oneself</h3><p>Here are a few questions you might want to keep in mind when determining the appropriateness of any of the following patterns:</p><ul><li>Is this a high-level Read (Query) or Write (Command) operation?</li><li>Does it require complex validation, business rule enforcement, or data aggregation?</li><li>Is it dependent upon persisted state in the underlying data store?</li><li>Will it be called frequently? Is there a need for performance?</li></ul><h3>The Patterns</h3><p>Here I present the patterns, categorized into four different categories: A, B, C, and D. The categories are presented in order of hypothetical preponderance — with the most common appearing first. Where applicable, I also list workflow examples from the demo application and code samples, if possible.</p><h3>Category A — CRUD Read Patterns</h3><h4>A1: CRUD Read Directly From Data Store</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/0*7N-QMwFi5ZdZnyQu.png" /></figure><p>Description: Fast CRUD read having no dependency on Domain concerns, and with a heavy bias toward Presentation (View Model) or more uncommonly, Identity Model. As stated earlier, most Queries will resemble this.</p><p>Preponderance: Approximately 80% of Queries.</p><p>Persistence Frameworks Used: Dapper.</p><p>Workflow Examples:</p><ul><li>GetCustomer</li><li>GetCustomerId</li><li>GetTenantsForCustomer</li><li>GetEmployee</li><li>GetEmployeeList</li><li>GetEmployeeOrgChart</li><li>GetPaidTimeOffPolicyDetail</li><li>GetPaidTimeOffPolicyList</li><li>GetAuthorizedTenantsForUser</li><li>GetTenant</li><li>GetTenantEmployeesForUser</li><li>GetTenantIdFromAssignmentKey</li><li>GetTenantIdFromSlug</li><li>GetUserHasTenantAccess</li><li>GetUserStatus</li></ul><p>Code Sample:</p><pre>public class GetUserStatusQueryHandler : IRequestHandler&lt;GetUserStatusQuery, UserStatusViewModel&gt;<br>{<br>    private readonly IApplicationReadDbFacade facade;<br>    public GetUserStatusQueryHandler(IApplicationReadDbFacade facade) =&gt; this.facade = facade ?? throw new ArgumentNullException(nameof(facade));<br>    public async Task&lt;UserStatusViewModel&gt; Handle(GetUserStatusQuery request, CancellationToken cancellationToken)<br>    {<br>        var userStatus = await facade.QueryFirstOrDefaultAsync&lt;UserStatusViewModel&gt;(@&quot;<br>				SELECT TOP 1<br>                    u.IsCustomer,<br>                    c.Id CustomerId,<br>	                CASE WHEN c.Id IS NULL THEN 0 ELSE 1 END HasProvidedCustomerInformation,<br>	                CASE WHEN e.Id IS NULL THEN 0 ELSE 1 END HasProvidedEmployeeInformation<br>                FROM AspNetUsers u WITH(NOLOCK)<br>                LEFT JOIN Customers c WITH(NOLOCK) ON c.AspNetUsersId = u.Id<br>                LEFT JOIN Employees e WITH(NOLOCK) ON e.AspNetUsersId = u.Id AND (@TenantId IS NULL OR e.TenantId = @TenantId)<br>                WHERE u.Id = @AspNetUsersId<br>            &quot;, request, cancellationToken: cancellationToken);<br>        userStatus.AuthorizedTenants = (await facade.QueryAsync&lt;int&gt;(&quot;SELECT TenantId FROM TenantAspNetUsers t WITH(NOLOCK) WHERE AspNetUsersId = @AspNetUsersId&quot;, request, cancellationToken: cancellationToken)).ToArray();<br>        return userStatus;<br>    }<br>}</pre><h4>A2: CRUD Read Via Persistence Entities</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/0*O5_H9RJbxfCrJTeD.png" /></figure><p>Description: Infrequent read operations which may or may not benefit from the fluency of LINQ that Entity Framework provides, or Persistence entities may be hydrated directly using Dapper. Little to no need to project to complex, composite View Models, etc.</p><p>Preponderance: Less than 10–20% of Queries.</p><p>Persistence Frameworks Used: Entity Framework Core and/or Dapper.</p><p>Workflow Examples:</p><ul><li>GetPaidTimeOffRequestsForEmployee</li></ul><p>Code Sample:</p><pre>public class GetPaidTimeOffRequestsForEmployeeQueryHandler : IRequestHandler&lt;GetPaidTimeOffRequestsForEmployeeQuery, PaidTimeOffRequestViewModel[]&gt;<br>{<br>    private readonly IApplicationWriteDbContext context;</pre><pre>    private readonly IDbEntityToViewModelMapper&lt;PaidTimeOffRequestEntity, PaidTimeOffRequestViewModel&gt; mapper;</pre><pre>    public GetPaidTimeOffRequestsForEmployeeQueryHandler(IApplicationWriteDbContext context, IDbEntityToViewModelMapper&lt;PaidTimeOffRequestEntity, PaidTimeOffRequestViewModel&gt; mapper)<br>    {<br>        this.context = context ?? throw new ArgumentNullException(nameof(context));<br>        this.mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));<br>    }</pre><pre>    public async Task&lt;PaidTimeOffRequestViewModel[]&gt; Handle(GetPaidTimeOffRequestsForEmployeeQuery request, CancellationToken cancellationToken)<br>    {<br>        // PERSISTENCE LAYER<br>        var employee = request.EmployeeId != null ?<br>            await context.Employees.Include(e =&gt; e.ForPaidTimeOffRequests).FirstOrDefaultAsync(e =&gt; e.Id == (int)request.EmployeeId &amp;&amp; e.TenantId == request.TenantId) :<br>            context.Employees.Include(e =&gt; e.ForPaidTimeOffRequests).FirstOrDefault(e =&gt; e.AspNetUsersId == request.AspNetUsersId) ??<br>            throw new NotFoundException(&quot;Invalid employee ID or ASP.NET user ID specified.&quot;);</pre><pre>        // PRESENTATION LAYER<br>        var vms = (from req in employee.ForPaidTimeOffRequests.OrderBy(r =&gt; r.StartDate) select mapper.Map(req)).ToArray();<br>        return vms;<br>    }<br>}</pre><h3>Category B — Domain-Mediated Write Patterns</h3><h4>B1: Domain-Mediated Write With Entity Hydration From Data Store</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/0*McWKrechQQqzHJ99.png" /></figure><p>Description: Perhaps the most common of Domain-centric write patterns. Persistence entities are hydrated (read) from the underlying data store to facilitate orchestration of a complex write operation. Business logic-heavy operations will tend to resemble this, as it is necessary to retrieve persisted state to perform necessary computations. For example, it would be necessary to retrieve paid time off requests for an employee to calculate whether a pending request is valid, would overlap with another pending request, etc. The complexity of these types of operation will tend to lean toward the use of Entity Framework Core, with Dapper as a handy fallback.</p><p>Preponderance: Approximately 50–80% of Commands.</p><p>Persistence Frameworks Used: Entity Framework Core and/or Dapper.</p><p>Workflow Examples:</p><ul><li>AddOrUpdateEmployee</li><li>SubmitNewPaidTimeOffRequest</li></ul><p>Code Samples (GitHub):</p><ul><li><a href="https://github.com/JacobsDataSolutions/OrgManager/blob/7123340a280616010e09d3d1ef41f589756a2c5c/JDS.OrgManager/JDS.OrgManager.Application/HumanResources/Employees/Commands/AddOrUpdateEmployee/AddOrUpdateEmployeeCommand.cs">AddOrUpdateEmployeeCommand</a></li><li><a href="https://github.com/JacobsDataSolutions/OrgManager/blob/7123340a280616010e09d3d1ef41f589756a2c5c/JDS.OrgManager/JDS.OrgManager.Application/HumanResources/TimeOff/Commands/SubmitNewPaidTimeOffRequest/SubmitNewPaidTimeOffRequestCommand.cs">SubmitNewPaidTimeOffCommand</a></li></ul><h4>B2: Domain-Mediated Write Without Entity Hydration From Data Store</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*1qxeSzVSWKijhXUB.png" /></figure><p>Description: Validation or business logic-heavy operations are performed that have no particular dependency on persisted state. Persistence entities are used to help in the orchestration. I would regard this as a rare pattern in the wild.</p><p>Preponderance: Less than 10% of Commands.</p><p>Persistence Frameworks Used: Entity Framework Core and/or Dapper.</p><h4>B3: Domain-Mediated Write Without Entity Hydration, Directly To Data Store</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*QNtO1iv0k_acp4PJ.png" /></figure><p>Description: Much like Pattern B2, validation or business logic-heavy operations are performed that have no particular dependency on persisted state. Rather than use Persistence entities, state is persisted directly to the database, thus achieving a performance benefit and possibly simpler code.</p><p>Preponderance: Less than 10% of Commands.</p><p>Persistence Frameworks Used: Dapper.</p><h3>Category C — CRUD Write Patterns</h3><h4>C1: CRUD Write</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/0*NGvIxbF5q1TN-9G9.png" /></figure><p>Description: Just because we’re building enterprise business applications does not mean that EVERY write operation is subject to business rule validation or otherwise has to pass through the Domain layer. In fact, there are many situations in which it doesn’t make any sense to do so. Remember what I said earlier about Bruce Lee and Jeet Kune Do?</p><blockquote><em>“Having </em>totality<em> means being capable of following “what is,” because “what is” is constantly moving and constantly changing. If one is anchored to a particular view, one will not be able to follow the swift movement of “what is.”</em></blockquote><blockquote><em>― Bruce Lee, Tao of Jeet Kune Do</em></blockquote><p>Various subsystems or areas of the application will tend toward CRUD data input, add/update semantics, etc. and that’s perfectly OK. When it seems logical to do so, we may employ a pattern like this, either with or without Entity Framework Core, to perform database updates.</p><p>Preponderance: Approximately 20–50% of Commands.</p><p>Persistence Frameworks Used: Entity Framework Core and/or Dapper.</p><p>Workflow Examples:</p><ul><li>AddOrUpdateCustomer</li><li>AddOrUpdateTenant</li><li>ProvisionTenant</li><li>SeedInitialData</li></ul><p>Code Sample:</p><pre>public class AddOrUpdateCustomerCommandHandler : IRequestHandler&lt;AddOrUpdateCustomerCommand, CustomerViewModel&gt;<br>{<br>    private readonly IApplicationWriteDbContext context;<br>    private readonly IViewModelToDbEntityMapper&lt;CustomerViewModel, CustomerEntity&gt; customerMapper;<br>    public AddOrUpdateCustomerCommandHandler(<br>        IApplicationWriteDbContext context,<br>        IViewModelToDbEntityMapper&lt;CustomerViewModel, CustomerEntity&gt; customerMapper<br>        )<br>    {<br>        this.context = context ?? throw new ArgumentNullException(nameof(context));<br>        this.customerMapper = customerMapper ?? throw new ArgumentNullException(nameof(customerMapper));<br>    }</pre><pre>    public async Task&lt;CustomerViewModel&gt; Handle(AddOrUpdateCustomerCommand request, CancellationToken cancellationToken)<br>    {<br>        // PRESENTATION/APPLICATION LAYER<br>        var customerViewModel = request.Customer;</pre><pre>        // PERSISTENCE LAYER<br>        var customerAdded = false;<br>        using (var transaction = await context.Database.BeginTransactionAsync(cancellationToken))<br>        {<br>            var sqlTransaction = transaction.GetDbTransaction();<br>            var customerEntity = await context.Customers.AsNoTracking().FirstOrDefaultAsync(c =&gt; c.AspNetUsersId == request.AspNetUsersId, cancellationToken: cancellationToken);<br>            if (customerEntity != null)<br>            {<br>                // Update.<br>                customerMapper.Map(customerViewModel, customerEntity);<br>            }<br>            else<br>            {<br>                // Add.<br>                customerEntity = customerMapper.Map(customerViewModel);<br>                customerAdded = true;<br>            }<br>            customerEntity.AspNetUsersId = request.AspNetUsersId;<br>            await context.Customers.AddAsync(customerEntity, cancellationToken);<br>            context.Entry(customerEntity).State = customerAdded ? EntityState.Added : EntityState.Modified;</pre><pre>            await context.SaveChangesAsync(cancellationToken);<br>            await transaction.CommitAsync(cancellationToken);<br>        }<br>        return customerViewModel;<br>    }<br>}</pre><h4>C2: CRUD Write Directly To Data Store</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/0*mh8Zl2MKpxPqIZue.png" /></figure><p>Description: Like in the previous pattern, we are doing CRUD write operations directly to the database. What’s different in this pattern is that both the Domain and Persistence layers are bypassed. This is useful for fast or sweeping changes to the data model, like simple updates or hard deletion. Since Persistence entities aren’t used, this precludes using Entity Framework Core, and we use Dapper instead to do the job.</p><p>Preponderance: Approximately 20–50% of Commands.</p><p>Persistence Frameworks Used: Dapper.</p><p>Workflow Examples:</p><ul><li>ClearTables</li><li>DeleteTenant</li></ul><p>Code Sample:</p><pre>public class DeleteTenantCommand : IRequest&lt;DeleteTenantViewModel&gt;<br>{<br>    public DeleteTenantViewModel DeleteTenant { get; set; } = default!;</pre><pre>    public class DeleteTenantCommandHandler : IRequestHandler&lt;DeleteTenantCommand, DeleteTenantViewModel&gt;<br>    {<br>        private readonly IApplicationWriteDbContext context;</pre><pre>        private readonly IApplicationWriteDbFacade facade;</pre><pre>        public DeleteTenantCommandHandler(IApplicationWriteDbFacade facade, IApplicationWriteDbContext context)<br>        {<br>            this.facade = facade ?? throw new ArgumentNullException(nameof(facade));<br>            this.context = context ?? throw new ArgumentNullException(nameof(context));<br>        }</pre><pre>        public async Task&lt;DeleteTenantViewModel&gt; Handle(DeleteTenantCommand request, CancellationToken cancellationToken)<br>        {<br>            var tenantViewModel = request.DeleteTenant;<br>            var tenantName = await facade.QueryFirstOrDefaultAsync&lt;string&gt;(@&quot;SELECT TOP 1 Name From Tenants WITH(NOLOCK) WHERE Id = @TenantId&quot;, tenantViewModel);<br>            if (tenantName.ToUpper() != tenantViewModel.ConfirmationCode.ToUpper())<br>            {<br>                throw new ApplicationLayerException(&quot;Invalid confirmation provided for delete tenant command.&quot;);<br>            }</pre><pre>            using (var transaction = await context.Database.BeginTransactionAsync())<br>            {<br>                var sqlTransaction = transaction.GetDbTransaction();<br>                await facade.ExecuteAsync(<br>                    string.Join(&quot;\r\n&quot;, from t in facade.GetTenantTables() select $&quot;DELETE FROM {t} WHERE TenantId = @TenantId&quot;)<br>                    + &quot;\r\nDELETE FROM Tenants WHERE Id = @TenantId&quot;, tenantViewModel, sqlTransaction);<br>                await transaction.CommitAsync();<br>            }<br>            return tenantViewModel;<br>        }<br>    }<br>}</pre><h3>Category D — Domain-Mediated Read Patterns</h3><h4>D1: Domain-Mediated Read Via Persistence Entities</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*Up02XCqsCLByahBL.png" /></figure><p>Description: While not as common as CRUD read operations, there may be situations in which it makes sense to perform complex orchestrations which depend upon Domain logic. A good example would be reporting. Entity Framework Core is great under these conditions since the fluency of LINQ can be useful for representing data projections, transformations, and the like.</p><p>Preponderance: At most 20% of Queries.</p><p>Persistence Frameworks Used: Entity Framework Core and/or Dapper.</p><p>Workflow Examples:</p><ul><li>GetPaidTimeOffRequestsForTenant</li><li>VerifyOrganization</li></ul><p>Code Sample:</p><pre>public class GetPaidTimeOffRequestsForTenantQuery : IRequest&lt;PaidTimeOffRequestViewModel[]&gt;<br>{<br>    public int TenantId { get; set; }<br>    public class GetPaidTimeOffRequestsForTenantQueryHandler : IRequestHandler&lt;GetPaidTimeOffRequestsForTenantQuery, PaidTimeOffRequestViewModel[]&gt;<br>    {<br>        private readonly IApplicationWriteDbContext context;<br>        private readonly IDbEntityToDomainEntityMapper&lt;PaidTimeOffRequestEntity, PaidTimeOffRequest&gt; dbEntityMapper;<br>        private readonly IDomainEntityToViewModelMapper&lt;PaidTimeOffRequest, PaidTimeOffRequestViewModel&gt; domainEntityMapper;<br>        private readonly PaidTimeOffRequestService paidTimeOffRequestService;</pre><pre>        public GetPaidTimeOffRequestsForTenantQueryHandler(<br>            IApplicationWriteDbContext context,<br>            PaidTimeOffRequestService paidTimeOffRequestService,<br>            IDbEntityToDomainEntityMapper&lt;PaidTimeOffRequestEntity, PaidTimeOffRequest&gt; dbEntityMapper,<br>            IDomainEntityToViewModelMapper&lt;PaidTimeOffRequest, PaidTimeOffRequestViewModel&gt; domainEntityMapper<br>            )<br>        {<br>            this.context = context ?? throw new ArgumentNullException(nameof(context));<br>            this.paidTimeOffRequestService = paidTimeOffRequestService ?? throw new ArgumentNullException(nameof(paidTimeOffRequestService));<br>            this.dbEntityMapper = dbEntityMapper ?? throw new ArgumentNullException(nameof(dbEntityMapper));<br>            this.domainEntityMapper = domainEntityMapper ?? throw new ArgumentNullException(nameof(domainEntityMapper));<br>        }</pre><pre>        public Task&lt;PaidTimeOffRequestViewModel[]&gt; Handle(GetPaidTimeOffRequestsForTenantQuery request, CancellationToken cancellationToken)<br>        {<br>            // PERSISTENCE<br>            var tenantRequestEntities = (from r in context.PaidTimeOffRequests where r.TenantId == request.TenantId select r).ToList();</pre><pre>            // DOMAIN<br>            var paidTimeOffRequests = (from r in tenantRequestEntities select dbEntityMapper.Map(r)).ToList();<br>            paidTimeOffRequests = paidTimeOffRequestService.GetPaidTimeOffRequestsWithStatusUpdates(paidTimeOffRequests, DateTime.Today);</pre><pre>            return Task.FromResult((from r in paidTimeOffRequests select domainEntityMapper.Map(r)).ToArray());<br>        }<br>    }<br>}</pre><h4>D2: Domain-Mediated Read Directly From Data Store</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/0*gOd9XHv4hvUuBZoj.png" /></figure><p>Description: Dapper is used to directly hydrate Domain entities, which are then immediately used for business logic or validation. This pattern is useful for fast validation logic, such as reacting to user input when filling in form information, typeahead logic, etc. In the demo application, I’ve created a Reactive forms validator that examines three different controls — start date, end date, and hours requested — for when an employee is requesting time off.</p><p>Preponderance: At most 20% of Queries.</p><p>Persistence Frameworks Used: Dapper.</p><p>Workflow Examples:</p><ul><li>ValidateRequestedPaidTimeOffHours</li></ul><p>Code Samples:</p><p>On the API side…</p><pre>public class ValidateRequestedPaidTimeOffHoursQueryHandler : IRequestHandler&lt;ValidateRequestedPaidTimeOffHoursQuery, PaidTimeOffRequestValidationResult&gt;<br>{<br>    private readonly IApplicationReadDbFacade facade;<br>    private readonly IViewModelToDomainEntityMapper&lt;ValidateRequestedPaidTimeOffHoursViewModel, PaidTimeOffRequest&gt; mapper;<br>    private readonly PaidTimeOffRequestService paidTimeOffRequestService;</pre><pre>    public ValidateRequestedPaidTimeOffHoursQueryHandler(<br>        IApplicationReadDbFacade facade,<br>        PaidTimeOffRequestService paidTimeOffRequestService,<br>        IViewModelToDomainEntityMapper&lt;ValidateRequestedPaidTimeOffHoursViewModel, PaidTimeOffRequest&gt; mapper)<br>    {<br>        this.facade = facade ?? throw new ArgumentNullException(nameof(facade));<br>        this.paidTimeOffRequestService = paidTimeOffRequestService ?? throw new ArgumentNullException(nameof(paidTimeOffRequestService));<br>        this.mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));<br>    }</pre><pre>    public async Task&lt;PaidTimeOffRequestValidationResult&gt; Handle(ValidateRequestedPaidTimeOffHoursQuery request, CancellationToken cancellationToken)<br>    {<br>        var viewModel = request.ValidationRequest;<br>        var tentativeRequest = mapper.Map(viewModel);<br>        var today = DateTime.Today;<br>        var parms = new { request.AspNetUsersId, viewModel.EndDate, viewModel.StartDate, viewModel.ForEmployeeId, viewModel.HoursRequested, viewModel.TenantId };</pre><pre>        // TODO: add domain validation/authorization if submitting on behalf of another employee (i.e. manager is submitting).<br>        var paidTimeOffPolicy = await facade.QueryFirstOrDefaultAsync&lt;PaidTimeOffPolicy&gt;(@&quot;<br>            SELECT TOP 1 p.[Id]<br>                    ,p.[AllowsUnlimitedPto]<br>                    ,p.[EmployeeLevel]<br>                    ,p.[IsDefaultForEmployeeLevel]<br>                    ,p.[MaxPtoHours]<br>                    ,p.[Name]<br>                    ,p.[PtoAccrualRate]<br>                FROM PaidTimeOffPolicies p WITH(NOLOCK)<br>                JOIN Employees e WITH(NOLOCK) ON e.PaidTimeOffPolicyId = p.Id AND e.TenantId = p.TenantId<br>                WHERE ((@ForEmployeeId IS NULL AND e.AspNetUsersId = @AspNetUsersId) OR e.Id = @ForEmployeeId) AND e.TenantId = @TenantId<br>        &quot;, parms, cancellationToken: cancellationToken);<br>        if (paidTimeOffPolicy == null)<br>        {<br>            throw new NotFoundException(&quot;PTO policy not found or invalid.&quot;);<br>        }<br>        var existingRequests = await facade.QueryAsync&lt;PaidTimeOffRequest&gt;(@&quot;<br>            SELECT p.[Id]<br>                    ,p.[ApprovalStatus]<br>                    ,p.[EndDate]<br>                    ,p.[ForEmployeeId]<br>                    ,p.[HoursRequested]<br>                    ,p.[StartDate]<br>                    ,p.[Paid]<br>                    ,p.[SubmittedById]<br>                FROM [PaidTimeOffRequests] p WITH(NOLOCK)<br>                JOIN Employees e WITH(NOLOCK) ON e.Id = p.ForEmployeeId AND e.TenantId = p.TenantId<br>                WHERE ((@ForEmployeeId IS NULL AND e.AspNetUsersId = @AspNetUsersId) OR e.Id = @ForEmployeeId) AND e.TenantId = @TenantId<br>        &quot;, parms, cancellationToken: cancellationToken);</pre><pre>        return paidTimeOffRequestService.ValidatePaidTimeOffRequest(tentativeRequest, existingRequests, paidTimeOffPolicy, today);<br>    }<br>}</pre><p>On the UI side…</p><pre>form = this.fb.group(<br>    {<br>        startDate: [undefined, [Validators.required]],<br>        endDate: [undefined, [Validators.required]],<br>        forEmployeeId: [undefined, []],<br>        hoursRequested: [0, []],<br>        result: [PaidTimeOffRequestValidationResult.OK, []],<br>        tenantId: [0, []]<br>    },<br>    { asyncValidator: requestedPaidTimeOffHoursValidator(this.timeOffClient, this.ngUnsubscribe) }<br>);<br>...<br>export function getErrorMessageFromPtoRequestValidationResult(result: PaidTimeOffRequestValidationResult): string {<br>    let msg = &quot;&quot;;<br>    switch (result) {<br>        case PaidTimeOffRequestValidationResult.NotEnoughHours:<br>            msg = &quot;Not enough time accrued.&quot;;<br>            break;<br>        case PaidTimeOffRequestValidationResult.OverlapsWithExisting:<br>            msg = &quot;Overlaps with an existing PTO request.&quot;;<br>            break;<br>        case PaidTimeOffRequestValidationResult.InThePast:<br>            msg = &quot;Cannot be in the past.&quot;;<br>            break;<br>        case PaidTimeOffRequestValidationResult.TooFarInTheFuture:<br>            msg = &quot;Too far into the future.&quot;;<br>            break;<br>        case PaidTimeOffRequestValidationResult.StartDateAfterEndDate:<br>            msg = &quot;Start date must be before end date.&quot;;<br>            break;<br>        case PaidTimeOffRequestValidationResult.OK:<br>            return null;<br>    }<br>    return msg;<br>}</pre><pre>export function requestedPaidTimeOffHoursValidator(timeOffClient: TimeOffClient, ngUnsubscribe: Subject&lt;unknown&gt;): AsyncValidatorFn {<br>    return (control: AbstractControl): Promise&lt;{ [key: string]: any } | null&gt; | Observable&lt;{ [key: string]: any } | null&gt; =&gt; {<br>        if (isEmptyInputValue(control.value)) {<br>            return of(null);<br>        } else {<br>            // control is a reference to the whole form.<br>            return control.valueChanges.pipe(<br>                debounceTime(500),<br>                take(1),<br>                switchMap((_) =&gt; {<br>                    const viewModel = new ValidateRequestedPaidTimeOffHoursViewModel();<br>                    viewModel.init(control.value);<br>                    if (viewModel.hoursRequested &amp;&amp; viewModel.startDate &amp;&amp; viewModel.endDate) {<br>                        return timeOffClient.validateRequestedPaidTimeOffHours(viewModel).pipe(<br>                            map((result: PaidTimeOffRequestValidationResult) =&gt; {<br>                                const msg = getErrorMessageFromPtoRequestValidationResult(result);<br>                                return !!msg ? { invalid: { message: msg } } : null;<br>                            }),<br>                            takeUntil(ngUnsubscribe)<br>                        );<br>                    }<br>                    return of(null);<br>                })<br>            );<br>        }<br>    };<br>}</pre><h4>D3: Domain-Mediated Read Without Any Data Store Interaction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/0*94Zo2Q5ur1i5IKp9.png" /></figure><p>Description: Sometimes it makes sense to have the UI call API routines which are not dependent upon any particular state, and therefore should not interact with the database. This could be a good approach to keep complex business logic out of the UI (where it doesn’t belong anyway), thereby reducing the size of the UI bundle delivered to the user’s browser. Additionally, using server-side technologies like C#, F#, LINQ, etc. allows for a more elegant solution. Or, perhaps that logic is sensitive and it makes sense to keep it on the server. Remember that anything happening inside the user’s browser should not be trusted.</p><p>Preponderance: Likely less than 5–10% of Queries.</p><p>Persistence Frameworks Used: None.</p><p>Workflow Examples:</p><ul><li>GetNewAssignmentKey</li></ul><p>Code Sample (this is admittedly a trivial example):</p><pre>public class GetNewAssignmentKeyQueryHandler : IRequestHandler&lt;GetNewAssignmentKeyQuery, Guid&gt;<br>{<br>    public Task&lt;Guid&gt; Handle(GetNewAssignmentKeyQuery request, CancellationToken cancellationToken) =&gt; Task.FromResult(Guid.NewGuid());<br>}</pre><h3>Conclusion</h3><p>I started by waxing philosophical, mentioning the book The Tao of Jeet Kune Do by Bruce Lee, and how its concepts are surprisingly relatable to software development. Specifically, I talked about how the code-level and architectural design patterns which we employ in the art of software development should flow naturally, non-dogmatically, and how we should be open to employing different approaches as the problem at hand warrants. I discussed a series of architectural patterns that seem to emerge when doing CQRS with Clean DDD, though neither of those is mandatory to use the patterns. I brought up basic guidelines for the application of those patterns, and considerations for deciding when one may or may not be appropriate for a given situation. Finally, I presented the patterns themselves, offering up suggestions for scenarios in which they could be useful.</p><h3>A Final Word From The Legend</h3><blockquote><em>“Set patterns, incapable of adaptability, of pliability, only offer a better cage. Truth is outside of all patterns.”</em></blockquote><blockquote><em>― Bruce Lee, Tao of Jeet Kune Do</em></blockquote><h3>Experts / Authorities / Resources</h3><h3>Bruce Lee</h3><ul><li><a href="https://bookshop.org/books/tao-of-jeet-kune-do/9780897502023">Tao of Jeet Kune Do</a> (Classic book on Eastern philosophy and martial arts)</li></ul><h3>Wikipedia</h3><ul><li><a href="https://en.wikipedia.org/wiki/Pareto_principle">Pareto Principle</a></li></ul><h3>Persistence Tools</h3><ul><li><a href="https://stackexchange.github.io/Dapper/">Dapper</a></li><li><a href="https://docs.microsoft.com/en-us/ef/core/">Entity Framework Core</a></li></ul><p>This is entry #6 in the <a href="https://blog.jacobsdata.com/category/scaffold%20clean%20ddd%20web%20app">Scaffold Your Clean DDD Web App Series</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=350085c53e5f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-alchemy/domain-driven-design-workflow-patterns-350085c53e5f">Domain-Driven Design Workflow Patterns</a> was originally published in <a href="https://medium.com/software-alchemy">Software Alchemy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain-Driven Design Entity Mapping Strategies]]></title>
            <link>https://medium.com/software-alchemy/domain-driven-design-entity-mapping-strategies-7c94183acd02?source=rss-a80f78e022fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c94183acd02</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Jacobs Data Solutions]]></dc:creator>
            <pubDate>Mon, 22 Mar 2021 03:46:28 GMT</pubDate>
            <atom:updated>2021-03-22T03:46:28.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*7fTEtgGrjTCl10te.jpg" /></figure><p>Image by <a href="https://pixabay.com/users/geralt-9301/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2496193">Gerd Altmann</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2496193">Pixabay</a></p><h3>Introduction</h3><p>Previously, I discussed a cross-stack methodology for persisting exception information from deep within the server-side application to the UI app running in the user’s browser. In this story, we’re going to circle back and discuss the importance of keeping a separation between various entity types within a DDD application, the challenges that presents, and elegant mapping strategies we can use to make it work. First, however, I’m going to briefly touch on some key enhancements to the C# language that were released with version 9, and how those influence our architecture from a Domain-Driven Design perspective. Alongside the blog entry in which I laid out my <a href="https://blog.jacobsdata.com/2020/03/02/a-clean-domain-driven-design-architectural-template">Clean DDD architectural template</a> in detail, this is one of the most important that I’ve written to date, so I hope you enjoy it and find the knowledge from this to be useful.</p><h3>C# 9 Enhancements — The F#-ification Continues…</h3><p>Having been programming F# for nearly a decade now, I find it amusing, though at times unnerving, how more and more features from F# end up in each new release of C#. Sometimes these features smoothly transition over, though (as with switch expressions and their F# counterpart, match expressions) this is not always the case. I’ll definitely comment more in the future. However, suffice it to say, the new features of C# 9 will impact our DDD implementation.</p><h3>Records as Value Objects</h3><p>I plan to go into more detail in a later blog entry on the nuances of <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#record-types">C# records</a>, and how they square up against F# records, which have been canonical in that language since the beginning. However, at this time I will simply state that, for the purposes of the demo application, I chose to reimplement the Value Object classes as records. Please note that this is at odds with the recommendations of other DDD authorities that I follow, such as Vladimir Khorikov, who gives good reasons in <a href="https://enterprisecraftsmanship.com/posts/csharp-records-value-objects/">this blog entry</a> why records are NOT well-suited to Value Object implementations.</p><p>Once I figured out how the new record types work in C#, the carrot was simply too tempting for me to resist, knowing that I could turn this…</p><pre>public class Address : ValueObject<br>{<br>    public string City { get; }<br>    public State State { get; }<br>    public string Street1 { get; }<br>    public string Street2 { get; }<br>    public ZipCode Zip { get; }</pre><pre>    public Address(string street1, string city, State state, ZipCode zip, string street2 = null)<br>    {<br>        Street1 = street1 ?? throw new ArgumentNullException(nameof(street1));<br>        City = city ?? throw new ArgumentNullException(nameof(city));<br>        State = state ?? throw new ArgumentNullException(nameof(state));<br>        Zip = zip ?? throw new ArgumentNullException(nameof(zip));<br>        Street2 = string.IsNullOrWhiteSpace(street2) ? &quot;&quot; : street2;<br>    }</pre><pre>    public override string ToString()<br>    {<br>        var apt = !string.IsNullOrWhiteSpace(Street2) ? &quot; &quot; + Street2 : &quot;&quot;;<br>        return $&quot;{Street1}{apt}, {City}, {State} {Zip}&quot;;<br>    }</pre><pre>    protected override IEnumerable&lt;object&gt; GetAtomicValues()<br>    {<br>        yield return Street1;<br>        yield return Street2;<br>        yield return City;<br>        yield return State;<br>        yield return Zip;<br>    }<br>}</pre><p>… into this:</p><pre>public record Address(string Street1, string City, State State, ZipCode ZipCode, string? Street2 = default) : IValueObject<br>{<br>    public override string ToString()<br>    {<br>        var apt = !string.IsNullOrWhiteSpace(Street2) ? &quot; &quot; + Street2 : &quot;&quot;;<br>        return $&quot;{Street1}{apt}, {City}, {State} {ZipCode}&quot;;<br>    }<br>}</pre><p>If this turns out to be a misguided decision, then we can always <strong>pivot</strong> back to a base class implementation, like what was in place earlier. That’s the beauty of software architecture, as opposed to real life, building architecture — in the software world, the “bricks” don’t cost anything. You must simply be mindful of your time, and if you screw up, learn from your mistake and then change course quickly.</p><h3>Init-Only Setters</h3><p>Another C# 9 feature that was released alongside records is <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#init-only-setters">init-only setters</a>. In my opinion, this feature has been needed for a while, and once I started using it, it felt like a breath of fresh air. Why? Because it allows us to more elegantly declare Domain entity types that are inherently immutable, without needing to lean on constructors for property initialization.</p><p>Let’s examine the code of a previous version of one of our Domain entity classes, which I personally find kind of smelly.</p><pre>public class PaidTimeOffPolicy : DomainEntity&lt;PaidTimeOffPolicy&gt;<br>{<br>    public bool AllowsUnlimitedPto { get; private set; }<br>    public int EmployeeLevel { get; private set; }<br>    public bool IsDefaultForEmployeeLevel { get; private set; }<br>    public decimal? MaxPtoHours { get; private set; }<br>    public string Name { get; private set; }<br>    public decimal? PtoAccrualRate { get; private set; }</pre><pre>    public PaidTimeOffPolicy()<br>    { }</pre><pre>    public PaidTimeOffPolicy(bool allowsUnlimitedPto, int employeeLevel, bool isDefaultForEmployeeLevel, decimal? maxPtoHours, string name, decimal? ptoAccruralRate)<br>    {<br>        if (employeeLevel &lt; 1)<br>        {<br>            throw new ArgumentOutOfRangeException(nameof(employeeLevel));<br>        }<br>        if (!allowsUnlimitedPto &amp;&amp; (maxPtoHours == null || ptoAccruralRate == null))<br>        {<br>            throw new PaidTimeOffException($&quot;Invalid PTO policy. If policy does not specify unlimited hours, then you must specify both max PTO hours and PTO accrual rate.&quot;);<br>        }<br>        if (string.IsNullOrWhiteSpace(name))<br>        {<br>            throw new ArgumentNullException(nameof(name));<br>        }<br>        AllowsUnlimitedPto = allowsUnlimitedPto;<br>        EmployeeLevel = employeeLevel;<br>        MaxPtoHours = allowsUnlimitedPto ? null : maxPtoHours;<br>        PtoAccrualRate = allowsUnlimitedPto ? null : ptoAccruralRate;<br>        Name = name;<br>        IsDefaultForEmployeeLevel = isDefaultForEmployeeLevel;<br>    }<br>}</pre><p>What stands out here?</p><ul><li>It has an empty constructor, which is needed to allow mapping tools like Mapster to do their job.</li><li>It has six parameters in the main constructor, which comes close to violating the “Rule of Seven” (I believe I read about that in <a href="https://www.oreilly.com/library/view/code-complete-second/0735619670/">Code Complete 2</a>, though I’m not 100% sure.)</li><li>It’s doing copious validation in the main constructor, which may or may not be a good practice. At the very least, that validation won’t be executed if an instance of this class is creating using Mapster, or otherwise by calling the empty constructor. Of course, this betrays another design smell, which is failing to consolidate the validation into a single method and call it from multiple places, but I digress…</li><li>It can be moderately to severely hard to maintain, and unit tests might start breaking all over the place, depending on how complex the business logic becomes in the future.</li></ul><p>If only there were a way to use the property initialization syntax that we all have known and loved since version 4, or whenever, combined with immutability… wait, now there is!</p><p>Thank goodness for init-only setters.</p><pre>public class PaidTimeOffPolicy : DomainEntity&lt;PaidTimeOffPolicy&gt;<br>{<br>    public bool AllowsUnlimitedPto { get; init; }<br>    public int EmployeeLevel { get; init; }<br>    public bool IsDefaultForEmployeeLevel { get; init; }<br>    public decimal? MaxPtoHours { get; init; }<br>    public string Name { get; init; } = default!;<br>    public decimal? PtoAccrualRate { get; init; }</pre><pre>    public override void ValidateAggregate()<br>    {<br>        base.ValidateAggregate();<br>        if (EmployeeLevel &lt; 1)<br>        {<br>            throw new PaidTimeOffException(&quot;Invalid employee level for PTO policy.&quot;);<br>        }<br>        if (!AllowsUnlimitedPto &amp;&amp; (MaxPtoHours == null || PtoAccrualRate == null))<br>        {<br>            throw new PaidTimeOffException($&quot;Invalid PTO policy. If policy does not specify unlimited hours, then you must specify both max PTO hours and PTO accrual rate.&quot;);<br>        }<br>        if (string.IsNullOrWhiteSpace(Name))<br>        {<br>            throw new PaidTimeOffException(&quot;Invalid PTO policy name.&quot;);<br>        }<br>    }<br>}</pre><p>Instantiating new Domain entities is now this simple, and the code is more maintainable because we’re not concerned about argument positioning, etc.</p><pre>var p = new PaidTimeOffPolicy<br>{<br>    AllowsUnlimitedPto = true,<br>    EmployeeLevel = 6,<br>    IsDefaultForEmployeeLevel = true,<br>    MaxPtoHours = 55.0m,<br>    Name = &quot;HELLO&quot;,<br>    PtoAccrualRate = 10.0M,<br>    Id = 67<br>};</pre><h3>Immutability is Key</h3><p>Make this into another one of your mantras: “immutability is key.” Note that in my interpretation of Domain-Driven Design (Clean DDD-Jacobs???) this is ONLY applicable to the Domain layer. Why? <strong>Because it is in the Domain layer that we are most concerned with logical code correctness, data validation, and business rules being faithfully implemented in a manner which is intelligible, scalable, and maintainable</strong>… and mutability is anathema to all the above.</p><p>So, let’s reiterate our intent in how we apply this to the two main types of Domain classes:</p><h3>Value Objects</h3><p>These are immutable reference types which have <strong>value semantics</strong> and <strong>structural equality</strong> comparison operations. In other words, they look and behave like classic .NET structs, but they are reference types under the hood. If their constituent properties are equal, then for all intents and purposes two separate Value Objects of the same type may be considered equal. 80% of the time we can probably get away with implementing them using the new C# 9 record types, and for the outliers we may choose to fall back on a ValueObject base class implementation.</p><h3>Domain Entities</h3><p>These are immutable reference types which have <strong>identity semantics</strong> and <strong>reference equality</strong> comparison operations. This means that two Employee objects may have entirely identical property values — First Name, Last Name, SSN — however, we may NOT assume that they philosophically represent the same real-life person (fun fact: in the United States, Social Security numbers are not guaranteed to be unique). As a matter of fact, two Domain entities may represent the same real-life entity (for example, a person) <em>at different points in time</em>, and should therefore be considered distinct for the purposes of our application! Each Domain entity instance has a unique identifier, typically borrowed from the corresponding Persistence entity, which can be used to determine whether two different objects represent the same thing. Combined with a fluent syntax that looks something like this…</p><pre>employee.WithManager(manager);</pre><p>… it becomes possible to create complex aggregates inside workflows, while maintaining the safety of immutability.</p><p>Fortunately, the new C# features — records and init-only setters — which make the above possible, also seem to play nice with <strong>mapping tools</strong> and other <strong>reflection-based techniques</strong>, like the nifty DomainEntity base class helper method you see below (please note that this technique is not future-proof and may break with future versions of the framework):</p><pre>public TEntity ReflectionCloneWith&lt;TProperty&gt;(Expression&lt;Func&lt;TEntity, TProperty&gt;&gt; expr, TProperty value)<br>{<br>    var prop = expr.GetPropertyInfoFromLambda();<br>    var e = CreateShallowCopy();<br>    prop.SetValue(e, value);<br>    return e;<br>}</pre><p>All of this brings us to my main point, and the crux of this blog entry. Why use separate, immutable Domain entity types? Why mapping? Why is all this even necessary? I’m glad you asked.</p><h3>The Design’s Greatest Strength Is Also It’s Greatest Weakness</h3><p>Without getting too far ahead of ourselves — and I will go into this in more detail in the next blog entry — a typical high-level workflow for a complex update operation, such as updating employee information or submitting a PTO request, will look something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*vSqTbRDTL4iF7mju.png" /></figure><p>In a nutshell, we are passing through multiple layers, thereby transforming multiple entity type aggregates <em>in both directions</em>, just to perform a single operation. Furthermore, we may not assume that analogous entity types from each layer may be similar enough to each other that some mapping or translation process isn’t necessary, or that such operations may be trivialized.</p><p>If you’ve followed along with my previous blog entries, then you’ll know that I advocate keeping a clear demarcation between Domain entities and other types of entities in the stack, such as Persistence entities and View Models. This means that when we declare our Persistence entities using Entity Framework, or some other way, we do NOT treat those entities in any way as Domain entities. Note that this flies in the face of the guidance provided by many other experts. However, I’ve both built and maintained countless systems which did not abide by this practice, and every time it’s led to tears and frustration. Again, we’re talking about line-of-business applications, not CRUD. Our intent is to maintain architectural loose coupling between the layers of the system, which promotes scalability and maintainability.</p><p>(I want to mention that in the <a href="https://github.com/JacobsDataSolutions/OrgManager">demo application</a> these Clean DDD workflows are implemented as CQRS Commands/Queries. In the context of this blog entry, I’m not going to assume that you are using CQRS. It’s not a requirement in order to build a Clean DDD solution, and there are other ways you might choose to orchestrate your Domain logic. However, the same principle applies.)</p><p>We’ve established a mandate — make Domain entities the focus of the application and do not reuse them for any other purpose, such as View Models or Persistence entities — yet this is all on paper. In practice it’s actually harder than you might think. By trying to solve one problem, we’ve introduced more complexity into our application. I warned you before that this is perhaps the biggest drawback to my Clean DDD approach. However, it’s possible to minimize the pain of the added complexity, and that’s exactly what I’m going to show you next.</p><h3>Slaying the Hydra</h3><p>Like the <a href="https://en.wikipedia.org/wiki/Lernaean_Hydra">Lernaean Hydra</a> from Greek mythology, often in the software profession we find that in attempting to solve one problem, we end up creating one or more additional problems before coming to a final, workable solution. This is a great example.</p><p>Our ultimate goal is to be able to freely map from View Models to Domain entities to Persistence entities, or any permutation thereof, with minimal headache and without creating any hacky solutions that we might regret later as the solution evolves. I’m going to demonstrate how I solved that problem, and the various secondary problems which arose along the way, so that you can confidently overcome analogous obstacles in your own coding endeavors. Let’s begin.</p><h3>Problem #1: Manually Mapping Between Entities Is Tedious</h3><p>This sucks.</p><pre>var employee = new Employee<br>{<br>    HomeAddress = new Address(employeeViewModel.Address1, employeeViewModel.City, new State(employeeViewModel.State), new ZipCode(employeeViewModel.ZipCode)),<br>    FirstName = employeeViewModel.FirstName,<br>    LastName = employeeViewModel.LastName,<br>	...<br>};</pre><p>What you see above is the naïve approach, and you should avoid it like the plague. Remember: your job as a software professional is to <em>automate</em> solutions to difficult problems, not punch repetitive lines of code into your IDE or cut and paste blocks of logic without a thought as to how difficult it’ll be to maintain. You should strive to <a href="https://blog.jacobsdata.com/2020/01/27/basic-concepts-of-software-design-and-architecture#laying-the-groundwork">think abstractly</a> and whenever possible, make the computer do the repetitive work. Enter, mapper classes.</p><h3>Solution #1: Create Well-Defined Mapper Classes Using a Robust Toolkit Under the Hood</h3><p>At this point many of you are saying “just use AutoMapper or Mapster directly inside your workflows and be done with it!” Not so fast. As the above code illustrates, mapping between fundamentally different entity types, even something as “simple” as an Employee, gets messy quickly. You end up with an overgrowth of complex configurations which may or may not be neatly maintained in a single location, and now your line-of-business code is tightly coupled to a third-party framework. Great, you just poisoned the well you drink from.</p><p>Instead, what we will do to solve this problem is create well-defined mapping interfaces, and corresponding mapper classes which implement them. We then use Dependency Injection to provide the mappers to our workflows.</p><p>The workflows don’t care what’s behind those interfaces. You could be using Mapster, or AutoMapper, or some home brewed reflection-based approach. You could be manually setting properties or using some combination of the above. It doesn’t matter. There is an <strong>implicit code contract</strong> in place stating that the workflows will receive a mapper class instance that will do its job — map one entity type to another. This is the essence of Dependency Injection/Inversion of Control. As a knock-on benefit, the code is easier to understand and vastly more unit testable. Such an implementation may look like this:</p><pre>public class EmployeeViewModelToDomainEntityMapper : IEmployeeViewModelToDomainEntityMapper<br>{<br>    protected TypeAdapterConfig Config { get; init; } = new TypeAdapterConfig();</pre><pre>    public EmployeeViewModelToDomainEntityMapper()<br>    {<br>        Configure(<br>            Config.NewConfig&lt;EmployeeViewModel, Employee&gt;()<br>            .Map(dest =&gt; dest.HomeAddress, src =&gt; new Address(src.Address1, src.City, new State(src.State, &quot;&quot;), new ZipCode(src.ZipCode), src.Address2))<br>            .Map(dest =&gt; dest.Salary, src =&gt; new Money(src.Salary, Currency.GetByCode(src.CurrencyCode)))<br>            // Do NOT deep copy object graphs, with the exception of Value Objects (which have value semantics)<br>            .IgnoreMember((member, side) =&gt; side == MemberSide.Destination &amp;&amp; !(member.Type.IsValueType || typeof(IValueObject).IsAssignableFrom(member.Type) || member.Type == typeof(string)))<br>            );<br>        PerformAdditionalInitialization();<br>    }</pre><pre>    public Employee Map(EmployeeViewModel source) =&gt; source.Adapt&lt;Employee&gt;(Config);</pre><pre>    public void Map(EmployeeViewModel source, Employee destination) =&gt; source.Adapt(destination, typeof(EmployeeViewModel), typeof(Employee), Config);<br>}</pre><p>As you can see, we are not constrained by any third-party tool. We have the capability to use Mapster under the hood, which is obviously what we will choose to do most of the time for productivity’s sake. However, we don’t have to. The details of the mapping process are encapsulated behind the interface.</p><p>We inject the mapper into our CQRS Command handler like so:</p><pre>public AddOrUpdateEmployeeCommandHandler(<br>    IApplicationWriteDbContext context,<br>    IApplicationWriteDbFacade facade,<br>    IEmployeeViewModelToDomainEntityMapper employeeVmToDomainEntityMapper<br>    )<br>{<br>    this.context = context ?? throw new ArgumentNullException(nameof(context));<br>    this.facade = facade ?? throw new ArgumentNullException(nameof(facade));<br>    this.employeeVmToDomainEntityMapper = employeeVmToDomainEntityMapper ?? throw new ArgumentNullException(nameof(employeeVmToDomainEntityMapper));<br>}</pre><p>And we use it like this:</p><pre>public async Task&lt;EmployeeViewModel&gt; Handle(AddOrUpdateEmployeeCommand request, CancellationToken cancellationToken)<br>{<br>    // APPLICATION LAYER<br>    var employeeViewModel = request.Employee;<br>    ... other code<br>    // DOMAIN LAYER<br>    var employee = employeeVmToDomainEntityMapper.Map(employeeViewModel);<br>    ...</pre><p>Seems like a fairly good fix, right? No, there’s a problem. We now must create a separate mapper class to represent each entity relationship, and we are copying over a ton of boilerplate for each one we create. If we want to map from PTO policy View Models to Domain entities, here we go again…</p><pre>public class PaidTimeOffPolicyViewModelToDomainEntityMapper : IPaidTimeOffPolicyViewModelToDomainEntityMapper<br>{<br>    protected TypeAdapterConfig Config { get; init; } = new TypeAdapterConfig();</pre><pre>    public PaidTimeOffPolicyViewModelToDomainEntityMapper()<br>    {<br>        Configure(<br>            Config.NewConfig&lt;PaidTimeOffPolicyViewModel, PaidTimeOffPolicy&gt;()<br>	...</pre><p>We now have a different problem on our hands.</p><h3>Problem #2: Repetitious Mapping Code (Violation of DRY)</h3><p>The above code clearly violates the Don’t Repeat Yourself (DRY) principle. For a solution with just one or two View Model to Domain entity relationships, maybe this would be fine. However, that’s not realistic, and this will not scale. The obvious solution is to fall back on those basic concepts we learned as junior developers — inheritance and encapsulation.</p><h3>Solution #2: Create an Abstract Generic Base Class and Strongly Typed Generic Interfaces to Facilitate Encapsulation</h3><p>The approach to fix this problem is to:</p><ol><li>Maximally reuse code across the mapper classes and</li><li>Avoid having to create superfluous base classes to represent each different kind of relationship (VM-&gt;Domain entity; VM-&gt;Persistence entity; Domain entity-&gt;Persistence entity, etc.)</li></ol><p>We fulfill the first criteria by creating a mapper base class, in combination with the Template Method design pattern; the second, using generics.</p><p>When combined together, we end up with an abstract generic MapperBase&lt;TSource, TDestination&gt; class, from which we will derive all mapper class implementations. That base class looks like this:</p><pre>public abstract class MapperBase<br>{<br>}</pre><pre>public abstract class MapperBase&lt;TSource, TDestination&gt; : MapperBase where TSource : notnull where TDestination : notnull<br>{<br>    protected TypeAdapterConfig Config { get; init; } = new TypeAdapterConfig();</pre><pre>    protected MapperBase()<br>    {<br>        Configure(<br>            Config.NewConfig&lt;TSource, TDestination&gt;()<br>            // Do NOT deep copy object graphs, with the exception of Value Objects (which have value semantics)<br>            .IgnoreMember((member, side) =&gt; side == MemberSide.Destination &amp;&amp; !(member.Type.IsValueType || typeof(IValueObject).IsAssignableFrom(member.Type) || member.Type == typeof(string)))<br>            );<br>        PerformAdditionalInitialization();<br>    }</pre><pre>    public virtual TDestination Map(TSource source) =&gt; source.Adapt&lt;TDestination&gt;(Config);</pre><pre>    public virtual void Map(TSource source, TDestination destination) =&gt; source.Adapt(destination, typeof(TSource), typeof(TDestination), Config);</pre><pre>    public virtual string ToScript(TSource source) =&gt; source.BuildAdapter().CreateMapExpression&lt;TDestination&gt;().ToScript();</pre><pre>    protected virtual TypeAdapterSetter&lt;TSource, TDestination&gt; Configure(TypeAdapterSetter&lt;TSource, TDestination&gt; typeAdapterSetter) =&gt; typeAdapterSetter;</pre><pre>    protected virtual void PerformAdditionalInitialization()<br>    {<br>    }<br>}</pre><p>This is great! There’s no longer a need to copy over boilerplate code across mapper implementations — it’s all encapsulated inside the base class. Along the way, we’ve created generic interfaces to represent all the possible kinds of mapping relationships that will probably come into play, which you can see listed below:</p><pre>IDbEntityToDomainEntityMapper&lt;TSource, TDestination&gt;<br>IDbEntityToValueObjectMapper&lt;TSource, TDestination&gt;<br>IDbEntityToViewModelMapper&lt;TSource, TDestination&gt;<br>IDomainEntityToDbEntityMapper&lt;TSource, TDestination&gt;<br>IDomainEntityToViewModelMapper&lt;TSource, TDestination&gt;<br>IViewModelToDbEntityMapper&lt;TSource, TDestination&gt;<br>IViewModelToDomainEntityMapper&lt;TSource, TDestination&gt;<br>IViewModelToValueObjectMapper&lt;TSource, TDestination&gt;</pre><p>Peeking inside one of them, you’ll see that we’re using generic constraints so that the compiler enforces validity of the relationship (the implicit code contract).</p><pre>public interface IDomainEntityToViewModelMapper&lt;TDomainEntity, TViewModel&gt; where TDomainEntity : IDomainEntity where TViewModel : IViewModel<br>{<br>    TViewModel Map(TDomainEntity source);</pre><pre>    void Map(TDomainEntity source, TViewModel destination);<br>}</pre><p>This way, someone can’t start working on the system and create a “Domain entity to View Model mapper” which actually maps from Domain entities to Persistence entities, or something like that. This is all simply good coding practice.</p><p>Creating a new mapper class, free from repetitive boilerplate, is as easy as this:</p><pre>public class EmployeeDomainEntityToViewModelMapper : MapperBase&lt;Employee, EmployeeViewModel&gt;, IDomainEntityToViewModelMapper&lt;Employee, EmployeeViewModel&gt; { }</pre><p>Any particular mappers that have special requirements are free to override the virtual members of the base class.</p><p>All is not well, though…</p><p>Guess what? Requirements keep pouring in from the business, and now we’ve had to create all of these mapper classes:</p><pre>AddOrUpdateEmployeeDomainEntityToViewModelMapper<br>AddOrUpdateEmployeeViewModelToDbEntityMapper<br>AddOrUpdateEmployeeViewModelToDomainEntityMapper<br>AddressDbEntityToValueObjectMapper<br>AddressViewModelToValueObjectMapper<br>CustomerViewModelToDbEntityMapper<br>EmployeeDbEntityToDomainEntityMapper<br>EmployeeDomainEntityToDbEntityMapper<br>EmployeeDomainEntityToViewModelMapper<br>EmployeeViewModelToDomainEntityMapper<br>PaidTimeOffPolicyDbEntityToDomainEntityMapper<br>PaidTimeOffPolicyDomainEntityToDbEntityMapper<br>PaidTimeOffRequestDbEntityToDomainEntityMapper<br>PaidTimeOffRequestDbEntityToViewModelMapper<br>PaidTimeOffRequestDomainEntityToDbEntityMapper<br>PaidTimeOffRequestDomainEntityToViewModelMapper<br>TenantViewModelToDbEntityMapper<br>ValidateRequestedPaidTimeOffHoursViewModelToDomainEntityMapper</pre><p>Ahhhhh!!!!!!!!</p><h3>Problem #3: Need to Manually Create New Mapper Classes for Every Entity Relationship</h3><p>We’re no longer creating horrible boilerplate code by hand, which is nice, but we’re still back in the boat of having to create a new class every time there’s a new entity mapping requirement. This is now tedious in another way, and it gets worse as the application grows and grows. Is there some magical programming wizardry that can save us from this predicament?</p><p>Maybe there is.</p><h3>Solution #3: Use Auto-Generation Code (Meta-Programming) Alongside Partial Classes to Minimize the Pain of Mapper Class Creation</h3><p>Manually creating a new mapper class for every new entity relationship is a massive pain. Fortunately, we can mitigate it by using a classic meta-programming technique, which is writing code that generates code.</p><p>Back in the day, we used to use T4 Templates to do this sort of thing. However, I eventually found them to be clunky and they didn’t work really well with multiple input files. The fact of the matter is, this isn’t hard to do in your language of choice, and that’s exactly what we’ve done with the demo application. If you download the <a href="https://github.com/JacobsDataSolutions/OrgManager">source code</a> off GitHub, you can see that I created a console application in F# called JDS.OrgManager.MapperGeneratorConsoleApp.</p><p>I’m not going to post all of it up here because it doesn’t matter that much and frankly it’s a bunch of spaghetti code. But it gets the job done. The sample below shows how we use reflection to scan through generated assemblies, searching for classes that implement the various tag interfaces that indicate what kind of entities they are.</p><pre>let assignableTypes = [ typeof&lt;IDomainEntity&gt;; typeof&lt;IViewModel&gt;; typeof&lt;IDbEntity&gt;; typeof&lt;IValueObject&gt; ]<br>let allTypes =<br>    Directory.EnumerateFiles(&quot;.&quot;, &quot;*.dll&quot;)<br>    |&gt; Seq.filter (fun name -&gt; name.TrimStart(&#39;.&#39;, &#39;\\&#39;).StartsWith(&quot;JDS&quot;))<br>    |&gt; Seq.map Assembly.LoadFrom<br>    |&gt; Seq.map (fun a -&gt; a.GetTypes())<br>    |&gt; Seq.concat<br>    |&gt; Seq.filter (fun t -&gt; assignableTypes |&gt; List.exists (fun t&#39; -&gt; t&#39;.IsAssignableFrom(t)))<br>    |&gt; Seq.map (fun t -&gt; { Name = t.Name; Type = t; AssignableType = assignableTypes |&gt; List.find (fun t&#39; -&gt; t&#39;.IsAssignableFrom(t)) })<br>    |&gt; List.ofSeq</pre><p>In case you haven’t figured it out by now, I’m a huge fan of F#. The functional paradigm is incredibly powerful, and F# owns when it comes to tasks like this. Anyway, here is a small sample of the input file to the program.</p><pre>CustomerViewModel-&gt;CustomerEntity<br>Employee-&gt;EmployeeEntity<br>EmployeeEntity-&gt;Employee<br>EmployeeViewModel-&gt;Employee<br>Employee-&gt;EmployeeViewModel</pre><p>As you can see, it’s just a text file that specifies the relationships we want to generate. After we run it, it spits out a C# file that looks kind of like this:</p><pre>public partial class AddressViewModelToValueObjectMapper : MapperBase&lt;IAddressViewModel, Address&gt;, IViewModelToValueObjectMapper&lt;IAddressViewModel, Address&gt;<br>{ }<br>public partial class CustomerViewModelToDbEntityMapper : MapperBase&lt;CustomerViewModel, CustomerEntity&gt;, IViewModelToDbEntityMapper&lt;CustomerViewModel, CustomerEntity&gt;<br>{ }<br>public partial class EmployeeDbEntityToDomainEntityMapper : MapperBase&lt;EmployeeEntity, Employee&gt;, IDbEntityToDomainEntityMapper&lt;EmployeeEntity, Employee&gt;<br>{ }<br>public partial class EmployeeDomainEntityToDbEntityMapper : MapperBase&lt;Employee, EmployeeEntity&gt;, IDomainEntityToDbEntityMapper&lt;Employee, EmployeeEntity&gt;<br>{ }</pre><p>This is a prime example of when it’s okay to break our own rules. In this case, we are putting multiple class declarations into a single source file, something I’d never do under ordinary circumstances. You’ll notice that these are declared as partial classes. Partial class implementations are an extremely useful feature that has been around since C# 2. Their purpose, as you can see here, is to allow developers to split class declarations across multiple files. In this way, we can extend auto-generated code without worrying about our customizations getting wiped out the next time the generator runs. Obviously, there’s no one-size-fits-all-solution and we cannot be certain that the MapperBase default implementation will always fit our needs in every situation. So, we’ve left ourselves an out.</p><p>Here’s the new, customized code for the Employee View Model to Domain entity mapper class that we saw earlier. Again, this is code that I manually wrote to augment the auto-generated code from the mapper generator console app.</p><pre>public partial class EmployeeViewModelToDomainEntityMapper<br>{<br>    private readonly IViewModelToValueObjectMapper&lt;IAddressViewModel, Address&gt; addressMapper;</pre><pre>    public EmployeeViewModelToDomainEntityMapper(IViewModelToValueObjectMapper&lt;IAddressViewModel, Address&gt; addressMapper) =&gt; this.addressMapper = addressMapper ?? throw new ArgumentNullException(nameof(addressMapper));</pre><pre>    protected override TypeAdapterSetter&lt;EmployeeViewModel, Employee&gt; Configure(TypeAdapterSetter&lt;EmployeeViewModel, Employee&gt; typeAdapterSetter)<br>        =&gt; base.Configure(typeAdapterSetter)<br>            .Map(dest =&gt; dest.HomeAddress, src =&gt; addressMapper.Map(src))<br>            .Map(dest =&gt; dest.Salary, src =&gt; new Money(src.Salary, Currency.GetByCode(src.CurrencyCode)));<br>}</pre><p>Now, it seems like we have the best of all worlds. We have combined the power of automation with the flexibility to handle special cases, like what you see above. We have finally slayed the hydra and solved our mapping problem entirely, right?</p><p>Wrong. Now there’s another issue.</p><h3>Problem #4: Mapper Class Explosion</h3><p>This is the final problem we have yet to solve (I promise). Scenarios like this are common in software solutions that have been built in the Object-Oriented paradigm (OOP), as is the case with C#. This is especially true when using sophisticated design patterns to compensate for inherent shortcomings of the language and/or framework. An overabundance of classes tends to occur because that is simply the natural tendency of OOP languages. In our case, we have made it so easy to generate mapping code that we now have a proliferation of mapper classes in our solution. This is problematic because A. it becomes onerous to inject mapper classes into workflows that are even moderately complex, as you can see from the constructor declaration below…</p><pre>public AddOrUpdateEmployeeCommandHandler(<br>    IApplicationWriteDbContext context,<br>    IApplicationWriteDbFacade facade,<br>    IViewModelToDomainEntityMapper&lt;AddOrUpdateEmployeeViewModel, Employee&gt; employeeVmToDomainEntityMapper,<br>    IViewModelToDbEntityMapper&lt;AddOrUpdateEmployeeViewModel, EmployeeEntity&gt; employeeVmToDbEntityMapper,<br>    IDomainEntityToViewModelMapper&lt;Employee, AddOrUpdateEmployeeViewModel&gt; employeeDomainEntityToViewModelMapper,<br>    IDomainEntityToDbEntityMapper&lt;Employee, EmployeeEntity&gt; employeeDomainToDbEntityMapper,<br>    IDbEntityToDomainEntityMapper&lt;EmployeeEntity, Employee&gt; employeeDbEntityToDomainEntityMapper,<br>    IDbEntityToDomainEntityMapper&lt;PaidTimeOffPolicyEntity, PaidTimeOffPolicy&gt; ptoPolicyDbEntityToDomainEntityMapper<br>    )<br>{<br>    this.context = context ?? throw new ArgumentNullException(nameof(context));<br>    this.facade = facade ?? throw new ArgumentNullException(nameof(facade));<br>    this.employeeVmToDbEntityMapper = employeeVmToDbEntityMapper ?? throw new ArgumentNullException(nameof(employeeVmToDbEntityMapper));<br>    this.employeeVmToDomainEntityMapper = employeeVmToDomainEntityMapper ?? throw new ArgumentNullException(nameof(employeeVmToDomainEntityMapper));<br>    this.employeeDomainEntityToViewModelMapper = employeeDomainEntityToViewModelMapper ?? throw new ArgumentNullException(nameof(employeeDomainEntityToViewModelMapper));<br>    this.employeeDomainToDbEntityMapper = employeeDomainToDbEntityMapper ?? throw new ArgumentNullException(nameof(employeeDomainToDbEntityMapper));<br>    this.employeeDbEntityToDomainEntityMapper = employeeDbEntityToDomainEntityMapper ?? throw new ArgumentNullException(nameof(employeeDbEntityToDomainEntityMapper));<br>    this.ptoPolicyDbEntityToDomainEntityMapper = ptoPolicyDbEntityToDomainEntityMapper ?? throw new ArgumentNullException(nameof(ptoPolicyDbEntityToDomainEntityMapper));<br>}</pre><p>… and B. the registration code for our IOC container will quickly balloon out of control, as you can see from the short sample below:</p><pre>public static class DependencyInjectionExtensions<br>{<br>    public static IServiceCollection AddApplicationLayer(this IServiceCollection services, bool addValidation = false, bool addRequestLogging = false, bool useReadThroughCachingForQueries = false)<br>    {<br>        services<br>            .AddSingleton&lt;IDomainEntityToDbEntityMapper&lt;Employee, EmployeeEntity&gt;, EmployeeDomainToDbEntityMapper&gt;()<br>            .AddSingleton&lt;IDomainEntityToDbEntityMapper&lt;PaidTimeOffPolicy, PaidTimeOffPolicyEntity&gt;, PaidTimeOffPolicyDomainToDbEntityMapper&gt;()<br>            .AddSingleton&lt;IViewModelToDomainEntityMapper&lt;RegisterOrUpdateEmployeeCommand, Employee&gt;, RegisterOrUpdateEmployeeDomainEntityMapper&gt;()<br>            .AddSingleton&lt;IViewModelToDbEntityMapper&lt;TenantViewModel, TenantEntity&gt;, TenantViewModelToDbEntityMapper&gt;();<br>...</pre><p>There are now too many interconnected pieces, and it can become easy to forget to register one of the mappers, in which case the application will throw an exception at run time when it is unable to resolve the proper implementation for the injected interface.</p><p>Fortunately, there’s an elegant solution.</p><h3>Solution #4: Use Registration by Convention, and Create a Universal Mapper Factory</h3><p>The first part of the solution to our problem involves implementing a pattern which is a good idea regardless of the situation at hand, and that is incorporating Registration by Convention into the application. Simply put, this means using a toolkit to automatically register classes into the IOC container rather than manually writing the registration code, which is error-prone and tedious. In the demo application I’ve chosen to use a package called <a href="https://github.com/khellang/Scrutor">Scrutor</a> to get the job done. The result is what you see below.</p><pre>public static class DependencyInjectionExtensions<br>{<br>    public static IServiceCollection AddApplicationLayer(this IServiceCollection services, bool addValidation = false, bool addRequestLogging = false, bool useReadThroughCachingForQueries = false)<br>    {<br>        services.Scan(scan =&gt;<br>            scan<br>            .FromCallingAssembly()<br>            .AddClasses(classes =&gt; classes.AssignableTo(typeof(IDbEntityToViewModelMapper&lt;,&gt;))).AsImplementedInterfaces().WithSingletonLifetime()<br>            .AddClasses(classes =&gt; classes.AssignableTo(typeof(IDbEntityToDomainEntityMapper&lt;,&gt;))).AsImplementedInterfaces().WithSingletonLifetime()<br>            .AddClasses(classes =&gt; classes.AssignableTo(typeof(IDbEntityToValueObjectMapper&lt;,&gt;))).AsImplementedInterfaces().WithSingletonLifetime()<br>            .AddClasses(classes =&gt; classes.AssignableTo(typeof(IDomainEntityToDbEntityMapper&lt;,&gt;))).AsImplementedInterfaces().WithSingletonLifetime()<br>            .AddClasses(classes =&gt; classes.AssignableTo(typeof(IDomainEntityToViewModelMapper&lt;,&gt;))).AsImplementedInterfaces().WithSingletonLifetime()<br>            .AddClasses(classes =&gt; classes.AssignableTo(typeof(IViewModelToDbEntityMapper&lt;,&gt;))).AsImplementedInterfaces().WithSingletonLifetime()<br>            .AddClasses(classes =&gt; classes.AssignableTo(typeof(IViewModelToDomainEntityMapper&lt;,&gt;))).AsImplementedInterfaces().WithSingletonLifetime()<br>            .AddClasses(classes =&gt; classes.AssignableTo(typeof(IViewModelToValueObjectMapper&lt;,&gt;))).AsImplementedInterfaces().WithSingletonLifetime()<br>        );</pre><p>In a nutshell, we are simply telling it to find all concrete implementations of the open generic interfaces specified and register each as a singleton. It is fast, efficient, and makes our task way easier.</p><p>The second part of our solution is intended to make the actual usage of dependency injection easier inside the high-level workflows. As you’ll recall from the code sample earlier in this section, we are injecting six different mappers into the AddOrUpdateEmployee command handler class. Six! And this is just to perform a moderately complex operation: adding a new employee to a tenant and running some business validation rules. Is there an easier way? Absolutely. The answer is to create a universal mapper factory class, which encapsulates the IOC container and uses a little reflection mojo to make it more intuitive to use.</p><p>In brief, the universal mapper factory, which I’ve named simply ModelMapper, exposes a number of methods of the form:</p><pre>TDestinationType Map___To___(TSourceType source)</pre><p>OR</p><pre>void Map___To___(TSourceType source, TDestinationType existing)</pre><p>When one of these methods is called, the appropriate mapper type is resolved from the IOC container, cached in a ConcurrentDictionary (to improve performance on subsequent calls), and then the underlying Map() method is invoked on the mapper object. You can see the ModelMapper source code below. It’s a little verbose, but I think it’s important, so I’ve presented it in its entirety.</p><pre>public class ModelMapper : IModelMapper<br>{<br>    private readonly IServiceProvider serviceProvider;</pre><pre>    private ConcurrentDictionary&lt;Type, object&gt; mapperLookup = new ConcurrentDictionary&lt;Type, dynamic&gt;();</pre><pre>    public ModelMapper(IServiceProvider serviceProvider)<br>    {<br>        this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));<br>    }</pre><pre>    public TDomainEntity MapDbEntityToDomainEntity&lt;TDbEntity, TDomainEntity&gt;(TDbEntity dbEntity)<br>        where TDbEntity : IDbEntity<br>        where TDomainEntity : IDomainEntity =&gt; GetFactoryMethodInstance&lt;TDbEntity, TDomainEntity&gt;().Invoke(dbEntity);</pre><pre>    public TValueObject MapDbEntityToValueObject&lt;TDbEntity, TValueObject&gt;(TDbEntity dbEntity)<br>        where TDbEntity : IDbEntity<br>        where TValueObject : IValueObject =&gt; GetFactoryMethodInstance&lt;TDbEntity, TValueObject&gt;().Invoke(dbEntity);</pre><pre>    public TViewModel MapDbEntityToViewModel&lt;TDbEntity, TViewModel&gt;(TDbEntity dbEntity)<br>        where TDbEntity : IDbEntity<br>        where TViewModel : IViewModel =&gt; GetFactoryMethodInstance&lt;TDbEntity, TViewModel&gt;().Invoke(dbEntity);</pre><pre>    public void MapDbEntityToViewModel&lt;TDbEntity, TViewModel&gt;(TDbEntity dbEntity, TViewModel existing)<br>        where TDbEntity : IDbEntity<br>        where TViewModel : IViewModel =&gt; GetVoidMethodInstance&lt;TDbEntity, TViewModel&gt;().Invoke(dbEntity, existing);</pre><pre>    public TDbEntity MapDomainEntityToDbEntity&lt;TDomainEntity, TDbEntity&gt;(TDomainEntity domainEntity)<br>        where TDomainEntity : IDomainEntity<br>        where TDbEntity : IDbEntity =&gt; GetFactoryMethodInstance&lt;TDomainEntity, TDbEntity&gt;().Invoke(domainEntity);</pre><pre>    public void MapDomainEntityToDbEntity&lt;TDomainEntity, TDbEntity&gt;(TDomainEntity domainEntity, TDbEntity existing)<br>        where TDomainEntity : IDomainEntity<br>        where TDbEntity : IDbEntity =&gt; GetVoidMethodInstance&lt;TDomainEntity, TDbEntity&gt;().Invoke(domainEntity, existing);</pre><pre>    public TViewModel MapDomainEntityToViewModel&lt;TDomainEntity, TViewModel&gt;(TDomainEntity domainEntity)<br>        where TDomainEntity : IDomainEntity<br>        where TViewModel : IViewModel =&gt; GetFactoryMethodInstance&lt;TDomainEntity, TViewModel&gt;().Invoke(domainEntity);</pre><pre>    public void MapDomainEntityToViewModel&lt;TDomainEntity, TViewModel&gt;(TDomainEntity domainEntity, TViewModel existing)<br>        where TDomainEntity : IDomainEntity<br>        where TViewModel : IViewModel =&gt; GetVoidMethodInstance&lt;TDomainEntity, TViewModel&gt;().Invoke(domainEntity, existing);</pre><pre>    public TDbEntity MapViewModelToDbEntity&lt;TViewModel, TDbEntity&gt;(TViewModel viewModel)<br>        where TViewModel : IViewModel<br>        where TDbEntity : IDbEntity =&gt; GetFactoryMethodInstance&lt;TViewModel, TDbEntity&gt;().Invoke(viewModel);</pre><pre>    public void MapViewModelToDbEntity&lt;TViewModel, TDbEntity&gt;(TViewModel viewModel, TDbEntity existing)<br>        where TViewModel : IViewModel<br>        where TDbEntity : IDbEntity =&gt; GetVoidMethodInstance&lt;TViewModel, TDbEntity&gt;().Invoke(viewModel, existing);</pre><pre>    public TDomainEntity MapViewModelToDomainEntity&lt;TViewModel, TDomainEntity&gt;(TViewModel viewModel)<br>        where TViewModel : IViewModel<br>        where TDomainEntity : IDomainEntity =&gt; GetFactoryMethodInstance&lt;TViewModel, TDomainEntity&gt;().Invoke(viewModel);</pre><pre>    public TValueObject MapViewModelToValueObject&lt;TViewModel, TValueObject&gt;(TViewModel viewModel)<br>        where TViewModel : IViewModel<br>        where TValueObject : IValueObject =&gt; GetFactoryMethodInstance&lt;TViewModel, TValueObject&gt;().Invoke(viewModel);</pre><pre>    private Func&lt;TSource, TTarget&gt; GetFactoryMethodInstance&lt;TSource, TTarget&gt;()<br>    {<br>        var mapper = GetMapper&lt;TSource, TTarget&gt;();<br>        return (Func&lt;TSource, TTarget&gt;)Delegate.CreateDelegate(typeof(Func&lt;TSource, TTarget&gt;), mapper, &quot;Map&quot;);<br>    }</pre><pre>    private object GetMapper&lt;TSource, TTarget&gt;()<br>    {<br>        var mapperType = (typeof(TSource), typeof(TTarget)) switch<br>        {<br>            (Type source, Type target) when typeof(IDbEntity).IsAssignableFrom(source) &amp;&amp; typeof(IDomainEntity).IsAssignableFrom(target) =&gt;<br>                typeof(IDbEntityToDomainEntityMapper&lt;,&gt;).MakeGenericType(source, target),<br>            (Type source, Type target) when typeof(IDbEntity).IsAssignableFrom(source) &amp;&amp; typeof(IValueObject).IsAssignableFrom(target) =&gt;<br>                typeof(IDbEntityToValueObjectMapper&lt;,&gt;).MakeGenericType(source, target),<br>            (Type source, Type target) when typeof(IDbEntity).IsAssignableFrom(source) &amp;&amp; typeof(IViewModel).IsAssignableFrom(target) =&gt;<br>                typeof(IDbEntityToViewModelMapper&lt;,&gt;).MakeGenericType(source, target),<br>            (Type source, Type target) when typeof(IDomainEntity).IsAssignableFrom(source) &amp;&amp; typeof(IDbEntity).IsAssignableFrom(target) =&gt;<br>                typeof(IDomainEntityToDbEntityMapper&lt;,&gt;).MakeGenericType(source, target),<br>            (Type source, Type target) when typeof(IDomainEntity).IsAssignableFrom(source) &amp;&amp; typeof(IViewModel).IsAssignableFrom(target) =&gt;<br>                typeof(IDomainEntityToViewModelMapper&lt;,&gt;).MakeGenericType(source, target),<br>            (Type source, Type target) when typeof(IViewModel).IsAssignableFrom(source) &amp;&amp; typeof(IDbEntity).IsAssignableFrom(target) =&gt;<br>                typeof(IViewModelToDbEntityMapper&lt;,&gt;).MakeGenericType(source, target),<br>            (Type source, Type target) when typeof(IViewModel).IsAssignableFrom(source) &amp;&amp; typeof(IDomainEntity).IsAssignableFrom(target) =&gt;<br>                typeof(IViewModelToDomainEntityMapper&lt;,&gt;).MakeGenericType(source, target),<br>            (Type source, Type target) when typeof(IViewModel).IsAssignableFrom(source) &amp;&amp; typeof(IValueObject).IsAssignableFrom(target) =&gt;<br>                typeof(IViewModelToValueObjectMapper&lt;,&gt;).MakeGenericType(source, target),<br>            { } =&gt; throw new ApplicationLayerException($&quot;Could not get instance of mapper class for source type {typeof(TSource).Name} and destination type {typeof(TTarget).Name}.&quot;)<br>        };</pre><pre>        return mapperLookup.GetOrAdd(mapperType, serviceProvider.GetRequiredService(mapperType));<br>    }</pre><pre>    private Action&lt;TSource, TTarget&gt; GetVoidMethodInstance&lt;TSource, TTarget&gt;()<br>    {<br>        var mapper = GetMapper&lt;TSource, TTarget&gt;();<br>        return (Action&lt;TSource, TTarget&gt;)Delegate.CreateDelegate(typeof(Action&lt;TSource, TTarget&gt;), mapper, &quot;Map&quot;);<br>    }<br>}</pre><p>Now, instead of having to inject in multiple mapper types into workflows that need them, we can simplify our constructor to this:</p><pre>public class AddOrUpdateEmployeeCommandHandler : IRequestHandler&lt;AddOrUpdateEmployeeCommand, AddOrUpdateEmployeeViewModel&gt;<br>{<br>    private readonly IApplicationWriteDbContext context;<br>    private readonly IApplicationWriteDbFacade facade;<br>    private readonly IModelMapper mapper;<br>    public AddOrUpdateEmployeeCommandHandler(<br>        IApplicationWriteDbContext context,<br>        IApplicationWriteDbFacade facade,<br>        IModelMapper mapper<br>        )<br>    {<br>        this.context = context ?? throw new ArgumentNullException(nameof(context));<br>        this.facade = facade ?? throw new ArgumentNullException(nameof(facade));<br>        this.mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));<br>    }</pre><p>Using it is as simple as:</p><pre>mapper.MapViewModelToDbEntity(employeeViewModel, employeeEntity);</pre><p>or</p><pre>var employee = mapper.MapDbEntityToDomainEntity&lt;EmployeeEntity, Employee&gt;(employeeEntity);</pre><p>You can review the entire AddOrUpdateEmployee workflow for the demo solution on GitHub, <a href="https://github.com/JacobsDataSolutions/OrgManager/blob/master/JDS.OrgManager/JDS.OrgManager.Application/HumanResources/Employees/Commands/AddOrUpdateEmployee/AddOrUpdateEmployeeCommand.cs">here</a>.</p><p>At last, we have slayed the hydra of complexity. We developed a means by which we can easily map from View Models to Domain entities to Persistence entities, or any permutation thereof, which allows us to meet our mandate of keeping entity types decoupled. The groundwork is in place for our system to scale elegantly and efficiently, while keeping the code reasonably maintainable.</p><h3>Conclusion</h3><p>We started out be re-examining Domain entities and Value Objects from a Domain-Driven Design perspective, and then saw that new C# 9 language features such as records and init-only setters can help simplify the design of these classes. Next, I laid out the case for keeping different entity types — View Models, Domain entities, and Persistence entities — distinct and decoupled, the primary reason being that they serve orthogonal purposes, and we want our application to scale. After that, I discussed the complexity that this design decision introduces, and outlined a four-step process for mitigating that complexity, culminating in the creation of an elegant mapping infrastructure that we can use to transform entities of one type to those of another.</p><p>In the next blog entry, we’ll explore how we can use this new mapping infrastructure to create various kinds of DDD workflow patterns, giving us the power and flexibility to implement virtually any requirement the business team throws at as. It’s starting to get interesting…</p><h3>Experts / Authorities / Resources</h3><h3>Vladimir Khorikov</h3><ul><li><a href="https://enterprisecraftsmanship.com/posts/csharp-records-value-objects/">C# Records as DDD Value Objects</a></li></ul><h3>Steve McConnell</h3><ul><li><a href="https://www.oreilly.com/library/view/code-complete-second/0735619670/">Code Complete 2</a></li></ul><h3>MSDN Official Docs</h3><ul><li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9">What’s New in C# 9.0</a></li></ul><h3>Wikipedia</h3><ul><li><a href="https://en.wikipedia.org/wiki/Lernaean_Hydra">Hydra</a> (mythical beast)</li></ul><h3>Mapping Tools</h3><ul><li><a href="https://github.com/MapsterMapper/Mapster">Mapster</a></li><li><a href="https://automapper.org/">AutoMapper</a></li><li><a href="https://github.com/khellang/Scrutor">Scrutor</a></li></ul><p>This is entry #5 in the <a href="https://blog.jacobsdata.com/category/scaffold%20clean%20ddd%20web%20app">Scaffold Your Clean DDD Web App Series</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c94183acd02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-alchemy/domain-driven-design-entity-mapping-strategies-7c94183acd02">Domain-Driven Design Entity Mapping Strategies</a> was originally published in <a href="https://medium.com/software-alchemy">Software Alchemy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Global Exception Handling in ASP.NET Core and Angular]]></title>
            <link>https://medium.com/software-alchemy/global-exception-handling-in-asp-net-core-and-angular-aee9d27a7c12?source=rss-a80f78e022fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/aee9d27a7c12</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Jacobs Data Solutions]]></dc:creator>
            <pubDate>Thu, 12 Nov 2020 13:54:45 GMT</pubDate>
            <atom:updated>2020-11-12T13:54:45.564Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*iC8-pf7Q_ZMIa1TL.jpg" /></figure><p>Image by <a href="https://pixabay.com/users/pexels-2286921/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1283624">Pexels</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1283624">Pixabay</a></p><h3>Introduction</h3><p>In the previous blog entry, I discussed the data model and our strategy for persisting/reading data to/from the database in a way that facilitates the CQRS architectural pattern. I also discussed combining Dapper with EF Core for maximum flexibility, and we briefly revisited the high-level tenancy models.</p><p>In this blog entry I’ll go over using custom ASP.NET Core middleware to catch various kinds of exceptions so that we can return the proper HTTP status code to the user’s browser. At the Angular side we’ll take advantage of these status codes in order to direct the user to the appropriate pages on an error — an “unauthorized” page or general error page — or simply display a notification. This is one approach to handling server exceptions which are prone to “bubble up” from lower layers of the stack, such as the Application and Domain layers, and elegantly updating the UI.</p><p>As before, I’ve made sweeping changes to our demo application that you can access on GitHub <a href="https://github.com/JacobsDataSolutions/OrgManager/releases/tag/Blog-Entry-12">here</a>. I encourage you to follow along in the code and if you have any feedback or suggestions, feel free to let me know.</p><h3>Exception Flow</h3><p>Before we jump in, let’s revisit the high-level architecture you’ve seen before, if you’ve been reading previous blog entries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*vM0F7NNjLhj9LC3r.png" /></figure><p>The big takeaway from this simple diagram is that this represents the Dependency Inversion Principle on an architectural level.</p><p>The Dependency Inversion Principle states:</p><blockquote><em>High-level modules should not depend on low-level modules. Both should depend on abstractions (e.g. interfaces).</em></blockquote><blockquote><em>Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.</em></blockquote><p>I’ve spoken about this principle in <a href="https://blog.jacobsdata.com/2020/01/27/basic-concepts-of-software-design-and-architecture#solid">previous blog entries</a>, so you may want to revisit those if you’re starting to get lost. Now, pay attention here, this is important. As Uncle Bob points out in his influential blog article simply entitled <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">The Clean Architecture</a> you’ll notice that the dependencies point inward, like you see below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*ezwAqV-jq_2Gz2A0.png" /></figure><p>Our architecture abides by Bob’s “Dependency Rule,” which is to say that peripheral layers rely upon core layers, and Dependency Injection is the magic glue that ties them together:</p><ul><li>Infrastructure and Persistence models and interfaces are declared in the Application layer. Concrete implementations of these interfaces are found in the peripheral layers and get injected into the orchestration components of the Application layer.</li><li>The Presentation layer executes controller actions, representing high-level operations, against Application layer services. This is accomplished using the CQRS pattern, facilitated by MediatR.</li><li>Domain (business) operations are orchestrated directly by the Application layer. For the most part, Dependency Inversion/IOC is NOT used to instantiate Domain layer components, for the simple, yet elusive reason that everything going on in there is already abstract — it represents the realm of pure business logic. It is truly the core of the core of this architecture.</li></ul><p>You might believe that when something goes wrong (database components start throwing exceptions, a message queue is down, business logic has logic errors, so on) that this diagram would be completely inverted. However, this is not so. As you can see below…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*0bU88b-oJ-10F4v1.png" /></figure><p>… aside from the fact that our new diagram looks kind of like the Flux Capacitor from the <a href="https://www.imdb.com/title/tt0088763/">Back to the Future</a> movies, under error conditions exceptions don’t necessarily flow against the direction of dependency. Here’s why.</p><ul><li>The Web API is still the entry-point for our application. This is where all dependencies get wired up and resolved by our IOC container. It’s effectively the top of the stack, were you to take this diagram and flatten it out.</li><li>Even though we are programming against abstractions, those abstractions need to have something concrete behind them at the end of the day. Those low-level/external components get called by the Application layer, which is the lynch pin that holds the architecture together.</li></ul><h3>Bridge from the Web API to the UI</h3><p>As the diagram above implies, our goal is to handle exceptional, error condition scenarios in the Web API and communicate those errors to the UI, namely by serializing the exceptions as JSON text and setting the proper HTTP response code for the web response. Using <a href="https://tools.ietf.org/html/rfc7807">industry standards</a> to communicate errors across the wire isn’t exactly a revolutionary idea on my part, but there are some nuances here that I’d like to discuss that aren’t agreed upon by all web developers. Taking a step back, please allow me to share my general philosophy on best practices for handling exceptions in an enterprise system. My opinion may differ from that of other software professionals out in the blogosphere, and in the end it’s up to you to decide what patterns and practices work best for you. At any rate, here is my stance:</p><ol><li>Whenever possible, it is best to handle abnormal conditions such as validation failures and/or authorization failures as high up in the stack as possible — in other words in the Web API controller methods. This should not come as a surprise to anyone. If possible, a declarative approach, such as using ASP.NET Core authorization filters and policies should be preferred.</li><li>Exceptions are perfectly OK to throw inside deeper layers of the application — i.e. the Application layer, Domain layer, etc. — especially when used for business logic errors and so forth. However, be aware that this comes at a cost, and that exceptions can be computationally expensive to handle in your application.</li><li>Custom exception types should have semantic names which are relevant to the application, and not be coerced by the technology stack you’re building on or the protocol you’re using (HTTP). I’ll explain more below.</li><li>Exceptions which are thrown by deeper layers of the application should be caught, logged, and communicated to the UI by the Web API, however…</li><li>As developers, we should be diligent NOT to get into the habit of using exceptions for flow control in our application (i.e. IF-THEN-ELSE logic). Exceptions are for exceptional, unexpected error conditions.</li></ol><p>In essence, we are walking a fine line between two extremes:</p><ul><li>Preemptively packing all error checking logic into top-level methods of high-level operations — Web API calls — in order to avoid throwing exceptions. This is NOT recommended and is futile to boot, because no software developer is omniscient enough to anticipate every single possible error scenario for sufficiently complex applications, and even making the attempt to do so would result in controller methods that are bloated and unmaintainable. Furthermore, this flies in the face of our Clean DDD architectural approach, which aims to encapsulate business logic in the core of our application. This includes handling business logic failure conditions.</li><li>Throwing exceptions willy-nilly all throughout the stack and gleefully using them for flow control. This is also NOT recommended, because it results in a different kind of unmaintainability. Exceptions are special in that they bubble up the call stack, effectively cutting across layers of the application. This characteristic should not be abused.</li></ul><p>We will walk the middle path, in which:</p><ul><li>As much as possible, validation and authorization checks are done at the controller level. This can be done inside custom filter attributes, <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-3.1">authorization policies</a>, or <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authorization/resourcebased?view=aspnetcore-3.1">authorization handlers</a>.</li><li>When exceptions bubble up from deeper layers of the application, these will be caught by middleware and translated into the proper HTTP error responses that the UI can handle.</li></ul><p>Some solutions may implement custom exception types which correspond to the standard HTTP status codes. For instance, one may declare exception types such as BadRequestException, ForbiddenException, etc. I generally disagree with this approach and here’s why: in the context of a particular SaaS application, these are broadly defined and don’t really mean anything. The various verbs and status codes of the HTTP standard were intentionally designed to be general purpose because they’re meant to accommodate a wide swath of potential applications. However, that inherent vagueness doesn’t mesh well with the bounded contexts and ubiquitous language of our particular application.</p><p>In our OrgManager solution, for instance, does it make sense for the Domain layer to throw a BadRequestException when an employee tries to request more time off than they have accrued, or would it be easier to understand, debug, and maintain a section of code that instead threw something like a TimeOffException, or EmployeeException? The latter is what I’ve tried to implement in the demo application (though in some situations, like with the &quot;Not Found&quot; status code, the HTTP standard name is perfectly fine).</p><p>If you examine the demo solution, you’ll see that what I’ve done is fairly straightforward:</p><p>A base exception type is declared for each core layer of the application — ApplicationLayerException for the Application layer and DomainLayerException for the domain layer.</p><p>Additional, more specific exception types are derived from those two in areas of the application in which they make sense. For instance, the Domain layer has an EmployeeException under the Human Resources bounded context. The Application layer declares certain functionally oriented exception types that are appropriate inside CQRS workflows, such as AccessDeniedException, NotFoundException, etc.</p><p>When creating new exception types, one of the options available under the quick actions context menu (CTRL+.) is “Generate All.” This will generate all constructors for your custom exception type, and I highly recommend you do that. The result looks something like this:</p><pre>public DomainLayerException()<br>{<br>}</pre><pre>public DomainLayerException(SerializationInfo info, StreamingContext context) : base(info, context)<br>{<br>}</pre><pre>public DomainLayerException(string message) : base(message)<br>{<br>}</pre><pre>public DomainLayerException(string message, Exception innerException) : base(message, innerException)<br>{<br>}</pre><h3>Handling Exceptions with Middleware</h3><p>Once we’ve declared our custom exception types, we need a way to catch any such exceptions that get thrown further down the stack and translate them into the proper HTTP response.</p><p>In the demo solution I created a simple test controller to simulate these different exception types being thrown, so that we can determine if our middleware is working the way we’d expect it to. I created an Angular component to call those endpoints, which is what you see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/0*ndvJdS7xRukKjFYr.png" /></figure><p>By default, ASP.NET Core will catch any unhandled exceptions and return an HTTP status 500 to the client, like what you see here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/0*4W8MeGL-SsB0Ctpv.png" /></figure><p>Examining a response while running in Development mode shows a stack trace…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*_X4iYwBAbHA6xSKb.png" /></figure><p>… while running in Production mode shows a general “error processing your request” response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*Ok8aS3CKR4RRuqfg.png" /></figure><p>We’ll change this default behavior, so that more appropriate error codes are returned for a given exception, and details of the error that occurred are serialized as JSON, which our UI can more seamlessly utilize.</p><p>There are a few different ways to tackle the problem at hand. I’ll demonstrate two of them. In the first approach we’ll create and wire in our own custom middleware component and in the second we’ll hook in to the existing ASP.NET Core exception handling middleware.</p><p>Before going further, it’d be worth taking a few minutes to review how the ASP.NET Core middleware pipeline works. <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1">This</a> is a good place to start.</p><p>In simplistic terms, the ASP.NET Core middleware pipeline represents the classic two-pass <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">Chain of Responsibility</a> pattern, like what you see here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*eXQkEMzCrnfV_6-Q.png" /></figure><p>Each middleware component gets a chance to handle both the inbound request and outbound response, and short-circuit the pipeline if appropriate. This is exceptionally useful (no pun intended) when handling error conditions, and my hat’s off to the ASP.NET Core team for choosing this design pattern.</p><h3>Approach #1: Creating Our Own Custom Exception-Handling Middleware</h3><p>The first way is the simplest to understand, and you’re likely to find this across different blogs and Stack Overflow questions on the Net. We simply create our own middleware component like so:</p><pre>public class CustomErrorHandlingMiddleware<br>{<br>    private readonly RequestDelegate next;</pre><pre>    public CustomErrorHandlingMiddleware(RequestDelegate next)<br>    {<br>        this.next = next;<br>    }</pre><pre>    public async Task Invoke(HttpContext context, IWebHostEnvironment env)<br>    {<br>        try<br>        {<br>            await next(context);<br>        }<br>        catch (Exception ex)<br>        {<br>            await HandleExceptionAsync(context, ex, env);<br>        }<br>    }</pre><pre>    private static Task HandleExceptionAsync(HttpContext context, Exception ex, IWebHostEnvironment env)<br>    {<br>        var code = HttpStatusCode.InternalServerError; // 500 if unexpected</pre><pre>        if (ex is AccessDeniedException)<br>        {<br>            code = HttpStatusCode.Forbidden;<br>        }<br>        if (ex is AuthorizationException)<br>        {<br>            code = HttpStatusCode.Unauthorized;<br>        }<br>        else if (ex is NotFoundException)<br>        {<br>            code = HttpStatusCode.NotFound;<br>        }<br>        else if (ex is ApplicationLayerException)<br>        {<br>            code = HttpStatusCode.BadRequest;<br>        }</pre><pre>        var includeDetails = env.IsEnvironment(&quot;Development&quot;);<br>        var title = includeDetails ? &quot;An error occurred: &quot; + ex.Message : &quot;An error occurred&quot;;<br>        var details = includeDetails ? ex.ToString() : null;</pre><pre>        var problem = new ProblemDetails<br>        {<br>            Status = (int?)code,<br>            Title = title,<br>            Detail = details<br>        };</pre><pre>        context.Response.ContentType = &quot;application/problem+json&quot;;<br>        context.Response.StatusCode = (int)code;</pre><pre>        var result = JsonConvert.SerializeObject(problem);<br>        return context.Response.WriteAsync(result);<br>    }<br>}</pre><p>The way it works is dirt simple. The body of the Invoke() method, which gets called by the ASP.NET Core pipeline, contains a try/catch block around the request delegate invocation. Any exceptions which get thrown are caught and handled inside the private HandleExceptionAsync() method. This method examines the type of the exception and based upon that, sets the appropriate HTTP status code. Details of the exception are serialized as a <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.problemdetails?view=aspnetcore-3.1">ProblemDetails</a> object so that it abides by industry standards. Done and done.</p><p>In keeping with our practice of using a DependencyInjectionExtensions static class to simplify configuration, we add one more extension method to that class.</p><pre>public static IApplicationBuilder UseCustomErrorHandlingMiddleware(this IApplicationBuilder app) =&gt;<br>    app.UseMiddleware&lt;CustomErrorHandlingMiddleware&gt;();</pre><p>When wiring it into the pipeline in the Startup class, this should be right near the top of the Configure() method.</p><pre>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br>    // API error handling.<br>    // Approach 1: custom error handling middleware.<br>    app.UseCustomErrorHandlingMiddleware();<br>...</pre><p>When we again generate custom exceptions using our test error controller, the results are quite different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*Y4PdszgmXtAA7grj.png" /></figure><p>As you can see, the proper response codes are being returned…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*rKXsfXMRqnn8l9dR.png" /></figure><p>… and the body of the response contains the JSON we would expect.</p><p>Hooray!</p><h3>Approach #2: Hooking into ASP.NET Core ExceptionHandlerMiddleware</h3><p>As Andrew Lock, author of <a href="https://www.manning.com/books/asp-net-core-in-action-second-edition">ASP.NET Core in Action</a> states in this <a href="https://andrewlock.net/creating-a-custom-error-handler-middleware-function/">blog post</a>, there are a few edge cases which can make it dicey to roll your own global exception handling middleware. For that reason, I’ll now present the approach he recommends.</p><p>Honestly, what you see here is just a modified version of Andrew’s code, so I recommend you give his blog entry a read. The big difference between this one and Approach #1 is that instead of creating middleware, we are declaring the exception handling functionality as methods on a static class, which will then get hooked into the out-of-the-box ASP.NET Core exception handling middleware. Our static class looks like this:</p><pre>public static class CustomErrorHandlerHelper<br>{<br>    public static Task WriteDevelopmentResponse(HttpContext httpContext, Func&lt;Task&gt; next)<br>        =&gt; WriteResponse(httpContext, includeDetails: true);</pre><pre>    public static Task WriteProductionResponse(HttpContext httpContext, Func&lt;Task&gt; next)<br>        =&gt; WriteResponse(httpContext, includeDetails: false);</pre><pre>    private static async Task WriteResponse(HttpContext httpContext, bool includeDetails)<br>    {<br>        // Try and retrieve the error from the ExceptionHandler middleware<br>        var exceptionDetails = httpContext.Features.Get&lt;IExceptionHandlerFeature&gt;();<br>        var ex = exceptionDetails?.Error;</pre><pre>        // Should always exist, but best to be safe!<br>        if (ex != null)<br>        {<br>            // Get the details to display, depending on whether we want to expose the raw exception<br>            var title = includeDetails ? &quot;An error occurred: &quot; + ex.Message : &quot;An error occurred&quot;;<br>            var details = includeDetails ? ex.ToString() : null;</pre><pre>            var code = HttpStatusCode.InternalServerError; // 500 if unexpected</pre><pre>            if (ex is AccessDeniedException)<br>            {<br>                code = HttpStatusCode.Forbidden;<br>            }<br>            if (ex is AuthorizationException)<br>            {<br>                code = HttpStatusCode.Unauthorized;<br>            }<br>            else if (ex is NotFoundException)<br>            {<br>                code = HttpStatusCode.NotFound;<br>            }<br>            else if (ex is ApplicationLayerException)<br>            {<br>                code = HttpStatusCode.BadRequest;<br>            }</pre><pre>            var problem = new ProblemDetails<br>            {<br>                Status = (int?)code,<br>                Title = title,<br>                Detail = details<br>            };</pre><pre>            // This is often very handy information for tracing the specific request<br>            var traceId = Activity.Current?.Id ?? httpContext?.TraceIdentifier;<br>            if (traceId != null)<br>            {<br>                problem.Extensions[&quot;traceId&quot;] = traceId;<br>            }</pre><pre>            httpContext.Response.ContentType = &quot;application/problem+json&quot;;<br>            httpContext.Response.StatusCode = (int)code;</pre><pre>            //Serialize the problem details object to the Response as JSON (using System.Text.Json)<br>            var stream = httpContext.Response.Body;<br>            await JsonSerializer.SerializeAsync(stream, problem);<br>        }<br>    }<br>}</pre><p>This is the configuration extension method we’ve declared in our DependencyInjectionExtensions class.</p><pre>public static void UseCustomErrors(this IApplicationBuilder app, IHostEnvironment environment)<br>{<br>    if (environment.IsDevelopment())<br>    {<br>        app.Use(CustomErrorHandlerHelper.WriteDevelopmentResponse);<br>    }<br>    else<br>    {<br>        app.Use(CustomErrorHandlerHelper.WriteProductionResponse);<br>    }<br>}</pre><p>This is how we wire it into the Startup class.</p><pre>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br>    // Approach 2: use ASP.NET Core ExceptionHandlerMiddleware.<br>    app.UseExceptionHandler(app2 =&gt; app2.UseCustomErrors(env));<br>...</pre><p>When we again throw exceptions using the test controller, the results are what we’d expect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*GTASwwteQ4Xvl8z_.png" /></figure><h3>Handling Error Responses in the UI</h3><p>Now that we’ve figured out how to catch exceptions in the Web API and send them across the wire as a ProblemDetails instance with appropriate HTTP response code, let’s see what we can do to handle those on the Angular side.</p><p>In a nutshell, the primary means by which we handle error responses is by using <a href="https://angular.io/api/common/http/HttpInterceptor">HTTP interceptors</a>. Think of these Angular’s version of middleware — they are essentially components which manipulate the HTTP request/response streams, and follow a chain of responsibility pattern, just like what ASP.NET Core does.</p><p>Here is the implementation of a custom HttpInterceptor that I created for the demo application.</p><pre>@Injectable()<br>export class HttpErrorInterceptor implements HttpInterceptor {<br>    constructor(private injector: Injector) {}<br>    intercept(<br>        request: HttpRequest&lt;any&gt;,<br>        next: HttpHandler<br>    ): Observable&lt;HttpEvent&lt;any&gt;&gt; {<br>        return next.handle(request).pipe(<br>            catchError((response) =&gt; {<br>                if (<br>                    response instanceof HttpErrorResponse &amp;&amp;<br>                    response.error instanceof Blob &amp;&amp;<br>                    response.error.type === &quot;application/problem+json&quot;<br>                ) {<br>                    return new Promise&lt;any&gt;((resolve, reject) =&gt; {<br>                        const notificationService = this.injector.get(<br>                            NotificationService<br>                        );<br>                        const router = this.injector.get(Router);</pre><pre>                        if (response.status === 401) {<br>                            router.navigate([&quot;unauthorized&quot;]);<br>                        } else {<br>                            const reader = new FileReader();<br>                            reader.onload = (e: Event) =&gt; {<br>                                try {<br>                                    const error = JSON.parse(<br>                                        (&lt;any&gt;e.target).result<br>                                    );<br>                                    notificationService.error(error.title);<br>                                    reject(<br>                                        new HttpErrorResponse({<br>                                            error:<br>                                                error.title +<br>                                                &quot; / &quot; +<br>                                                error.detail,<br>                                            headers: response.headers,<br>                                            status: response.status,<br>                                            statusText: response.statusText,<br>                                            url: response.url<br>                                        })<br>                                    );<br>                                } catch (e) {<br>                                    reject(response);<br>                                }<br>                            };<br>                            reader.onerror = (e) =&gt; {<br>                                reject(response);<br>                            };<br>                            reader.readAsText(response.error);<br>                        }<br>                    });<br>                }</pre><pre>                return throwError(response);<br>            })<br>        );<br>    }<br>}</pre><p>And here is how we wire it up inside the core module (core.module.ts).</p><pre>providers: [<br>        {<br>            provide: HTTP_INTERCEPTORS,<br>            useClass: HttpErrorInterceptor,<br>            multi: true<br>        },<br>...</pre><p>Just a few quick points to make before we conclude.</p><p>We are taking advantage of Angular’s dependency injection mechanism to get a reference to the Notification service we got for free when we spliced in the ANMS starter kit.</p><p>We are also using dependency injection to get a hold of the Router, so that we can direct users to a “Unauthorized” page on 401 errors.</p><p>If possible, we try to display the custom error message that was set by our ASP.NET Core error handling middleware/function at the Web API side. While running in development, this will be the descriptive message of the exception that was thrown. When running in production, it will be a general error message.</p><p>As before, the expected HTTP response codes are being set in the response. However, now the UI is handling them by displaying a popup message, or redirecting to an error page, as you can see below.</p><p>ApplicationLayerException (400):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*X3EzQHIPsvB1DkFg.png" /></figure><p>NotFoundException (404):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*tw_O2IRncL40E7cn.png" /></figure><p>InvalidOperationException (500):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*l5lfcl6F6RojZcN5.png" /></figure><p>AuthorizationException (401):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*3TWvcGNku6yUP4is.png" /></figure><p>So far so good. We have successfully bridged the gap between ASP.NET Core and Angular, thereby presenting a much more seamless user experience for our application.</p><h3>Conclusion</h3><p>In this blog entry I went over the high-level architecture of our Clean Domain-Driven Design web application. I presented again those diagrams from previous entries showing the layering of our system, and showed the direction of exception flow when something goes wrong in the app. I briefly gave my professional opinion on best practices for naming, throwing, and handling exceptions. I explained the impossibility of trying to account for all error conditions in controller methods (i.e. don’t throw any exceptions) on the one hand and throwing exceptions gratuitously (i.e. using exceptions for flow control) on the other. I presented my opinion that neither approach is right in the extreme, and that we should try to seek a middle ground. Then I went into different approaches for catching exceptions in the Web API using middleware, and how to serialize those exceptions across the wire using HTTP standards-compatible methodologies. Finally, I wrapped up by demonstrating how to respond to the error responses generated by the Web API in the Angular UI using HTTP interceptors, thus providing a better user experience.</p><h3>Housekeeping Matters</h3><p>I enjoy writing these blog entries and helping other developers, however I’m at a point right now where I need to prioritize my time in order to finish some other projects that I have on my plate. Therefore, I’m going to take a break from blogging for a few months in order to stay heads down and accomplish those goals. I may or may not write another blog entry here or there, time permitting, but for the most part you can expect radio silence from my end.</p><p>That being said, if you need to reach out to me, please do so! I’d be happy to answer any questions you have or discuss anything software development related. You can connect with me on LinkedIn, Twitter, Facebook, or Medium by clicking on the “connect/follow” links at the top of the main page of my blog, or you can contact me directly using the form at <a href="https://jacobsdata.com/">jacobsdata.com</a>.</p><p>Along the way, I’ll make a few updates to the demo application on GitHub. Now that <a href="https://docs.microsoft.com/en-us/dotnet/core/dotnet-five">.NET 5</a> has finally launched, there are lots of great new tools and features to try to incorporate into the app.</p><p>Happy coding!</p><h3>Experts / Authorities / Resources</h3><p>HTTP Status Codes (MDN Network) — <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status">https://developer.mozilla.org/en-US/docs/Web/HTTP/Status</a></p><p>RFC 7807 — <a href="https://tools.ietf.org/html/rfc7807">https://tools.ietf.org/html/rfc7807</a></p><p>Angular HttpInterceptor — <a href="https://angular.io/api/common/http/HttpInterceptor">https://angular.io/api/common/http/HttpInterceptor</a></p><p>Chain of Responsibility pattern — <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern</a></p><p>Andrew Lock</p><ul><li>Create Custom Error Handling Middleware — <a href="https://andrewlock.net/creating-a-custom-error-handler-middleware-function/">https://andrewlock.net/creating-a-custom-error-handler-middleware-function/</a></li><li>ASP.NET Core in Action — <a href="https://www.manning.com/books/asp-net-core-in-action-second-edition">https://www.manning.com/books/asp-net-core-in-action-second-edition</a></li></ul><p>Robert C. Martin (“Uncle Bob”)</p><ul><li>Clean Coder Home — <a href="http://cleancoder.com/">http://cleancoder.com</a></li><li>Clean Architecture — <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html</a></li></ul><p>Official Microsoft Docs</p><ul><li>Middleware — <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1">https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1</a></li><li>Authorization Policies — <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-3.1">https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-3.1</a></li><li>Authorization Handlers — <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authorization/resourcebased?view=aspnetcore-3.1">https://docs.microsoft.com/en-us/aspnet/core/security/authorization/resourcebased?view=aspnetcore-3.1</a></li></ul><p>This is entry #4 in the <a href="https://blog.jacobsdata.com/category/scaffold%20clean%20ddd%20web%20app">Scaffold Your Clean DDD Web App Series</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aee9d27a7c12" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-alchemy/global-exception-handling-in-asp-net-core-and-angular-aee9d27a7c12">Global Exception Handling in ASP.NET Core and Angular</a> was originally published in <a href="https://medium.com/software-alchemy">Software Alchemy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaffold Your Clean DDD Web Application — Part 3: Persistence, Tenancy, and the Data Model]]></title>
            <link>https://medium.com/software-alchemy/scaffold-your-clean-ddd-web-application-part-3-persistence-tenancy-and-the-data-model-daf24a8aa150?source=rss-a80f78e022fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/daf24a8aa150</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jacobs Data Solutions]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 03:39:03 GMT</pubDate>
            <atom:updated>2020-09-26T18:05:20.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scaffold Your Clean DDD Web Application — Part 3: Persistence, Tenancy, and the Data Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*Tn9-kasWb8teC0lR.png" /></figure><h3>Introduction</h3><p>In the previous blog entry, we started to add back in our authentication components. We’re going to pick up the pace a little bit and try to knock out more structural/boilerplate code so we can get back to the fun stuff — building out the Application layer workflows and Domain business logic, and playing around in the cloud with Microsoft Azure.</p><p>In this blog entry we will evolve our solution and the data model behind it, so that we can begin to see how user requests and interactions operate against a multitenant system. We’ll start by refactoring the persistence interfaces and implementations to make the solution more scalable in a split-stack CQRS architecture. Alongside this change, I’ll show you how you can use both Dapper and Entity Framework Core inside a single transaction/unit of work. Then we’ll add some new EF Core entities corresponding to the tenants and customers of our SaaS product. Finally, we’ll perform some cleanup across the data model classes so that the Persistence layer is more robust.</p><p>Caveat emptor: some of the approaches I’ll be using here may deviate from the canonical or “textbook” way of implementing these features that you may see in different tutorials and guides on the Web. In some cases, that’s because we’re just trying to get something working, and we’ll be revisiting that functionality more in-depth in the future. In other cases, the canonical approach may be too tedious or involve a prohibitively frustrating amount of boilerplate code and configuration which is simply not worth it for our demo application. I’ll try to make clear when and why I’m breaking from convention in these situations, though it’s impossible to cover <em>everything</em>.</p><p>Related to this point, there may be changes to the <a href="https://github.com/JacobsDataSolutions/OrgManager/releases/tag/Blog-Entry-11">demo app</a> that I just don’t have time to go over in exhaustive detail. That’s why I encourage you to take a look at the actual code and also, if you have any helpful suggestions, don’t hesitate to let me know.</p><h3>First Things First: Understand Our Multitenant Architecture and High-Level Approach</h3><p>Before reading ahead, it’d be worthwhile for you to revisit some of the concepts I outlined in the blog entry called <a href="https://blog.jacobsdata.com/2020/02/03/monoliths-microservices-and-multitenancy">Monoliths, Microservices, and Multitenancy</a>, as these will certainly apply to what I’m about to lay out. In particular, I’d like to talk about the high-level multitenant architecture of the application. As stated in that blog entry, our end goal with the demo app is to fully implement <strong>Template D: Single Application, Multiple Sharded Multitenant Databases</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*0dH4CJPOu5pOa52A.png" /></figure><p>However, rather than going straight for that design, I’m going to punt on this (American football term) and initially implement it as <strong>Template B: Single Application, Single Multitenant Database</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/0*T9JFW5U2z7o5mqZF.png" /></figure><p>This is not to say that we won’t be using the former design in the future — we definitely will, especially as the need to scale starts to become urgent. However, at this point we’ll be starting off more simply, because:</p><ol><li>Our fictional client is yelling at us to get something finished and up in the cloud so that they can see why they’re paying us.</li><li>Having a high-level understanding of where we ultimately want to be, we can consciously and appropriately build out the Application layer in such a way that it WILL scale in the future, once we need to make the shift to multiple application databases. For now, it will remain <em>database agnostic</em>, which is to say, unconcerned and unaware of which application database it is actually talking to.</li><li>As long as we abide by robust <a href="https://blog.jacobsdata.com/2020/01/27/basic-concepts-of-software-design-and-architecture">patterns and practices</a>, we can manage complexity in the present while preserving the flexibility to break apart our data model and corresponding data persistence abstractions and implementations into separate schemas down the road, which is the plan.</li></ol><p>Great, so with that design consideration out of the way, let’s talk about one more concern at a high level before we dig into the code. As stated in that previous blog entry, we decided that tenant ID absolutely should be part of the composite primary key of every single table which contains tenant data — i.e. <em>intra-tenant</em> tables.</p><p>However, an extremely impactful design decision must be made early in the development lifecycle regarding whether to have tenant ID come before ID in the composite primary key, or vice versa.</p><p>As the database experts in <a href="https://dba.stackexchange.com/questions/98118/composite-primary-key-in-multi-tenant-sql-server-database">this Stack Exchange question</a> point out, neither approach is perfect, and we must weigh the pros/cons of each before committing to a decision. This is critically important (and weighing this decision now is NOT premature optimization), as we don’t want to be changing the fundamental architecture of our application databases when the system is already in production and then have to deal with customer data migration issues.</p><p>As the Stack Exchange answer explains,</p><ol><li>Having the ID first in the index before the tenant ID will cause interleaving of data from separate clients within the same data page, along with data page contention issues, locking issues, etc.</li><li>Conversely, having the tenant ID first can cause parameter sniffing issues, index fragmentation, etc.</li></ol><p>The “best practice” for ordering of composite primary key columns is to place the most selective columns first, which would be a vote for option (1). However, to make the best decision for our application, we should ask ourselves what the most common use cases of the application will be. Will it be likely that users of the application will be making queries against the database that cut across tenant boundaries, for example querying ALL employees across ALL tenants? The answer is NO, absolutely not. We anticipate that 95% of the time users of the application will only be making queries against a single tenant. There might be some automated processes or power user functionalities which may cut across tenants, but that is the exception to the rule. We are willing to pay the cost of doing more index maintenance and/or de-parameterizing our queries around the tenant ID if necessary, because we are considering the majority use case. We will go with option (2).</p><h3>Refactoring the Data Persistence Abstractions and Implementations</h3><p>Now that we have that decision out of the way, let’s keep pushing ahead and make the necessary updates to our data schema, Application layer abstractions, and Persistence layer implementations based upon our chosen course of action.</p><p>We’ll start by refactoring our data persistence classes and interfaces, starting out in the Application layer and then moving into the Persistence layer.</p><p>We’ll be renaming our data persistence interfaces, and corresponding implementations, using the convention IApplication[Read|Write]Db[Context|Facade]. So, for example, IApplicationWriteDbContext or IApplicationReadDbFacade. This is much more meaningful than our previous naming convention (i.e. IOrgManagerDbQueryFacade) because it conveys:</p><ul><li>That the implementation is pointing to an application (client) database, and NOT the tenant master database, which we’ll build out later.</li><li>That the implementation is pointing to either a read-only or read/write database. Remember when I <a href="https://blog.jacobsdata.com/2020/02/19/a-brief-intro-to-clean-architecture-clean-ddd-and-cqrs">introduced Clean DDD and CQRS</a>, and I mentioned splitting the database into one or more read-only databases and one read/write database? We are now making a bold step in that direction. Starting out, we’re still only going to have one database. However, <em>our calling code inside the CQRS workflows won’t know that</em>. Because we are programming to abstractions, not concretes, whatever is behind those interfaces doesn’t matter and our solution will still scale. The only caveat is that a single CQRS command or query may never talk to both the read database and the read/write database inside a single workflow/unit of work (see diagrams below). If a CQRS command needs to hydrate domain entities from an application database to do its work (which very obviously will be the case), then it needs to read that data from the read/write database. Think back to Ghostbusters: <a href="https://youtu.be/wyKQe_i9yyo">Don’t cross the streams</a>.</li><li>That the implementation is either using Entity Framework Core (“Context”) or Dapper (“Facade”). This is also visible just by examining the properties and methods of each respective interface. Unfortunately, it is difficult to prevent those abstractions from leaking, as the underlying persistence technologies are so radically different. However, it’s still imperative that we keep them behind interfaces so that we have flexibility in switching out the databases behind them, or even having no database behind them at all, which will be the case in unit test scenarios.</li></ul><p>Our persistence interfaces now reside here in the Application layer project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/0*-DXeoIrg_7jVQKgq.jpg" /></figure><p>And the source code for each of them is as follows.</p><p><strong>IApplicationWriteDbContext</strong>:</p><pre>public interface IApplicationWriteDbContext<br>{<br>    IDbConnection Connection { get; }<br>    DbSet&lt;CurrencyEntity&gt; Currencies { get; }<br>    DatabaseFacade Database { get; }<br>    DbSet&lt;EmployeeManagerEntity&gt; EmployeeManagers { get; }<br>    DbSet&lt;EmployeeEntity&gt; Employees { get; }<br>    bool HasChanges { get; }<br>    DbSet&lt;PaidTimeOffPolicyEntity&gt; PaidTimeOffPolicies { get; }<br>    EntityEntry Entry(object entity);<br>    EntityEntry&lt;TEntity&gt; Entry&lt;TEntity&gt;(TEntity entity) where TEntity : class;<br>    Task&lt;int&gt; SaveChangesAsync(CancellationToken cancellationToken);<br>}</pre><p><strong>IApplicationReadDbFacade</strong>:</p><pre>public interface IApplicationReadDbFacade<br>{<br>    Task&lt;IReadOnlyList&lt;T&gt;&gt; QueryAsync&lt;T&gt;(string sql, object param = null, IDbTransaction transaction = null, CancellationToken cancellationToken = default);<br>    Task&lt;T&gt; QueryFirstOrDefaultAsync&lt;T&gt;(string sql, object param = null, IDbTransaction transaction = null, CancellationToken cancellationToken = default);<br>    Task&lt;T&gt; QuerySingleAsync&lt;T&gt;(string sql, object param = null, IDbTransaction transaction = null, CancellationToken cancellationToken = default);<br>}</pre><p><strong>IApplicationWriteDbFacade</strong>:</p><pre>public interface IApplicationWriteDbFacade : IApplicationReadDbFacade<br>{<br>    Task&lt;int&gt; ExecuteAsync(string sql, object param = null, IDbTransaction transaction = null, CancellationToken cancellationToken = default);<br>}</pre><p>Right off the bat, there are some obvious changes that you might notice from the previous code implementation. For one, we have split the Dapper DB facade into two interfaces, as described above. The write DB facade derives directly from the read DB facade, which means that it can do everything that the read DB facade can, except it’s connecting to the read/write database instead of the read database. This is important, as we want to have the flexibility to perform queries against the read/write database.</p><p>Also, you’ll notice that the methods exposed on both of the DB facades now accept an IDbTransaction as an optional parameter. In CQRS commands and other units of work against the read/write database, we would like to be able to use both Entity Framework Core AND Dapper <em>inside the same database transaction</em>. This is a sophisticated design pattern. However, we want our system to be great, right? We want to have the flexibility to easily query the read/write database or perform sweeping updates such as complex delete operations. Dapper provides this. At the same time, we want the convenience of being able to update the database using aggregate objects, without worrying so much about the relationships between the underlying tables. Entity Framework Core provides this.</p><p>A picture (or four) is worth a thousand words, so here are a couple of diagrams showing what our new persistence interfaces and implementations look like, and how they communicate with the databases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*BecV_WYysL6mpcSA.png" /></figure><p>It’s a no-brainer to just have IApplicationWriteDbFacade inherit from IApplicationReadDbFacade, since it will share the same query methods. However, the implementation of that interface will be connected to the read/write database, NOT the read database.</p><p>Next, you can see that all CQRS queries will use IApplicationReadDbFacade to query data from the read database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*I9NlGw_puTva1uWf.png" /></figure><p>There are a couple of points to make here:</p><ol><li>There is no IApplicationReadDbContext. Why? This is a design decision on my part to only use Dapper to read data from the read database, and not use EF Core at all for query operations. There’s nothing to stop us from changing course and writing LINQ queries against such a context at some later point, but for now let’s keep it simple and use Dapper to get the job done.</li><li>IApplicationReadDbFacade always connects to the read database, never the read/write database. The read database is assumed to be a faithful snapshot of the read/write database, which happens through eventual consistency. Now, as stated earlier, at this point in time the read database and the read/write database are one and the same. However, we don’t want to paint ourselves into a corner as the solution scales, so we enforce a division between the two early on by intentionally separating our persistence components in this way.</li></ol><p>On to the CQRS commands…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*pGNmQPNXgUTakbwT.png" /></figure><p>You’ll notice a little more flexibility on the write side of the stack. It’s a design decision particular to each individual CQRS command workflow whether to inject IApplicationWriteDbFacade, IApplicationWriteDbContext, or both. Either the DB facade or the DB context can be used to read data from the read/write database in addition to updating the database. This works great and provides the ultimate in versatility, <em>as long as both are connected to the same database</em>.</p><p>DO NOT DO THIS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*7IW9iP0sLjqq9St-.png" /></figure><blockquote><em>Egon: Don’t cross the streams.</em></blockquote><blockquote><em>Peter: Why?</em></blockquote><blockquote><em>Egon: It would be bad.</em></blockquote><blockquote><em>Peter: I’m fuzzy on the whole good/bad thing. What do you mean “bad”?</em></blockquote><blockquote><em>Egon: Try to imagine all life as you know it stopping instantaneously and every molecule in your body exploding at the speed of light.</em></blockquote><blockquote><em>Raymond: Total protonic reversal.</em></blockquote><blockquote><em>Peter: That’s bad. Okay. Alright, important safety tip, thanks Egon.</em></blockquote><blockquote><em>- Ghostbusters</em></blockquote><p>I know it sounds like I’m beating a dead horse here, but I want to drive home the point that it’s a really bad idea to rely upon persistence components which could conceivably be connected to entirely separate data stores within the same transaction. I’ve actually witnessed errors in corporate systems that were caused by this exact anti-pattern — a lag of just a few milliseconds, even between databases in the same SQL Server availability group, could be enough to cause data inconsistency and hose the logic in your CQRS command. Don’t do it. Furthermore, as the application scales, how will we even know that whatever implementation is behind IApplicationReadDbFacade is even connected to a <em>database</em>? There could be some other kind of storage technology, like a caching layer, sitting behind it. If that’s the case, then there would be a huge disparity between what you’re reading from and writing to the data store.</p><p>This is all well and good on paper, but there’s a small catch — EF Core and Dapper don’t necessarily play nice together, or at the very least they weren’t designed with this use case in mind. That’s why we’ve decided to expose more EF Core details in IApplicationWriteDbContext, such as the Database property, and unfortunately it will take a small amount of trickery to make them work together since EF Core uses a different transaction class. Without getting too far ahead of ourselves, here’s what such an implementation might look like in practice:</p><pre>public MyCommandHandler(<br>    IApplicationWriteDbContext context,<br>    IApplicationWriteDbFacade facade<br>{<br>    this.context = context ?? throw new ArgumentNullException(nameof(context));<br>    this.facade = facade ?? throw new ArgumentNullException(nameof(facade));<br>}</pre><pre>public async Task&lt;MyViewModel&gt; Handle(MyCommand request, CancellationToken cancellationToken)<br>{<br>    ...<br>    using (var transaction = await context.Database.BeginTransactionAsync())<br>    {<br>        var sqlTransaction = transaction.GetDbTransaction();<br>        await facade.ExecuteAsync(<br>            @&quot;DELETE FROM Tenants WHERE …&quot;, null, sqlTransaction);<br>        await context.Tenants.AddAsync(tenantEntity);<br>        await context.SaveChangesAsync();<br>        await transaction.CommitAsync();<br>    }<br>    return ...<br>}</pre><p>Once again, the above is a contrived example, but it shows how this can be accomplished in practice. Using Dapper and Entity Framework Core together in the same transaction is an incredibly powerful technique and provides a great deal of flexibility. We can have our cake and eat it too.</p><h3>Cleaning Up and Enhancing the Data Model</h3><p>As it stands, we have a TenantId column on various application database tables, and it is part of the clustered primary index, which is great (once again, this enforces a hard division between tenants and helps prevent leakage of tenant-specific data across tenant boundaries). What’s missing, though, is the ability to manage tenants themselves. We’re going to remedy that deficiency of the data model with the addition of three new EF Core entities/database tables:</p><ul><li>Customers – Maintains information about the paying customers of our SaaS product.</li><li>Tenants – Maintains information about each tenant itself, including an &quot;assignment key&quot; (basically a GUID which will be used to aid in adding employees to the system), a slug (URL fragment which we will be using to route users to the proper tenant in Angular), and a reference to the customer who owns the tenant.</li><li>TenantAspNetUsers – A join table which specifies which users of the system have access to each tenant. The many-to-many relationship represented by this table is necessary because we don’t want to assume that each user will only have access to a single tenant. For example, what if a certain user is an employee of multiple companies? Or an employee of one but an administrator of several of them? These are possible real-life scenarios that we want to be prepared for.</li></ul><p>Here’s what our new EF Core entities look like for those tables.</p><pre>public class CustomerEntity : AuditableDbEntity, IAddressEntity<br>{<br>    public string Address1 { get; set; }<br>    public string Address2 { get; set; }<br>    public int AspNetUsersId { get; set; }<br>    public string City { get; set; }<br>    public int? CompanyId { get; set; }<br>    public CurrencyEntity Currency { get; set; }<br>    public string CurrencyCode { get; set; }<br>    public string FirstName { get; set; }<br>    public int Id { get; set; }<br>    public string LastName { get; set; }<br>    public string MiddleName { get; set; }<br>    public string State { get; set; }<br>    public ICollection&lt;TenantEntity&gt; Tenants { get; set; }<br>    public Title? Title { get; set; }<br>    public string Zip { get; set; }<br>    public CustomerEntity()<br>    {<br>        Tenants = new HashSet&lt;TenantEntity&gt;();<br>    }<br>}</pre><pre>public class TenantEntity : AuditableDbEntity<br>{<br>    public ICollection&lt;TenantAspNetUserEntity&gt; AspNetUsers { get; set; }<br>    public Guid AssignmentKey { get; set; }<br>    public CustomerEntity Customer { get; set; }<br>    public int CustomerId { get; set; }<br>    public ICollection&lt;EmployeeEntity&gt; Employees { get; set; }<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public string Slug { get; set; }<br>    public TenantEntity()<br>    {<br>        Employees = new HashSet&lt;EmployeeEntity&gt;();<br>        AspNetUsers = new HashSet&lt;TenantAspNetUserEntity&gt;();<br>    }<br>}</pre><pre>public class TenantAspNetUserEntity : IDbEntity<br>{<br>    public int AspNetUsersId { get; set; }<br>    public TenantEntity Tenant { get; set; }<br>    public int TenantId { get; set; }<br>}</pre><p>We’ll also need to update the DB context and add EF configuration classes for these entities. While we’re at it, we’ll clean up the other configuration classes as well. What we implemented before was fine for a first pass, yet we can do better. Before looking at the new code and my explanation of changes, take a look at the EmployeeEntityConfiguration class as we had initially implemented it, and see if you can make a list of code smells or areas of improvement that are present.</p><pre>public class EmployeeEntityConfiguration : ConfigurationBase&lt;EmployeeEntity&gt;<br>{<br>    public override void Configure(EntityTypeBuilder&lt;EmployeeEntity&gt; builder)<br>    {<br>        base.Configure(builder);<br>        builder.HasKey(e =&gt; new { e.TenantId, e.Id });<br>        builder.Property(e =&gt; e.Id).UseIdentityColumn();<br>        builder.Property(e =&gt; e.Address1).HasMaxLength(50);<br>        builder.Property(e =&gt; e.Address2).HasMaxLength(15).IsRequired(false);<br>        builder.Property(e =&gt; e.City).HasMaxLength(30);<br>        builder.Property(e =&gt; e.CurrencyCode).HasMaxLength(3);<br>        builder.Property(e =&gt; e.FirstName).HasMaxLength(25);<br>        builder.Property(e =&gt; e.LastName).HasMaxLength(25);<br>        builder.Property(e =&gt; e.MiddleName).HasMaxLength(25).IsRequired(false);<br>        builder.Property(e =&gt; e.PtoHoursRemaining).HasColumnType(&quot;decimal(18,4)&quot;);<br>        builder.Property(e =&gt; e.Salary).HasColumnType(&quot;decimal(18,4)&quot;);<br>        builder.Property(e =&gt; e.SocialSecurityNumber).HasMaxLength(11);<br>        builder.Property(e =&gt; e.State).HasMaxLength(2);<br>        builder.Property(e =&gt; e.Zip).HasMaxLength(10);</pre><pre>        builder.HasOne(e =&gt; e.Currency).WithMany();<br>        builder.HasOne(e =&gt; e.PaidTimeOffPolicy).WithMany().HasForeignKey(e =&gt; new { e.TenantId, e.PaidTimeOffPolicyId });<br>    }<br>}</pre><p>Do you have your list? OK, let’s see how we can improve this. See if your list is similar to mine.</p><ol><li>What stands out the most? The most glaring issue, in my opinion, is the numbers. Magic numbers, that is. This is a code smell as old as high-level programming languages. Each of the string properties which are calling the HasMaxLength() fluent configuration method has a hard-coded numerical length. We should be using constants here. In the new implementation, as you’ll see, we’ve created a Lengths static class, and we will be using the constant field lengths across both EF Core entities and Application layer validation classes. This lends a robustness to our code and consistency across the data model. For example, you may be looking at an address column in a particular table and you will be assured that <em>it is the same length as any other address column in any other table</em>.</li><li>There’s a similar problem with the decimal type properties, such as PtoHoursRemaining. Hard coding the column type as decimal(18,4) is not robust. These magic values must also be replaced with constants.</li><li>Properties which don’t require a time component should have their column type explicitly specified also, so we’ll create a constant for SQL date and set that as the SQL type for properties like DateHired, etc. Note that properties which require a time component (such as the CreatedUtc property) will get implemented as DateTime2 in the database by default, so there’s nothing we need to change there.</li><li>The properties corresponding to primary key columns — TenantId and Id—should be clearer about how their values are generated. More specifically, the Id column should be an identity column, which means that SQL Server will generate those values incrementally for us. On the other hand, the TenantId column should not be an identity column—we must always provide that value. We’ll add fluent method calls to the configuration class to make this explicit to EF Core.</li></ol><p>Here’s a better implementation of the EmployeeEntityConfiguration class.</p><pre>public class EmployeeEntityConfiguration : ConfigurationBase&lt;EmployeeEntity&gt;<br>{<br>    public override void Configure(EntityTypeBuilder&lt;EmployeeEntity&gt; builder)<br>    {<br>        base.Configure(builder);<br>        builder.HasKey(e =&gt; new { e.TenantId, e.Id });<br>        builder.Property(e =&gt; e.TenantId).ValueGeneratedNever();<br>        builder.Property(e =&gt; e.Id).UseIdentityColumn().ValueGeneratedOnAdd();<br>        builder.Property(e =&gt; e.Address1).HasMaxLength(Lengths.Address1).IsRequired();<br>        builder.Property(e =&gt; e.Address2).HasMaxLength(Lengths.Address2);<br>        builder.Property(e =&gt; e.City).HasMaxLength(Lengths.City).IsRequired();<br>        builder.Property(e =&gt; e.CurrencyCode).HasMaxLength(Lengths.CurrencyCode).IsRequired();<br>        builder.Property(e =&gt; e.FirstName).HasMaxLength(Lengths.FirstName).IsRequired();<br>        builder.Property(e =&gt; e.LastName).HasMaxLength(Lengths.LastName).IsRequired();<br>        builder.Property(e =&gt; e.MiddleName).HasMaxLength(Lengths.MiddleName);<br>        builder.Property(e =&gt; e.PtoHoursRemaining).HasColumnType(PersistenceLayerConstants.SqlDecimalType);<br>        builder.Property(e =&gt; e.Salary).HasColumnType(PersistenceLayerConstants.SqlDecimalType);<br>        builder.Property(e =&gt; e.SocialSecurityNumber).HasMaxLength(Lengths.SocialSecurityNumber);<br>        builder.Property(e =&gt; e.State).HasMaxLength(Lengths.State).IsRequired();<br>        builder.Property(e =&gt; e.Zip).HasMaxLength(Lengths.Zip).IsRequired();</pre><pre>        builder.Property(e =&gt; e.DateOfBirth).HasColumnType(PersistenceLayerConstants.SqlDateType);<br>        builder.Property(e =&gt; e.DateHired).HasColumnType(PersistenceLayerConstants.SqlDateType);<br>        builder.Property(e =&gt; e.DateTerminated).HasColumnType(PersistenceLayerConstants.SqlDateType);</pre><pre>        builder.HasOne(e =&gt; e.Currency).WithMany().OnDelete(DeleteBehavior.NoAction).HasForeignKey(e =&gt; e.CurrencyCode);<br>        builder.HasOne(e =&gt; e.Tenant).WithMany(e =&gt; e.Employees).HasForeignKey(e =&gt; e.TenantId);<br>        builder.HasOne(e =&gt; e.PaidTimeOffPolicy).WithMany().OnDelete(DeleteBehavior.NoAction).HasForeignKey(e =&gt; new { e.TenantId, e.PaidTimeOffPolicyId });<br>    }<br>}</pre><h3>Applying the Data Model Changes</h3><p>OK, great. The data model is looking much better, however we have one more task to complete before we wrap up, which is to add the new Entity Framework Core code migration so that our changes are reflected in the database schema. We could apply the changes as a new migration on top of the previous migration. However, these are sweeping enhancements to the data model, and since our system isn’t yet in production, we’ll blow away the previous migration and create these as an entirely new primary code migration.</p><p>From a Developer Command Prompt, inside the JDS.OrgManager.Persistence folder, we execute the following commands:</p><pre>dotnet ef database update 0<br>dotnet ef migrations remove<br>dotnet ef migrations add InitialRefactored</pre><p>If all goes well, then the new migration will be added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/0*WMMGr1uc-C6yQQOH.jpg" /></figure><p>We’re not done yet though. I’ll now show you how to manually add foreign key relationships to our freshly-scaffolded migration, so that we have relationality between the ASP.NET Core identity tables, namely AspNetUsers, and our application tables, such as Customers and TenantAspNetUsers. The approach I’ll demonstrate is the only viable way to accomplish this, unfortunately, because we really don’t want to mess around with having the same tables inside both the identity DB context and the application DB context, and as far as I know, there is no way for EF Core to create relationships between tables in separate contexts via configuration.</p><p>You may be a little skeptical and say that we have violated the separation of Persistence and Infrastructure concerns by doing this, and you would be right. However, the intent is that this is a non-permanent design decision which can stay in place until we are ready to break apart the database into separate application databases, tenant master databases, identity, etc.</p><p><strong>👓Developer commentary</strong>: I’ve actually fought religious wars over whether to use foreign keys at all, or to exclude them entirely. While there may be some perceived merits to not having them, my perspective is this: consciously choosing to NOT use foreign keys in an application database, especially when you’ve also committed to using an ORM like EF Core, is an incredibly myopic and bone-headed decision, for which you will pay dearly in both time and money as your solution scales. Foreign keys are guard rails which preserve the integrity of your customers’ data, and that data is the single most important asset of any information organization. I’d go so far as to say that it’s even debatable what kind of a performance boost, if any, you would hypothetically gain from leaving out foreign keys since now there’s no index on those columns that you’re joining against. For more information on this, I suggest you read <a href="https://www.oreilly.com/library/view/sql-antipatterns/9781680500073/">SQL Antipatterns</a>, by Bill Karwin, specifically the chapter entitled “Keyless Entry.”</p><p>OK, getting back on track. We’re going to manually add foreign key relationships between the AspNetUsers table and our application tables, <em>knowing full well that they will probably go away at some point</em> when we split the database into separate schemas. That’s perfectly fine. The idea is that they will support us during this phase of development.</p><p>Under the “migrations” folder in the JDS.OrgManager.Persistence project, there should be a file there called 20200920182315_InitialRefactored.cs or something like that. This is the migration added by EF Core. Unlike the auto-generated files that get created by typical scaffolding tools in the Microsoft stack, <em>these are meant to be modified by you, the developer</em>. Partial classes aren’t necessary, just go in and start modifying the code.</p><p>First, we’ll modify the Up() method. This gets called when applying the migration to the database. At this point in time, one of the major shortcomings of EF Core is that there is no good way to declaratively specify the ordering of columns in the tables that get created for each entity. It seems to default to putting the key columns first, which is fine, but then it orders the other columns alphabetically, with inherited properties appearing first. By convention, I like to have the audit columns—CreatedBy, LastUpdatedBy, etc.—last in the table. So, for each of the tables that have them, unfortunately we need to manually reorder them in each call to the CreateTable() method. Do you remember my discussion of productivity features of Visual Studio <a href="https://blog.jacobsdata.com/2019/10/09/work-more-efficiently-and-effectively-with-visual-studio-2019-foundational-concepts-series">way back when</a>? Hotkeys come in handy for this. We’ll highlight the four rows in the method call corresponding to the audit columns and move them down to the bottom using ALT + Down Arrow.</p><p>Now we’ll manually create the foreign key relationship to AspNetUsers, which we accomplish inside the constraints lambda expression with another call to table.ForeignKey().</p><p>When we’re done, it should look like this:</p><pre>migrationBuilder.CreateTable(<br>    name: &quot;Customers&quot;,<br>    columns: table =&gt; new<br>    {<br>        Id = table.Column&lt;int&gt;(nullable: false)<br>            .Annotation(&quot;SqlServer:Identity&quot;, &quot;1, 1&quot;),<br>        Address1 = table.Column&lt;string&gt;(maxLength: 50, nullable: false),<br>        Address2 = table.Column&lt;string&gt;(maxLength: 15, nullable: true),<br>        AspNetUsersId = table.Column&lt;int&gt;(nullable: false),<br>        City = table.Column&lt;string&gt;(maxLength: 30, nullable: false),<br>        CompanyId = table.Column&lt;int&gt;(nullable: true),<br>        CurrencyCode = table.Column&lt;string&gt;(maxLength: 3, nullable: false),<br>        FirstName = table.Column&lt;string&gt;(maxLength: 25, nullable: false),<br>        LastName = table.Column&lt;string&gt;(maxLength: 35, nullable: false),<br>        MiddleName = table.Column&lt;string&gt;(maxLength: 25, nullable: true),<br>        State = table.Column&lt;string&gt;(maxLength: 2, nullable: false),<br>        Title = table.Column&lt;int&gt;(nullable: true),<br>        Zip = table.Column&lt;string&gt;(maxLength: 10, nullable: false),<br>        CreatedBy = table.Column&lt;string&gt;(maxLength: 10, nullable: false),<br>        CreatedUtc = table.Column&lt;DateTime&gt;(nullable: false),<br>        LastModifiedBy = table.Column&lt;string&gt;(maxLength: 10, nullable: true),<br>        LastModifiedUtc = table.Column&lt;DateTime&gt;(nullable: true),<br>    },<br>    constraints: table =&gt;<br>    {<br>        table.PrimaryKey(&quot;PK_Customers&quot;, x =&gt; x.Id);<br>        table.ForeignKey(<br>            name: &quot;FK_Customers_Currencies_CurrencyCode&quot;,<br>            column: x =&gt; x.CurrencyCode,<br>            principalTable: &quot;Currencies&quot;,<br>            principalColumn: &quot;Code&quot;);<br>        // JDS<br>        table.ForeignKey(<br>            name: &quot;FK_Customers_AspNetUsers_AspNetUsersId&quot;,<br>            column: x =&gt; x.AspNetUsersId,<br>            principalTable: &quot;AspNetUsers&quot;,<br>            principalColumn: &quot;Id&quot;);<br>    });</pre><p>Near the end of the Up() method, we must also add an index as well.</p><pre>// JDS<br>migrationBuilder.CreateIndex(<br>    name: &quot;IX_Customers_AspNetUsersId&quot;,<br>    table: &quot;Customers&quot;,<br>    column: &quot;AspNetUsersId&quot;);</pre><p>We’ll have to repeat this process for a few other tables, like Employees and TenantAspNetUsers. Once we’re done, we can apply our modified schema to the database.</p><p>Hit CTRL + B to see if the solution builds, and then at the command line type:</p><pre>dotnet ef database update</pre><p>If we look at the schema in SQL Server Management Studio, we can see that our updates to the database have been applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4fSWrmU4tzpQohTl.png" /></figure><p>I’ll make a few comments about the schema, and then we’ll wrap up. I added color highlighting to the tables to help clarify.</p><ol><li>The ASP.NET Core Identity tables are highlighted in green. These are associated with AppIdentityDbContext and the migrations in the Infrastructure project.</li><li>The new tables that we added to the application DB context are highlighted in light blue. As the solution evolves, we’ll see that these belong to their own special bounded context, which we can just refer to as Customers/Billing for the time being. What’s interesting to note is that these all operate outside the bounds of any individual tenant. They represent a <em>supra-tenant</em> area of our data model, and at this point in time it doesn’t make sense to add domain entities corresponding to these tables to the Domain layer since we’re only going to perform CRUD operations against them (though that will probably change down the road, depending on how complex the billing logic needs to be).</li><li>The original application tables — Employees, EmployeeManagers, PaidTimeOffPolicies—have been left in gray. If you’ve been following along from previous blog entries, you’ll recall that these correspond to the Human Resources bounded context. These represent the intra-tenant area of our data model that I mentioned earlier, and you should notice that TenantId: * is a member of every one of those tables * is part of the corresponding composite primary key for each of those tables * is also a member of every single foreign key relationship between intra-tenant tables.</li><li>Read that last sentence again and make sure you fully understand what I’m trying to get across. The point is that the business logic which will ultimately be dependent upon those tables will have no idea that it’s operating inside of a tenant. In other words, that business logic will be <em>tenant agnostic</em>. Toward that end, we’re enforcing those tenant boundaries all the way down to the core of our data model, in both primary and foreign keys. This will make for a more robust solution and preserve data integrity going forward.</li><li>The foreign key relationships that we manually added are highlighted in red. We’ll keep these in mind as the solution grows just so that we’re aware that they’re provisional and may go away at some point.</li></ol><p>The data model is starting to look like something, and we’re ready to move on.</p><h3>Conclusion</h3><p>We started out by revisiting the different multitenant architectural templates and declaring which ones we were going to implement, namely <strong>Template D: Single Application, Multiple Sharded Multitenant Databases</strong> via <strong>Template B: Single Application, Single Multitenant Database</strong>. Then we again discussed the topic of the ordering of columns in the clustered primary index, specifically, whether TenantId should come first in intra-tenant tables. We decided that it should, even though there could be some performance issues down the road—the benefit is worth the cost. Next, we refactored the database interfaces and abstractions, breaking them up into read/write varieties and further dividing them into &quot;facades&quot; (Dapper) and &quot;contexts&quot; (Entity Framework Core). I talked about why it’s a really bad idea to use read facades in a CQRS command/write unit of work (&quot;crossing the streams&quot;). I mentioned how we can use Dapper and EF Core together in the same transaction, and why it’s beneficial to do so even though they are technologies which might seem to be orthogonal at first blush. We cleaned up the EF Core entity configuration files, making the relationships and constraints clearer and also removing magic values, which increases the maintainability of the code. Finally, we modified the EF Core code migration that we previously added by hand in order to create foreign key relationships between application and identity tables in the database, as well as reorder the columns of our tables. It was a lot of work, but our application is starting to shape up.</p><h3>Experts / Authorities / Resources</h3><ul><li><a href="https://dba.stackexchange.com/questions/98118/composite-primary-key-in-multi-tenant-sql-server-database">Composite Primary Key in multi-tenant SQL Server database</a></li><li><a href="https://github.com/StackExchange/Dapper">Dapper</a></li><li><a href="https://docs.microsoft.com/en-us/ef/core/">Entity Framework Core</a></li><li><a href="https://www.oreilly.com/library/view/sql-antipatterns/9781680500073/">SQL Antipatterns, by Bill Karwin</a></li></ul><p>This is entry #3 in the <a href="https://blog.jacobsdata.com/category/scaffold%20clean%20ddd%20web%20app">Scaffold Your Clean DDD Web App Series</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daf24a8aa150" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-alchemy/scaffold-your-clean-ddd-web-application-part-3-persistence-tenancy-and-the-data-model-daf24a8aa150">Scaffold Your Clean DDD Web Application — Part 3: Persistence, Tenancy, and the Data Model</a> was originally published in <a href="https://medium.com/software-alchemy">Software Alchemy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaffold Your Clean DDD Web Application — Part 2: Authentication and Identity]]></title>
            <link>https://medium.com/software-alchemy/scaffold-your-clean-ddd-web-application-part-2-authentication-and-identity-153962f835cb?source=rss-a80f78e022fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/153962f835cb</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jacobs Data Solutions]]></dc:creator>
            <pubDate>Tue, 15 Sep 2020 13:58:12 GMT</pubDate>
            <atom:updated>2020-09-15T13:58:12.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scaffold Your Clean DDD Web Application — Part 2: Authentication and Identity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*FMd1Xo5zhmRX10SI.jpg" /></figure><p>Image by <a href="https://pixabay.com/users/PublicDomainPictures-14/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=315266">PublicDomainPictures</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=315266">Pixabay</a></p><h3>Introduction</h3><p>In my previous blog entry we left off with a Web API project that doesn’t really do anything, and a UI that has been stripped of all non-essential features and is essentially bare bones. In this entry, we’ll start to add in more structural elements, namely the authentication components of the UI and Identity Model classes in our Web API. Fortunately, ASP.NET Core and Visual Studio do a lot of this work for us via scaffolding tools. Our main concern is to take this auto-generated code, modify it where needed, and move it into the appropriate layers of our Clean Architecture solution, namely the Infrastructure and Presentation layers.</p><h3>Step 1: Relocate and Customize the Identity Model Classes</h3><p>As you can see by looking at Solution Explorer, ASP.NET Core has generated a few different components automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/0*S1e1MAT7aI4RL3zT.jpg" /></figure><p>These include a login partial view, OIDC controller, and Entity Framework Core classes which represent the data model for Identity. As in previous versions of ASP.NET, an ApplicationUser class is also added which inherits from IdentityUser, but otherwise has no properties. This class is a hook, or extension point, from which we can provide additional properties for users of the application, and which will be persisted to the database which we will generate from our EF Core Identity model.</p><p>In keeping with our Clean DDD approach, it doesn’t make sense to keep the Identity Model classes in the Web API project, as that represents our Presentation layer, and Identity is not a Presentation concern. The next logical step, then, is to move these classes into the Infrastructure project. Obviously, we will change the namespaces of those classes along the way, and we will add in additional helper classes to integrate with Entity Framework Core.</p><p>As part of this transition, we’ll be adding in some more NuGet packages, as well, namely those having to do with ASP.NET Core Identity, though now is a good time to toss in MediatR as well.</p><p>Rather than talk about each change in excruciating detail, I’d suggest you simply look at the code yourself on GitHub, which you can access <a href="https://github.com/JacobsDataSolutions/OrgManager/releases/tag/Blog-Entry-10">here</a>. By clicking on the link to the commit corresponding to this blog entry, you can see a nice diff of the code changes.</p><p>There is one design decision worth mentioning, however, which is changing the data type of the Id column of the AspNetUsers table. Without getting too deep into the weeds, this is the table which corresponds to the Identity model’s IdentityUser class, and which gets created by EF Core migrations.</p><p>Pay attention: this is important. By default, the ApplicationUser class inherits from IdentityUser, which itself is basically equivalent to IdentityUser&lt;string&gt;. That generic parameter specifies the data type of the primary key. By default, ASP.NET Core Identity uses a string (varchar(450)) and slams a GUID (Globally Unique Identifier) in there for each user that signs up. This doesn’t work for our use case, because we will be using the user ID as a member of a composite primary key on a number of tables (such as the TenantAspNetUsers table, once we get to that point), and there are hard restrictions imposed by SQL Server on the size of primary keys. For this and other reasons that will become clear as we evolve the solution, we must change the ID type from string to int.</p><p>We do this by changing the declaration of the ApplicationUser class from this:</p><pre>public class ApplicationUser : IdentityUser<br>{<br>}</pre><p>to this:</p><pre>public class ApplicationUser : IdentityUser&lt;int&gt;<br>{<br>}</pre><p>On the surface it seems like a trivial change, however, we have fundamentally changed the referential structure of our data schema going forward, and this has wide-reaching design implications for the architecture of the entire solution. As I stated at the <a href="https://blog.jacobsdata.com/2020/01/27/basic-concepts-of-software-design-and-architecture">very beginning</a>, there is no silver bullet in software development. One downside to this decision is that it will make it harder to maintain data consistency across database boundaries (i.e. referencing the same ASP.NET Core user in multiple tenant databases). However, being able to use the user ID in composite primary keys is well worth that cost. Furthermore, there is nothing stopping us from adding a non-key GUID column alongside the integer user ID.</p><p>There’s another pain point associated with this change. Since the default Identity DbContext that ASP.NET Core scaffolds for us derives from ApiAuthorizationDbContext, it still expects IdentityUser types which have a string primary key for the ID column. We need to overhaul the AppIdentityDbContext (which we renamed from ApplicationDbContext) as well. Once again, I’m not going to go into great detail, but in a nutshell all I did was look at the source code for ASP.NET Core, which you can find on GitHub <a href="https://github.com/dotnet/aspnetcore">here</a>, and I customized it to fit my needs.</p><p>The source for AppIdentityDbContext has now gone from this:</p><pre>public class AppIdentityDbContext : ApiAuthorizationDbContext&lt;ApplicationUser&gt;<br>{<br>    public AppIdentityDbContext(<br>        DbContextOptions options,<br>        IOptions&lt;OperationalStoreOptions&gt; operationalStoreOptions) : base(options, operationalStoreOptions)<br>    {<br>    }<br>}</pre><p>to this:</p><pre>public class AppIdentityDbContext : IdentityDbContext&lt;ApplicationUser, IdentityRole&lt;int&gt;, int&gt;, IPersistedGrantDbContext<br>{<br>    private readonly IOptions&lt;OperationalStoreOptions&gt; _operationalStoreOptions;</pre><pre>    public DbSet&lt;DeviceFlowCodes&gt; DeviceFlowCodes { get; set; }</pre><pre>    public DbSet&lt;PersistedGrant&gt; PersistedGrants { get; set; }</pre><pre>    public AppIdentityDbContext(<br>        DbContextOptions options,<br>        IOptions&lt;OperationalStoreOptions&gt; operationalStoreOptions) : base(options)<br>    {<br>        _operationalStoreOptions = operationalStoreOptions;<br>    }</pre><pre>    Task&lt;int&gt; IPersistedGrantDbContext.SaveChangesAsync() =&gt; base.SaveChangesAsync();</pre><pre>    protected override void OnModelCreating(ModelBuilder builder)<br>    {<br>        base.OnModelCreating(builder);<br>        builder.ConfigurePersistedGrantContext(_operationalStoreOptions.Value);<br>    }<br>}</pre><p>OK, great. Before moving forward, there’s one more change we’ll make, which is adding a boolean property to ApplicationUser called IsCustomer. This is the first application-specific change we’ll make to the Identity schema, but it’s important. As the application evolves, this will differentiate between paying users of our system—literally, our SaaS customers—and ordinary users of the system.</p><p>The ApplicationUser class now looks like this:</p><pre>public class ApplicationUser : IdentityUser&lt;int&gt;<br>{<br>    public bool IsCustomer { get; set; }<br>}</pre><p>However, our work isn’t done yet. If you look at the code from the demo solution, you’ll notice that I added some EF Core helper classes like AppIdentityDbContextFactory and so on. We will be blowing away the default EF migrations that got scaffolded with our project and then using those helper classes to create new migrations from the command line. Only then will we see the database changes that we implemented by altering the ApplicationUser class.</p><p>Delete these files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/0*IG1IkmPLJYHOAxN8.jpg" /></figure><p>For these next steps, you’ll likely need to drop the OrgManager database and then recreate it.</p><p>Hit CTRL-B to make sure that the solution builds, then go to a developer command prompt. Inside the JDS.OrgManager.Infrastructure directory, type the following:</p><pre>dotnet ef migrations add Initial<br>dotnet ef database update</pre><p>If everything goes according to plan, you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/0*pRYZCpYIGNo2AbQS.jpg" /></figure><p>and this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/0*DvaJPMZA3vwBVDGz.jpg" /></figure><p>If we look at the database, we can see that our customizations are now reflected in the schema of the Identity tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*BN5vd4wKUZDxFv6J.jpg" /></figure><p>Great, what’s next?</p><h3>Step 2: Move the Authentication/Login Components Back Into the UI</h3><p>Now that we’ve moved the Identity model classes into their proper place in the Infrastructure project and customized them to fit our needs, at least for the time being, we’re now ready to splice back in the authentication components that we set aside in the <a href="https://blog.jacobsdata.com/2020/09/02/scaffold-your-clean-ddd-web-application-part-1-set-up-the-ui">previous blog entry</a>.</p><p>In the ClientApp-old folder that we set aside, which contains the SPA that Visual Studio created for us by default, we’ll take the api-authorization folder and copy it back in to our solution in ClientApp/src folder.</p><p>Here it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/0*0nXw3KdOhR8iZkqi.jpg" /></figure><p>There are a couple more Angular-specific tweaks that are required to make this work, such as wiring these components into the core module, but I won’t go into too much detail here since these are basically just boilerplate changes. Rather, it’d be more intuitive to look at the GitHub tag that I’ve provided <a href="https://github.com/JacobsDataSolutions/OrgManager/releases/tag/Blog-Entry-10">here</a> so you can see a diff of those changes.</p><p>One notable change that I’ll post here is the login buttons on the app.component template. Angular Ngrx Material Starter puts placeholders there by default that don’t really do anything. Since it’s a starter kit, the point of course is that we’re supposed to wire in our own authentication components. That’s exactly what we’ll do.</p><p>This will go away:</p><pre>&lt;button mat-button mat-stroked-button color=&quot;accent&quot; *ngIf=&quot;!isAuthenticated&quot; (click)=&quot;onLoginClick()&quot;&gt;Login<br>  &lt;/button&gt;</pre><pre>  &lt;button *ngIf=&quot;isAuthenticated&quot;<br>	  mat-icon-button<br>	  [matMenuTriggerFor]=&quot;toolbarUserMenu&quot;&gt;<br>&lt;fa-icon icon=&quot;user-circle&quot;&gt;&lt;/fa-icon&gt;<br>  &lt;/button&gt;<br>  &lt;mat-menu #toolbarUserMenu=&quot;matMenu&quot;&gt;<br>&lt;button mat-menu-item (click)=&quot;onLogoutClick()&quot;&gt;<br>  &lt;mat-icon&gt;&lt;fa-icon icon=&quot;power-off&quot;&gt;&lt;/fa-icon&gt;&lt;/mat-icon&gt;<br>  &lt;span&gt;Logout&lt;/span&gt;<br>&lt;/button&gt;<br>  &lt;/mat-menu&gt;</pre><p>and get replaced with this</p><pre>&lt;span class=&quot;d-none d-md-inline&quot; *ngIf=&quot;!isAuthenticated&quot;&gt;<br>&lt;button mat-button mat-stroked-button color=&quot;accent&quot; [routerLink]=&#39;[&quot;/authentication/login&quot;]&#39;&gt;<br>  Sign in<br>&lt;/button&gt;<br>  &lt;/span&gt;</pre><pre>  &lt;span class=&quot;d-none d-md-inline&quot; *ngIf=&quot;isAuthenticated&quot;&gt;<br>&lt;button mat-button mat-stroked-button color=&quot;accent&quot; [routerLink]=&#39;[&quot;/authentication/profile&quot;]&#39;&gt;<br>  Profile<br>&lt;/button&gt;<br>&lt;button mat-button mat-stroked-button color=&quot;accent&quot; [routerLink]=&#39;[&quot;/authentication/logout&quot;]&#39; [state]=&#39;{ local: true }&#39;&gt;<br>  Logout<br>&lt;/button&gt;<br>  &lt;/span&gt;</pre><p>Now when we click on the login button…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*G9bwbzV8-OZ10f2y.jpg" /></figure><p>It should take us to the standard server-hosted login page that we get by default when using the ASP.NET Core project template, like you see here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*xvTCgVKdd_WxcbEG.jpg" /></figure><p>If we click on the Register link above, we should be able to navigate to the out-of-the-box ASP.NET Core registration page, like you see here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*NSm2qex35303VvPR.jpg" /></figure><p>We should be able to sign up and do a fake email confirmation (since no email senders are hooked up to the solution at this point).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/0*dsK-_VgncblceDxo.jpg" /></figure><p>Now we can go back to the login page and login with the email/password combination that we just entered. If everything goes well, then when we go back to the root path of our application, the login buttons will have changed to show us that we’re logged in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*XIjdFrBIXwcBx9aN.jpg" /></figure><p>Congratulations! We have successfully spliced together two different UI starter kits and created a working web application that provides registration, login, and logout functionality. The look and feel still leaves a lot to be desired, but that’s okay. At this time, we’re only concerned with getting the basic functionality working. If we pay a visit to our database, we can see that, indeed, our test user was persisted and we are good to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/0*sxUoypHiCqI4hHXI.jpg" /></figure><p>As stated earlier, there’s a lot going on under the hood in these OIDC components, and we don’t want to reinvent the wheel (and this is a wheel that you REALLY do not want to reinvent). So instead, we have put on our application architect hats and figured out a way to create a synthesis of two different UI starters so that we can leverage their respective features that we get “for free” right out of the box.</p><p>Now, as always, this blog entry has run a little bit long. However, there’s one more trick I want to show you before we wrap up.</p><h3>Step 3: Override Default Identity Views/Components</h3><p>As you’ve probably figured out, the login/OIDC views and boilerplate authentication logic are baked into the Microsoft.AspNetCore.Identity.* packages that get included in the Web API project when you click on “Change” under the authentication tab in the project setup wizard. But what if you want to change these views? Or customize the login behavior? Here’s how you do that.</p><p>In a nutshell, we will be piggybacking off the instructions presented <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity">here</a>.</p><p>Visual Studio provides the capability for us to scaffold individual Identity views and components into our solution, effectively allowing us to override the default UI and functionality that are compiled into the package.</p><h3>Detour: When Everything Doesn’t Go as Planned (Or Murphy’s Law in the Real World)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*ifne3ZB9zQfOUFiG.jpg" /></figure><p>Image by <a href="https://pixabay.com/users/sdmacdonaldmiller-1948403/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1180794">sdmacdonaldmiller</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1180794">Pixabay</a></p><p>Now, just to be totally transparent with you, the steps I’m about the outline didn’t go smoothly when I was applying them to the demo application. I thought everything was pretty cut and dry, yet when I tried to scaffold the ASP.NET Identity components using Visual Studio I kept getting an uninformative error stating, “There was an error running the selected code generator: ‘Package restore failed. Rolling back package changes…’”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/0*7GOgs_Aj0Tr5GwrJ.jpg" /></figure><p>These sorts of situations happen all the time, even to senior developers and architects, and this is why our profession is so hard — we are frequently confronted with novel, challenging obstacles which test our problem-solving capabilities to the max and often require a markedly right-brained, or creative process to overcome them.</p><p>One approach we could take to solve this type of problem is to try to debug into Visual Studio itself, or dig through various error logs (if we’re lucky enough to have logged the error). However, that can be painful and may or may not be a good use of our time.</p><p>Words of wisdom: beware of time sinks, or fruitless activities that lead nowhere. Strive to develop an innate knowing of when to grind through to a workable solution to the problem, and when to cut losses and try something else.</p><p>Another tool in our mental toolbox could be to use heuristics, or mental shortcuts, to arrive at an answer fast. This method of problem-solving is great <em>as long as the potential impact to the system and your business is low</em> (i.e. you aren’t making seat-of-your-pants changes to a system in production) and also if you’re not short-changing yourself the opportunity to learn a valuable lesson. After all, your goal is to learn software development at a deeper level and not just rely on Stack Overflow for all your answers, right?</p><p>As implied above, one heuristic is to simply plug the error message into Google/Bing/Stack Overflow and see if there’s a simple solution to the problem. I tried this, and only wound up with answers that were vague, or otherwise didn’t apply to my specific scenario.</p><p>Another heuristic is to make sure everything is up to date (NuGet packages, tools, everything). I tried this approach, and it did fix the problem for me. Rather than plow through and waste a bunch of time trying to figure out what the error message really meant, fully grok the root cause and all that, I simply updated all the NuGet packages in the solution to their latest versions and then I updated Visual Studio itself to the latest version. Guess what? It worked! I was able to start scaffolding components again, and all in all it took maybe 20–30 minutes to get back on track.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/23/0*dGv3tiQFFA446x_S.png" /></figure><p>Pro tip: when something breaks or isn’t working that otherwise seems straightforward, the first question you should ask yourself is, “What changed?” In this case, the NuGet package versions apparently had been updated to a newer version and were out of sync with the version of Visual Studio I was using.</p><p>If the above tactic didn’t work out for me, which is actually what I was expecting at first, then I was fully prepared to go back into the ASP.NET Core source code that I pulled off of GitHub and start copying in the necessary views and classes manually. As a matter of fact, you should be comfortable doing this yourself, because you’re likely to find yourself in situations in which you need to customize parts of the framework (like what I did with the ApiAuthorizationDbContext toward the beginning of this blog entry) and there may or may not be tools to help you with this. It’s not as hard as you think; just figure out the version numbers of the packages that you’re using in your solution and then look for the git tag corresponding to that version in the code repository, like what I’ve shown here. Check out that commit, find the code you’re looking for, and you’re good to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_96Nw6KAIROKjExL.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/23/0*XZX4tStHUlHIu6xM.png" /></figure><p>Pro tip: when confronted with a seemingly insurmountable obstacle, a proverbial brick wall, as it were, trying to go over it or through it may not be the best way. Sometimes you need to take a step back from the problem (“sleep on it”) and then ask yourself if there isn’t a way <em>around it</em>.</p><h3>Back on Track. Scaffolding the Registration Page</h3><p>Now that I’ve talked about what can go wrong, let’s focus on the workflow when everything is running smoothly. While there are a large number of components that you can scaffold into your solution, as you can see from the screenshot below, the only one that we’re concerned with right now is the Registration page. That’s because later on we will modify it in order to make it differentiate between two different types of users: customers (paying users of the system) and ordinary employees.</p><p>So, the first step is to right click on the Web Api project in the solution, and select “Add-&gt;New Scaffolded Item” from the context menu, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*1rK52gjrazaOUc3X.jpg" /></figure><p>From there, we select “Add Layouts for Razor Pages” to add the standard shared partial views to the project. Note that we only need to do this once for our solution, and we won’t be repeating this step when we start scaffolding in additional components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*eqm_Gx9T-nH9RmjI.jpg" /></figure><p>Keep the “Generate layout page” checkbox checked and click “Add.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*8MpGumhI6kCdShTC.jpg" /></figure><p>Next, right click on the project again and select “Add-&gt;New Scaffolded Item” from the context menu just like before. This time, however, select the Identity tab from the left, select “Identity” from the menu, and click “Add.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*IfRXKHl2ZqQqp2uK.jpg" /></figure><p>Select the proper layout page and EF Core Identity DB Context, as seen below, and click “Add.” Just to be clear, I moved around some of the views before doing this just as a matter of personal preference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/0*4NpbpZRo7LGOxRuG.jpg" /></figure><p>If everything has gone according to plan, then you should now have a new nested folder structure under “Areas” within the Web Api project, along with some Razor import files, partial views, and our now customizable Registration view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/0*1KD_x1rELFLIgPWT.jpg" /></figure><p>All in a day’s work.</p><h3>Conclusion</h3><p>In this blog entry I first showed how to move the auto-generated identity classes and EF Core database context out of the Web Api project, and into the Infrastructure project. I demonstrated how you can customize those pieces for your own solution, such as changing the AspNetUsers primary key type from string (varchar) to int. This is extremely important, because there is never a one-size-fits-all path in software development, and we are trying to prepare our solution for more complex use cases in the future, such as including the user ID as part of a composite primary key.</p><p>Next, I showed how to move the auto-generated api-authorization Angular components back into the UI and wire them up to the login/logout/register workflow of the user interface. This is an important step because, again, we don’t want to have to do tedious work that’s been done a million times before in other projects.</p><p>After that, I talked about what can go wrong when using automated scaffolding tools and attempted to impart some of my wisdom regarding how to go about solving software problems in general.</p><p>Finally, I went through the process of scaffolding the Registration page and associated Razor pages and components using the “Add New Scaffolded” Item wizard.</p><p>That’s plenty for now, and hopefully the next few steps for building out our application will go a little more smoothly. Happy coding!</p><h3>Housekeeping Matters</h3><p>I’m aware that I use a lot of expressions and mannerisms in my writing that are particular to native speakers of English, and especially Americans. Some of my readers, people from Germany, for example, may come across an expression like “no silver bullet” and immediately understand what I mean since that phrase comes from a common cultural heritage that we share (in this particular example, it refers to stories of mythological creatures called ‘werewolves’ that date as far back as the middle ages, or earlier). However, people from other parts of the world may read that phrase and have no idea what I’m talking about. You may wonder what the heck bullets made of silver have to do with software development. If this is the case, and if there’s any confusion in any section of these blog entries as to what I’m trying to say, please feel free to leave a polite comment in the comment section asking for clarity, or message me directly, and I’ll do my best to explain.</p><h3>Experts / Authorities / Resources</h3><ul><li><a href="https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-3.1&amp;tabs=visual-studio">MSDN — Scaffold Identity Components</a></li><li><a href="https://github.com/dotnet/aspnetcore">ASP.NET Core source code</a> on GitHub</li><li><a href="https://en.wikipedia.org/wiki/Werewolf">Werewolf</a> (Wikipedia)</li></ul><p>This is entry #2 in the <a href="https://blog.jacobsdata.com/category/scaffold%20clean%20ddd%20web%20app">Scaffold Your Clean DDD Web App Series</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=153962f835cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-alchemy/scaffold-your-clean-ddd-web-application-part-2-authentication-and-identity-153962f835cb">Scaffold Your Clean DDD Web Application — Part 2: Authentication and Identity</a> was originally published in <a href="https://medium.com/software-alchemy">Software Alchemy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaffold Your Clean DDD Web Application — Part 1: Set Up the UI]]></title>
            <link>https://medium.com/software-alchemy/scaffold-your-clean-ddd-web-application-part-1-set-up-the-ui-cb9e862ec626?source=rss-a80f78e022fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb9e862ec626</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Jacobs Data Solutions]]></dc:creator>
            <pubDate>Wed, 02 Sep 2020 13:31:48 GMT</pubDate>
            <atom:updated>2020-09-02T13:31:48.527Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scaffold Your Clean DDD Web Application — Part 1: Set Up the UI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*h1Iu4adnA9CDacko.jpg" /></figure><p><a href="https://pixabay.com/users/capri23auto-1767157/">Image credit: Capri23auto @ Pixabay</a></p><h3>Introduction</h3><p>This is the first in a multi-part series in which I will be building off the <a href="https://blog.jacobsdata.com/category/foundational%20concepts">Foundational Concepts Series</a>. If you haven’t read those yet, then I highly recommend you go back and familiarize yourself with the ideas I present in those entries. Going forward, I’ll make the assumption that you’re relatively familiar with basic programming concepts as well as those related to architecture, such as Layers of Abstraction, Loose-Coupling, etc. Especially important are the patterns and practices focused around <a href="https://blog.jacobsdata.com/2020/02/10/a-basic-intro-to-domain-driven-design">Domain-Driven Design</a>, <a href="https://blog.jacobsdata.com/2020/02/19/a-brief-intro-to-clean-architecture-clean-ddd-and-cqrs">Clean Architecture, and CQRS</a>, as those inform the high-level design of the <a href="https://github.com/JacobsDataSolutions/OrgManager/">demo solution</a>.</p><p>My objective is to present actual, procedural steps that you can follow and apply to your own web projects using ASP.NET Core. As I present these steps, I will be updating the demo application accordingly, the goal being to evolve it into a working web application by the end of this series.</p><p>Just to be totally transparent: the finished application will be a little rough around the edges. Actually, VERY rough around the edges. That’s okay. My intent is simply to demonstrate that Clean Domain-Driven Design works in modern web applications built on the ASP.NET Core stack. The desired end-product will be a multi-tenant SaaS product which can scale to accommodate complex business logic. I intend to revisit different areas of functionality in future blog series’, at which point we can make it more robust and enterprise worthy.</p><p>Another point I wanted to mention as we embark upon this phase of our journey is that I’ll be building out the user interface as a SPA (Single Page Application) using Angular 10. This choice is somewhat arbitrary and based upon my own preferences, and you may want to build your front end using a different framework, such as React, Blazor, or whatever you’re comfortable with.</p><p>(For any of you who may not be familiar with SPAs and how they work, there are <a href="https://en.wikipedia.org/wiki/Single-page_application">plenty of resources out there</a> to help you get familiar with the basic concepts. In a nutshell, the way they work is that a simple HTML page is rendered to the user with a single element on it, which acts as a placeholder for where the SPA will be loaded. After that, the SPA, which is essentially just a series of JavaScript libraries, gets loaded into the user’s browser and bootstraps itself. From there on, the application runs entirely in the user’s browser and dynamically manipulates the DOM (Domain Object Model) of the browser in order to present a user interface which resembles a watered-down desktop application. A high-level web protocol such as REST or GraphQL is used by the SPA to communicate back and forth to the server application from the user’s browser.)</p><p>Using my particular interpretation of Clean Domain-Driven Design, I’ll develop an architecture which is loosely-coupled enough that you can “peel off” the UI from the Presentation layer, and replace it with anything else that’s compatible with the web protocol of the SPA/server-side controllers (in the case of the demo app, REST).</p><h3>Scaffolding Tools and Projects — Do Not Reinvent the Wheel</h3><p>As it currently stands, the Presentation layer and user interface for our OrgManager demo application is a simple .NET Core console application with a bunch of hard-coded calls to CQRS workflows. That’s not very useful in practice, is it?</p><p>We’ll start moving the solution in the direction of actual web application by:</p><ol><li>Scaffolding a new ASP.NET Core Web API project into our solution, and</li><li>Removing the web UI from the ClientApp folder and replacing it with a pre-built starter project.</li></ol><p>Step A is fairly easy, as the web scaffolding tools are built right into Visual Studio. Step B is much more involved, as we will be removing features that aren’t useful to us at this time, changing around the structure of the project, and adding new components to communicate with our web API and present an interface to the user. Still, I prefer this approach rather than building the UI from scratch because:</p><ol><li>It saves us from having to write a lot of boilerplate code (and Angular is unfortunately a boilerplate-heavy framework).</li><li>We get a lot of features “for free,” which in theory eases the learning curve and accelerates development.</li></ol><p>So, without further adieu, let’s get started by scaffolding out the Web API.</p><h3>Using Visual Studio to Create a Web Api Project</h3><p>First, we’ll click on the solution and select “Add New Project”. From the list of project templates that comes up, we select “ASP.NET Core Web Application” and click Next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JYd1KINHikmhiqq8.jpg" /></figure><p>The name of this project will be JDS.OrgManager.Presentation.WebApi.</p><p>Click Create.</p><p>We are now presented with a series of specific web project templates. Select Angular and then click on “Change” under the Authentication section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m4Df8uPTxvh6qJrz.jpg" /></figure><p>A new dialog box appears allowing you to select either “No Authentication” or “Individual User Accounts.” Select “Individual User Accounts.” This will add the ASP.NET Core Identity packages and scaffolding to our Web Api project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/0*6De0NIBD4MWMWqye.jpg" /></figure><p>When we click OK and then Create, it’ll scaffold our Web Api project.</p><p>Now we will set JDS.OrgManager.Presentation.WebApi as our startup project and run our solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/0*P0kc3K0T02vL_Ov8.jpg" /></figure><p>As you can see, we have the standard “Hello World” application that gets scaffolded by default. All well and good, but not super useful for what we’re trying to do.</p><p>Pay attention; here’s where things can get a little tricky.</p><h3>Replacing the Default SPA User Interface with an Out-Of-Box Starter Project</h3><p>The plan is to blow away 90% of the default ClientApp UI and replace it with a starter UI project, while maintaining the critical login and user account components which are auto generated by ASP.NET Core. Specifically, I’m referring to the components inside ClientApp/src/api-authorization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/0*58dO_mrJYfa6lnYP.jpg" /></figure><p>These components use OIDC (OpenID Connect)/Oauth2 to authenticate users into our system.</p><p>Pro tip: Trying to roll your own login and authentication components will lead you down the path of pain, guaranteed. Don’t do it. I highly, highly recommend you use out of the box solutions whenever possible. As far as security components go, like password hashers and the like, DON’T EVER TRY TO ROLL YOUR OWN, as that is just downright dangerous and is a good way for your web app to get hacked.</p><p>Getting back on track. Our approach will be to set aside the ClientApp folder for now, replace it with a starter UI project, and then splice the OIDC/authentication components back into it at some future point.</p><p>Rename the ClientApp folder “ClientApp-old,” or something to that effect. You may need to exit from Visual Studio to do this.</p><p>Now let’s install the UI starter project. For the demo application, I picked a project called <a href="https://github.com/tomastrajan/angular-ngrx-material-starter">Angular NgRx Material Starter</a>. I think this is a good solution to use because it’s clean, neatly maintained, and provides a solid foundation for us to work off of. Additionally, I wanted to get a nice, professional-looking user experience (UX), and Angular Material provides that. Another great thing about starter kits like this is that if you have trouble understanding how to implement certain patterns or functionalities, you can just look at the code that’s already there for guidance, which is exactly what we are going to do.</p><p>Angular itself can be a daunting framework to use, and the various sub-frameworks and packages that are incorporated into it, such as Angular Material, NgRx, Reactive Forms, etc. take that complexity to a whole new level entirely. Once again, that’s why it’s great to have some working demos/examples to use as a reference, and ANMS includes those as well.</p><p>Inside the root folder for the WebApi project, we have renamed ClientApp to ClientApp-old and moved it to a different folder. Following the instructions from the above link, we now execute the following commands from a Developer Command Prompt window to install the new UI:</p><pre>git clone <a href="https://github.com/tomastrajan/angular-ngrx-material-starter.git">https://github.com/tomastrajan/angular-ngrx-material-starter.git</a> ClientApp</pre><pre>npm install</pre><pre>npm start</pre><p>If all goes well, then the UI should compile and a browser window should pop up pointing to <a href="http://localhost:4200/#/about.">http://localhost:4200/#/about.</a> You should see something that looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*W0IAEqNtVLWu8fhi.jpg" /></figure><p>Hooray, we now have a UI!</p><p>Now comes the fun part.</p><p>First, we will customize details of the new UI to fit our project, following the guidelines on the ANMS GitHub page.</p><p>Then we will remove components and features that we don’t need, or which are not important at this point in time from the UI project. At that time, we’ll also perform other cleanup tasks, upgrade the Node packages, etc.</p><p>In a future blog post, we will splice the authentication/OIDC components into the new UI, but let’s not get too far ahead of ourselves.</p><p>The second step (cleanup) might seem trivial on the surface, but it isn’t. Since we are early on in the development process, it is crucial that we stay diligent, keeping our <a href="https://blog.jacobsdata.com/2020/01/27/basic-concepts-of-software-design-and-architecture">patterns and practices</a> in mind, and work to manage complexity in the solution so that we don’t get bogged in minutiae and distractions that detract from our ultimate goal: to ship a working product.</p><blockquote><em>“A designer knows he has achieved perfection not when there is nothing left to add, but when there is nothing left to take away.” — Antoine de Saint-Exupery</em></blockquote><p>With this philosophy in mind, let’s get moving. Rather than posting copious screenshots every inch of the way, I’m just going to list out the steps that I take to get the UI into a working state. Remember those tools that I told you to download <a href="https://blog.jacobsdata.com/2019/08/26/foundational-concepts-series-getting-started-as-a-microsoft-net-stack-developer">way back at the very beginning</a>, like TextCrawler, KDiff, etc.? They come in very handy for tasks like this, as you may need to perform operations like doing a regular expression replace across files nested in directory structures or diffing two files and merging parts of one into the other. These are tools of the trade, and I recommend you familiarize yourself with them.</p><h3>Customizing the UI</h3><p>1. First, I follow the instructions under the “Make It Your Own” section on the ANMS GitHub page. These are pretty self-explanatory. For convenience, I’ve reposted them below:</p><ul><li>use search and replace functionality of your favorite IDE to replace anms with &lt;your-app-prefix&gt; [I did this using TextCrawler inside the OrgManager\JDS.OrgManager\JDS.OrgManager.Presentation.WebApi\ClientApp\ folder — recursively scanning through subfolders]</li><li>rename project in package.json name property and set appropriate version (eg 0.0.0 or 1.0.0)</li><li>remove / rename context path config — — deploy-url /angular-ngrx-material-starter/ — base-href /angular-ngrx-material-starter in package.json, this is used to configure url (context path) on which the application will be available (eg. https://www.something.com/&lt;context-path&gt;/) [I removed the context path entirely because we only have one project]</li><li>rename app in /environments/ files (will be shown in browser tab)</li><li>delete pre-existing CHANGELOG.md (you will generate your own with future releases of your features)</li><li>delete CODE_OF_CONDUCT.md, CONTRIBUTING.md and BUILT_WITH.md files as they are relevant only if project is open sourced on Github</li><li>edit the title and Open Graph metadata properties in index.html</li><li>remove or adjust links in the footer</li><li>replace logo in /assets folder ( currently 128 x 128 pixel png file )</li><li>adjust colors in /themes/default-theme.scss</li><li>[NOT DOING] create a pull request in the original repository to update BUILT_WITH.md file with a link and short description of your project</li></ul><p>2. Perform additional cleanup on ClientApp which is not specified in the above steps. This can be tedious.</p><ul><li>Remove .git and .github folders so that we don’t end up checking this in as a submodule, but as a folder in our own solution.</li><li>Remove extraneous build targets that don’t make sense from project.json like “contributors:add” etc.</li><li>Delete unnecessary files such as LICENSE, README.MD, travis files, all-contributors*, etc.</li><li>Modify “start” target in package.json to stop “did not start listening for requests” error.</li><li>Rather than using Google’s palettes that are provided out of the box, use a color wheel tool such as <a href="https://color.adobe.com/create/color-wheel">this one</a> to come up with our own custom colors and then generate our own custom Angular Material palettes from those using <a href="http://mcg.mbitson.com/">this tool</a>. Copy the custom palettes into default-theme.scss and update the primary/accent/warn variables accordingly.</li><li>Move the contents from the “projects/&lt;project name&gt;” folder to the root folder of the ClientApp. Merge the tslint.json files. Delete the server/server.js file. Delete the now empty projects folder because we only have one project and don’t need it. Update paths in tsconfig.app.json and tsconfig.spec.json. Update paths in karma.conf.js. Update paths in environments/*.ts. Update package.json to remove references to the “projects” folder. Update angular.json to remove references to the “projects” folder.</li><li>Find any remaining references to “angular-ngrx-material-starter” in our project and replace with “org-manager.”</li><li>Update tslint.json: change quotemarks from single to double. Also change quotes from single to double in .prettierrc.</li><li>Blow away the “features” folder/modules entirely and remove all references to it in the various Angular modules of the project. If you want, you can just cut and paste the folder somewhere else if you want to use it as a reference.</li><li>Get rid of the references to the modules we just blew away from the app-routing.module.ts file. We’re not going to use the loadChildren() approach anyway (at least not at this time).</li><li>Remove all internationalization features (i18n) from the project such as ngx-translate — it’s just way too much complexity at this point in our development process. Blow away the assets/i18n folder. We can add these back later if we want. Unfortunately, this means we also have to remove all calls to the “translate” pipe in remaining components and replace those with the actual text.</li><li>Remove big-input and rtl-support components. We don’t need those at this time.</li><li>Remove the lazy reducers and component calls to Ngrx/store (namely in app.component). It’s just too much complexity at this point and we can always add it back in later.</li><li>Replace the default logo with something we create in Paint.NET. It’s not forever — we will be replacing it with an actual component at some point.</li></ul><p>Finally, it’s a good idea to update all Node packages.</p><pre>pm install -g npm-check-updates</pre><pre>ncu -u</pre><pre>npm install</pre><p>You should see some output like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*YNigEZXv1J8rdDXD.jpg" /></figure><p>After doing this, we should definitely do an</p><pre>npm run build</pre><p>inside the ClientApp folder to make sure that we didn’t break the UI by updating all the packages.</p><p>Guess what? We broke Typescript!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*RAuEj1ZbrWGrhl_O.jpg" /></figure><p>Fortunately, we can locate the offending package and downgrade it to the prior version. Visual Studio provides IntelliSense for this, which is really nice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*RRjeVw2mlu4leAZc.jpg" /></figure><h3>Are We There Yet?</h3><p>At the end of this long slog we should *hopefully* have a barebones UI that looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/0*JYPBIpJ-L6vTBfVo.jpg" /></figure><p>It doesn’t look like much. In fact, it doesn’t look like anything — it’s just a header, a footer, and an empty space in the middle where the Angular router outlet resides. There is no authentication/authorization. We’ve also removed some power features such as translations, ngrx/store, lazy child module loading, and so on. However, these are basically UI optimizations which are not necessary at this point and will only distract us from our primary goal, which is to use the UI as a vehicle to drive development of our web application (back end API) while we focus on building functionality around our Domain layer. That’s our game plan in a nutshell, and this is a good place to stop.</p><h3>Conclusion</h3><p>In this blog entry I demonstrated how to set up a basic ASP.NET Web Application project in a Visual Studio 2019 solution using their out-of-the-box Angular template. Then I showed how to replace the scaffolded Angular UI with a starter project from Github, with the intent that we can save some time, have a working code base as a reference, and get some features “for free” without having to proverbially reinvent the wheel. Finally, I gave some insight into how to customize the UI by updating certain configuration elements and removing features, kind of like what a sculptor does when they create their artworks through a process of subtraction. Hopefully this tedious process has left us in a better place, and we can get back to building the bulk of our solution. Going forward, we will look to start adding features back in and evolving the UI alongside our Web API as we work to meet the business needs of our fictional client.</p><h3>Experts/Authorities/Resources</h3><h3>UI Frameworks</h3><p><a href="https://angular.io/">Angular</a></p><p><a href="https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor">Blazor</a></p><p><a href="https://reactjs.org/">React</a></p><p><a href="https://vuejs.org/">Vue.js</a></p><h3>Tools</h3><p><a href="https://color.adobe.com/create/color-wheel">Color Wheel</a></p><p><a href="http://mcg.mbitson.com/">Custom Angular Material Palettes</a></p><h3>Starter Projects</h3><p><a href="https://github.com/tomastrajan/angular-ngrx-material-starter">Angular, NgRx, Angular CLI &amp; Angular Material Starter Project</a>, by Tomas Trajan</p><h3>People</h3><h4>Tomas Trajan</h4><ul><li><a href="https://medium.com/@tomastrajan">https://medium.com/@tomastrajan</a></li><li><a href="https://github.com/tomastrajan">https://github.com/tomastrajan</a></li><li><a href="https://twitter.com/tomastrajan">https://twitter.com/tomastrajan</a></li></ul><h3>More Information</h3><p><a href="https://en.wikipedia.org/wiki/Single-page_application">Single Page Application</a> (Wikipedia)</p><p>This is entry #1 in the <a href="https://blog.jacobsdata.com/category/scaffold%20clean%20ddd%20web%20app">Scaffold Your Clean DDD Web App Series</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb9e862ec626" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-alchemy/scaffold-your-clean-ddd-web-application-part-1-set-up-the-ui-cb9e862ec626">Scaffold Your Clean DDD Web Application — Part 1: Set Up the UI</a> was originally published in <a href="https://medium.com/software-alchemy">Software Alchemy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Template for Clean Domain-Driven Design Architecture]]></title>
            <link>https://medium.com/software-alchemy/a-template-for-clean-domain-driven-design-architecture-e386ad235f32?source=rss-a80f78e022fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e386ad235f32</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Jacobs Data Solutions]]></dc:creator>
            <pubDate>Mon, 02 Mar 2020 12:42:06 GMT</pubDate>
            <atom:updated>2020-03-03T12:50:08.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A Clean DDD Architectural Template" src="https://cdn-images-1.medium.com/max/825/0*Foozhd3m-cPa86Mc.jpg" /></figure><h3>Overview</h3><p>The purpose of this blog entry is to introduce an architectural template for building web applications which is based upon my interpretation of the Clean DDD and CQRS concepts that I introduced in the previous entry. The information I provide here is guidance only, and I don’t claim this to be the definitive approach to building modern applications. It reflects my own personal software development biases and may or may not be suitable to your needs. Once again, I’m operating under the assumption that you fall into a certain category, namely a developer or team of developers working in a startupy-type environment, or a small team within a larger organization. You embrace Agile and lean startup practices, are flexible in your thinking, and focused on continuous improvement and development. Whatever the case, you should always do your homework as well.</p><p>To demonstrate this template, I’ve created a demo application which attempts to solve a (highly contrived) fictional problem for a fake organization. As indicated in the past few entries, you can find the source code to the demo solution <a href="https://github.com/JacobsDataSolutions/OrgManager/">here</a>. Feel free to refer to the source code alongside the architectural guidelines I’ve outlined below.</p><p>In developing this template, I studied solutions and tutorials from a handful of experts. As always, I’ve linked to those resources at the bottom. The experts/resources that this architecture is based on are Jason Taylor, Julie Lerman, Steve Smith, Jimmy Bogard, Matthew Renze, Vladimir Khorikov, Greg Young, Dino Esposito, and finally the Microsoft e-book, .NET Microservices: Architecture for Containerized .NET Applications.</p><p>Out of all of these, I’m most in agreement with the Taylor solution, which in turn seems to be heavily influenced by the Microsoft guide. At first, I wanted to give this template some cool name like “Wolverine Architecture,” but I didn’t want to come off as <em>too</em> presumptuous, so I will just refer to it as “my architectural template” or “my architecture.”</p><p>Before I dive in, I’d like to list a few more caveats:</p><ul><li>The demo application is NOT complete, as it is in an initial state which is sufficient to demonstrate the concepts I’ve discussed in this and previous blog entries. It will change and evolve over time as I elaborate on more software development topics. As a matter of fact, at this point the actual “app” isn’t even an ASP.NET Core web application — I’ve started it out using a simple console application standing in for the Presentation layer. Hopefully this will help you to get a good idea of how the various layers and their corresponding components communicate through the stack without being distracted by too many boilerplate details that would have been there had I used an actual web app for the main project. I’ll try to tag the source code accordingly, so that each revision can be easily indexed to the blog entries that it pertains to.</li><li>A few key features are currently missing, such as Identity and Security. I’ll add those in future posts.</li><li>This architecture represents the stack up to the Persistence layer. I’m not going to touch on the UI yet.</li><li>I don’t agree with the above references on all points. It’s okay to disagree with the experts (although, if you are going to adopt a heretical stance, be well-prepared to defend your choice). I’ll try to clarify my reasoning in areas in which I deviate from their approaches.</li></ul><h3>First, the Use Case</h3><p>A company would like to have a comprehensive, business-centric application to manage various functions in the organization.</p><ul><li>They would like to automate processes which belong to the various business units of the organization — Human Resources, Accounting, etc. For example, they need to track payroll at a basic level, and they need a seamless way to onboard or offboard employees through the Manager of HR.</li><li>They need different adjunct functionalities, like tracking paid time off (PTO) time available, which will be handled through the HR side as well.</li><li>The business will almost certainly request additional features in the future as the application grows and they have time to interact with it, elucidating more business requirements.</li></ul><p>I’ve been instructed to build an enterprise solution on the .NET Core stack and deploy it to the Azure cloud. Starting out, the system will simply handle basic HR and Accounting, but it MUST be able to grow to accommodate more complex business functions, such as those managed by Operations, or even the executive team themselves. At the outset, I’m only allowed to use a single relational database as the data store, which will also be in the cloud. Additionally, I’ve been told by the CIO that the Accounting logic will be coded and maintained by a separate team (maybe even a single individual). She tells me this is for “technical” reasons. OK, those are my orders. Time to get to work.</p><h3>A Template for Business-Focused Web Applications in the Microsoft Cloud</h3><h3>Code-Level Conventions</h3><p>As stated in blog entry 4, I generally follow the conventions from Framework Design Guidelines. Once again, I highly, highly recommend that you use a tool like CodeMaid or something similar to automatically clean up and organize your files for you. You can customize it to organize them the way you want. Here are some specifics:</p><ul><li>Pascal case is used for classes names, method names, properties and so on.</li><li>Parameter names, private fields, etc. are camel case.</li><li>Underscores are never used, except in method names for unit tests. I never prefix private fields with underscores.</li><li>SCREAMING_CASE is never used.</li><li>While Hungarian notation is not allowed, certain conventions which might resemble it are okay, such as MyCoolController, MyAwesomeVm, UpdateSomethingCommand, etc. In other words, using suffixes. Those are generally okay.</li><li>I mentioned this in a previous post but here it is again. In recent years there has been a small yet fervent movement to stop prefixing interfaces with “I” because technically it is a vestige of Hungarian notation. DON’T DO THIS. Interfaces should be prefixed with “I” because the distinction between them and other types is so important that their names themselves should express this. If you have any doubts, just look at the source code for the various official Microsoft .NET Core packages. What do they do? (When in doubt, emulate the pros).</li></ul><p>I arrange my code files this way, top to bottom:</p><ul><li>Fields/constants</li><li>Properties/indexers</li><li>Constructors</li><li>Methods</li><li>Nested classes</li></ul><p>Within each of the above categories I arrange members based upon access modifier in the following order:</p><ul><li>Public</li><li>Internal</li><li>Protected</li><li>Private</li></ul><h3>Basic Solution Organization</h3><p>These are guidelines for organizing the solution into files and projects:</p><ul><li>There should be one class/enum/interface per source code file. This one drives me nuts. I’ve encountered solutions in which there are five or six different classes in a single file along with a bunch of enums and other nonsense. However, there is an exception to this rule, which you can see in the demo application: I’ve nested the handler classes for commands/queries inside the command/query classes themselves. The reason for this is simple, which is that user code doesn’t need to call them directly. Remember, we are relying on MediatR to perform the dispatch to handler methods.</li><li>Project names, folder names, and namespace names should all align. It drives me crazy when I encounter a solution in which there is a folder called “Foo” and the corresponding namespace for classes in that folder is “Bar.” Don’t do this. Names of everything should align, so that if decide you need to take a folder full of classes and put it into its own project, the namespaces don’t break. This idea, which I’ll tentatively call the “Project/Folder/Namespace Fungibility principle” is important, because as the solution grows it gives us the flexibility to refactor it easily and move different sections of the architecture into separate microservices. To put it simply, <em>Project Name = Folder Name = Namespace</em>. Do this, and your solutions will be much easier to refactor.</li><li>Related to the above point is the naming of projects themselves. A good guideline is &lt;Company&gt;.&lt;Solution&gt;.&lt;Layer&gt;.&lt;Bounded context or other detail&gt;. Alternatively, you can use &lt;Solution&gt;.&lt;Layer&gt;.&lt;BC/detail&gt; or whatever. Just be consistent.</li><li>I recommend keeping your project structure flat (for the most part). This means not hiding projects in some nested folder somewhere, which makes them difficult to find.</li></ul><h3>External Dependencies</h3><p>This is a list of third-party toolkits, libraries, and NuGet packages that the solution depends upon. This is not comprehensive, and more will be added as the solution grows over time.</p><ul><li>MediatR, by Jimmy Bogard — Used in both Domain layer and Application layer. This is a really powerful package and is the special sauce that brings everything together. As stated in the previous entry, MediatR facilitates a simple, elegant CQRS implementation.</li><li>Entity Framework Core — Microsoft’s ORM. Used almost exclusively inside CQRS commands to update the database and sometimes to perform simple queries against it.</li><li>Dapper — A powerful and efficient micro-ORM which allows us to write flexible queries which translate well into DTO/view models. Used on the query side of the stack to return query results by projecting complex SQL queries into 1NF view models.</li><li>FluentValidation — Plugs nicely into MediatR and allows for validation of commands that are sent down the stack before they hit the Domain layer.</li><li>Mapster — A fast and intuitive object mapping library which assists in mapping view models and persistence models to/from domain models. Alternatively, you could use AutoMapper, also by Jimmy Bogard, but at this time I prefer Mapster because it’s faster and the usage is slightly more intuitive.</li><li>Serlilog — A powerful logging library which sits on top of the base .NET Core logging infrastructure.</li></ul><h3>Logical Organization of the Solution</h3><p>When working with this or any other architecture, I strive to produce solutions that are neatly organized and easy to navigate. A great principle to follow in this regard is <a href="https://blog.cleancoder.com/uncle-bob/2011/09/30/Screaming-Architecture.html">Screaming Architecture</a> (<em>The architecture should scream the intent of the system!</em>), which is another Uncle Bob-ism. Starting from this, let’s discuss for a minute component organization and functional organization, which are two distinct methodologies for organizing classes, interfaces, components, and other objects together inside a software solution.</p><h3>Component Organization</h3><p>Under component organization, classes, interfaces and other objects are grouped together in folders or projects based upon their <em>category</em>, or what they represent — e.g. Controllers, Views, so on. The underlying concept here is categorical cohesion, which simply means that entities of the same classification or category should go together. Imagine grouping baseball players from a baseball league. In this way, all third basemen from all teams would go together into one group, pitchers in another, and so on.</p><p>This is the default for most solutions in .NET, especially MVC solutions. At first, this seems easier to grasp but has its drawbacks. As the solution grows, you may find yourself “jumping around” more to find dependencies for different components. I’ve certainly found this to be the case with most legacy systems I’ve worked on in corporate environments, in which F12, Ctrl-F12, and Ctrl-Q become my best friends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/0*BdFZPzZh-DfUDeg1.jpg" /></figure><p>These are all the same thing?</p><h3>Functional Organization</h3><p>On the other hand, functional organization is based upon the idea of spatial locality: it is more efficient to keep items that are often used together near each other. The underlying concept is functional cohesion, which means that entities which work toward the same goal or purpose should go together. Going back to the baseball analogy, this would simply imply that players from each team should go together, regardless of their positions, because they play together and operate as a functional unit on that team.</p><p>As applied to a .NET software solution, classes and other objects are grouped together in folders or projects based upon their <em>use case</em>, or what purpose they serve — e.g. RegisterOrUpdateEmployee, GetPaidTimeOffPolicyList, etc. The benefit to this approach is that it’s easier to navigate the solution, especially as it grows, and it helps you to maintain a high level of cohesion around different use cases of the system. Some of the downsides to this are that you might break from framework conventions, lose automatic scaffolding from certain tools, and so on. Personally, I think it’s worth the cost. As an aside, it’s worth noting that Angular uses functional organization by default, so this isn’t a totally radical methodology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/0*8xttXq3lpLCbg-Nh.jpg" /></figure><p>These all work well together.</p><p>In my architecture I use functional organization to the greatest extent possible, <em>where it makes sense</em>. Once again, the 80/20 rule (Pareto principle) applies. In situations where it doesn’t make sense, I fall back to component organization. In Renze’s demo solution he mixes unit test classes into the same folders as the classes under test within the application projects. DON’T EVER DO THIS. Unit tests are a different animal, and they belong in their own projects. Once again, principles and practices are guidance, general rules to follow, and as the character Morpheus states in the <a href="https://en.wikipedia.org/wiki/The_Matrix">Matrix</a>, “some of them can be bent, others can be broken.”</p><p>When applied to the architectural layers of a Clean DDD solution, functional organization looks like this. Layer/grouping:</p><ul><li>Domain — Each domain entity</li><li>Application — Aggregate root corresponding to each use case</li><li>Persistence — Each database table</li><li>Infrastructure — Each functional area of the operating system (file operations, etc.) and/or external resources</li><li>Presentation — Aggregate root corresponding to each screen or web page</li><li>Cross-cutting (Common) — Each cross-cutting concern (Logging, Security, etc.)</li></ul><h3>The Template</h3><p>Just as a refresher, here is what the architecture looks like at a high level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/0*cbV2X7Qio3BFEQCj.png" /></figure><h3>Core Layers</h3><p>As stated in the previous entry, the core is comprised of the Domain layer and the Application layer. Think of this as the “zone of abstractions and logic”.</p><h4>Domain Layer Organization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/0*PxIRrkNPntC6JvFG.png" /></figure><p>Once again, the Domain Layer should have no knowledge of outside layers, even by proxy (i.e. by exposing interfaces which are implemented by outside layers). It is strictly for business entities and logic.</p><p>Key points:</p><ul><li>I start with a single Domain project, in which I create root-level folders that hold base classes corresponding to different key DDD concepts — Models, Events, so on. Additional projects can be added, for instance to separate out bounded contexts, but this is the main one.</li><li>I also have a separate root level folder to house interfaces and other abstractions. I’ve named this Abstractions, and it’s pretty similar to the way that the official .NET Core packages are structured. In fact, at some point in the future we could even separate this into its own project. This is a recurring pattern throughout the layers.</li><li>There is a Common folder at the root level as well, which holds various Domain entities and value objects that don’t belong to any particular bounded context. This is essentially a “shared kernel” in DDD-speak. Note that this pattern doesn’t just apply to the Domain layer. Anything which <em>cuts across Bounded Contexts</em> goes into a “Common” folder for each layer.</li><li>Additional root level folders exist for each bounded context. In the future, as the solution scales, each one can be broken off into its own project with little refactoring involved, if we continue to abide by the Fungibility principle I stated above. You can see this in the demo app, where I have created a separate Domain project for the Accounting bounded context.</li><li>I studied a few different ValueObject base class implementations and I settled on the one that Taylor’s solution and the Microsoft e-book use. <a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/implement-value-objects">In this implementation</a>, child classes must explicitly state which data properties are used for comparison. While this might seem like more effort, I prefer this over reflection-based approaches because the design of each value object should not be taken lightly, and furthermore you don’t want to take a performance hit from using reflection in these. See below.</li><li>In general, the Domain layer should have zero reliance on external packages and third-party dependencies. However, if you examine the demo application, you’ll see that I put in a hard dependency on MediatR as a means of dispatching domain events. Some may regard this as worthy of a slap on the wrist, but I consider it to be a situation where breaking the rules is acceptable, because trying to abstract away MediatR is simply is not worth the effort, and it wouldn’t be hard to remove if the need arose to use a different in-process messaging implementation.</li></ul><p>Finally, here are some thoughts on putting persistence abstractions (interfaces) in the domain layer. At least two of the solutions I examined do this. For example, in Khorikov’s solution he puts CQRS commands into the Domain layer, and the Microsoft e-book does basically the same thing with repository interfaces.</p><p>I don’t agree with them. In my architectural template, CQRS commands and queries, and repository interfaces (if you choose to use them) NEVER go into the Domain layer, because they have nothing to do with pure business logic. Persistence logic, even through interfaces, does not belong in there. In this respect, my architecture is more conservative than other Clean DDD solutions — the Domain layer should ONLY be concerned with business logic and interaction among domain entities. The Application layer is the appropriate place to put persistence interfaces because <em>that</em> is the layer of orchestration and coordination.</p><h4>Application Layer Organization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/0*SjCIUFB9QGNOo6cm.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/0*u91z1r3G202Cxkht.png" /></figure><p>In my opinion, this is the most important layer in the entire architecture, so I’ll go into some detail on this.</p><p>Key points:</p><ul><li>Just like in the Domain layer, there is an Abstractions root level folder, inside which are subfolders which are broken apart using functional organization. In this case, each subfolder corresponds to different general concerns of the Application layer. This is important because this contains interfaces that higher-level layers, such as Persistence and Infrastructure will implement. This is basically the means by which this layer connects to the higher-level layers: Application layer components receive references to these various interfaces via constructor injection, and the higher-level layers provide the actual concrete implementations. This decoupling is extremely important, as we have now made it easy to mock the Application layer orchestration logic inside unit tests without requiring a connection to an actual database, operating system, etc. This is the Dependency Inversion principle in action. In the demo application there are two interfaces that I want to draw your attention to:</li><li>IOrgManagerDbContext — This is a facade which abstracts away an Entity Framework Core database context for our application data. This will be used almost exclusively on the command side of the stack.</li><li>IOrgManagerDbQueryFacade — This is a facade which abstracts away calls to a micro-ORM called Dapper. This will be used mostly on the query side of the stack, although there’s no restriction against using this inside commands, should the need arise.</li><li>There is a Common folder in here as well. Think of it as a higher-level shared kernel. In here are subfolders, each of which corresponds to a separate Entity Framework Core entity, which in turn will map to a database table, since we’re using EF code-first. You might be wondering why this is not broken apart by bounded context as well. The reason is simple: we are only targeting one database. As stated earlier, the approach is to build a monolithic application comprised of several projects, which can be broken apart into separate microservices at some later date. When (if) that time comes, we can worry about splitting the data model.</li><li>Also, at the root level there are folders corresponding to different bounded contexts. Just like with the Domain layer, these can be moved into separate projects, should the need arise. Each bounded context folder has subfolders corresponding to each aggregate root. Inside each of these, we’ve separated our commands from queries. See below on how this could scale, should the need arise to split the stack.</li><li>This layer may reference “helper” libraries such as mappers, internal messaging components (MediatR).</li></ul><p>MediatR + CQRS</p><ul><li>As stated in the previous blog entry, the use of the Mediator pattern along with CQRS is almost a no-brainer. Encapsulating commands/queries as MediatR requests is how we accomplish this.</li><li>We get additional benefits, such as being able to inject cross-cutting concerns into the request pipeline, which is exactly what I’ve done. The RequestCachingBehavior that I’ve implemented is a great example of this.</li></ul><h4>Application Model Classes</h4><p>Remember from the last entry what I said about view models? To recap, they are models that map to some piece of the UI and are used to communicate back and forth between the UI and the Presentation layer (web API). In this architecture I treat both CQRS commands and the DTOs that are returned from queries as view models. This might strike you as wrong or otherwise violating the Single Responsibility principle, but in this instance it’s okay. This is because the task-based orientation of CQRS functionally aligns with the UI, so there’s typically a 1:1 correspondence between the models that present information to the user and those that are required/produced by CQRS commands and queries. Furthermore, if there comes a time when the two must be decoupled, there’s nothing from stopping us from doing that and putting that mapping logic into the Presentation layer.</p><p>The persistence models are a different story… Several the solutions I studied were reusing the EF Core model classes as Domain entities. NO, NO, NO, NO! Even Taylor’s solution does this, and his architecture is the closest to mine out of all them. I disagree with virtually all the experts on this. Here’s why:</p><p>Persistence model classes never quite map perfectly to database tables and queries because of what Greg Young calls an <em>object-relational impedance mismatch</em>. This sounds complicated but it’s not. All it means is that databases and programming languages differ in the way they represent data and relationships between entities, so of necessity there always must be some degree of translation going on. More specifically, databases are (traditionally) relational, which means that they are based upon Set Theory. Modern programming frameworks are (often) object-oriented, which means that they are based on Graph Theory. Furthermore, databases have their own data types which are almost always different from the data types used in your programming language of choice, so conversion or even data loss is involved when communicating between the two. If you are using an ORM like Entity Framework, then it will handle this for you. If you are writing straight ADO.NET code, then you have to deal with the pain of mapping between them yourself.</p><p>Taking this a step further, domain entities and persistence entities have radically different intents: one is used to model the business and the other is used to store data. The accepted answer from <a href="https://softwareengineering.stackexchange.com/questions/384846/pitfalls-of-domain-driven-design-with-entity-framework#384929">this stack exchange question</a>, by Robert Bräutigam, explains it quite well:</p><blockquote><em>DDD and EF have little to nothing to do with each other.</em></blockquote><blockquote><em>DDD is a modeling concept. It means to think about the Domain, the Business Requirements, and model those. Especially in the context of object-orientation it means to create a design which mirrors business functions and capabilities.</em></blockquote><blockquote><em>EF is a persistence technology. It is mainly concerned with data and database records.</em></blockquote><blockquote><em>These two are sharply divorced. A DDD design may use EF in some form under the hood, but the two should not interact in any other way.</em></blockquote><blockquote><em>Some interpretations of Domain-Driven Design do advocate data-modeling, and I think this is what your question is about. In this interpretation “Entities” and “Value Objects” are essentially function-less data holders only, and the design concerns itself with what properties these hold and what relation they have between each other. In this context DDD vs. EF may come up.</em></blockquote><blockquote><em>This interpretation however is flawed, and I would strongly recommend ignoring it altogether.</em></blockquote><blockquote><em>In conclusion: DDD and EF are not mutually exclusive, they are actually irrelevant to each other, as long as you are doing proper object-modeling and not data-modeling. DDD objects should not in any shape or form be EF artifacts. DDD Entities should not be EF “entities” for example. Inside some business-relevant function, a DDD design might use EF with some related data-objects, but those should be always hidden under a business-relevant behavior-oriented interface.</em></blockquote><p>One solution to avoid getting tangled in this mess is to use mapping. You’ll notice that the folders corresponding to different commands/queries have mapper classes which allow you to map from view models to domain models, and back again. Additionally, the folders corresponding to different database tables have mapper classes that allow you to map from persistence entities to domain models, and back again as well. This is the price that we must pay for using a Clean DDD approach because it’s important to maintain the decoupling between Domain layer entities and view models/persistence entities. This is the biggest pain point in this architecture, but fortunately that pain can be minimized by using tools such as AutoMapper or Mapster. I’ve abstracted the mappers for each entity pair behind interfaces, because this makes our solution much more testable and flexible. Dependency injection is used to provide the actual implementations to the command/query classes that need them.</p><h4>Persistence Entities and Facades</h4><p>You might be questioning why view models and persistence models are declared in the Application layer instead of Presentation/Persistence. The answer, quite simply, is because the Application layer is doing all the heavy lifting in the system and depends upon them to manipulate the data model inside command handlers, and relay query results back up the stack from inside of query handlers.</p><p>Remember from the last entry, in which I talked about the asymmetry of the solution? You can clearly see this in the Application and Persistence layers, in which I’m using two different persistence technologies: Entity Framework Core and Dapper.</p><ul><li>EF Core is Microsoft’s ORM for .NET Core. I’m using this on the command/write side of the stack because it makes inserting and updating data to the database much easier. It can also be used for simple queries against the database inside CQRS commands. I’ve abstracted the EF Core DbContext behind an interface which gets injected into CQRS command handlers.</li><li>Dapper is a lightweight micro-ORM. I’m using this on the query/read side of the stack because it facilitates writing complex database queries without incurring the performance penalties typically associated with ORMs, including EF Core. I’ve abstracted a few key Dapper methods behind a query facade interface which gets injected into the CQRS query handlers.</li></ul><p>You’ll notice that the IOrgManagerDbContext and IOrgManagerDbQueryFacade interfaces still allow CQRS command/query handlers to use LINQ and/or straight SQL queries. Aren’t these leaky abstractions — i.e. allowing database details into the Application layer? In a sense, yes. Technically I’ve broken another rule and I’m sure Uncle Bob would yell at me for this. However, I’m of the camp that trying to create a “pure” abstraction that removes ALL knowledge of the underlying data store is not worth the effort, because the paradigms underlying various data stores can be so radically different that it’s difficult to keep underlying details from leaking across the interface boundary anyway. What if the underlying data store is a NoSQL database? Or the file system? The Repository pattern attempts to do mitigate this problem, but I’m not a fan of using it in CQRS solutions. Read on.</p><h4>To Repo, or Not to Repo?</h4><p>I disagree with a few the experts on the use of the Repository pattern. In my opinion, repositories are an unnecessary abstraction in CQRS solutions — they are trying to solve a problem which doesn’t exist, which is the encapsulation of task-based operations into a Unit of Work; the commands themselves already do this. Furthermore, I believe that repositories can tend to sway you toward CRUD-type semantics, whereas CQRS commands (ideally) are unambiguously centered around business tasks. I’m not 100% against repositories, but I think they are more appropriate for CRUD applications.</p><p>While it’s true that forgoing the use of repositories and writing LINQ/SQL queries directly in the CQRS handlers isn’t truly persistence agnostic, it is still flexible enough that we can swap out one database provider for another (in theory). Regarding testability, we still maintain the ability to write unit tests against our CQRS handlers by mocking out the persistence facade interfaces.</p><h3>Periphery Layers</h3><p>The periphery is comprised of the Persistence, Infrastructure, and Presentation layers. Think of this as the “zone of implementations and concretes.” Honestly, I’m not going to go into great detail with these because they are self-explanatory.</p><h4>Persistence Layer Organization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*osgmJ_eIlYG0jraq.png" /></figure><p>It’s important to mention that another benefit to using Entity Framework Core is that it allows us to scaffold our database from the persistence model classes, which can be a huge time saver and result in a clean, robust database schema. That’s exactly what I’ve done, so the EF configuration classes are in here, functionally organized into subfolders, along with the EF code migrations.</p><p>The Persistence layer additionally houses the implementations for the EF Core DbContext interface and the Dapper QueryFacade interface.</p><h4>Infrastructure Layer Organization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*VGnIL0UpufmnGNeu.png" /></figure><p>This is very similar to the Persistence layer. The Infrastructure layer contains concrete implementations for abstractions that are defined in the Application layer relating to things like Identity, accessing the file system, external messaging, and so on. Likewise, implementations for abstractions defined in the Common layer should also go in here, a good example being the IDateTime interface, discussed below.</p><p>You might be wondering why Identity is in here instead of in the Persistence layer. The reason is that Identity is an entirely separate architectural area from persistence, and there’s no reason to assume that user identity will be backed by a DB, as opposed to some third-party identity store accessed through an API (there are dozens out there).</p><h4>Presentation Layer Organization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/0*d3iqsOzcR6NLvNfE.png" /></figure><p>For all intents and purposes the Presentation layer is the top of the stack as far as back end code is concerned. The UI is treated separately. In the finished solution, this will be an ASP.NET Core web API with thin logic inside of it. The only code inside here will be:</p><ul><li>ASP.NET Core boilerplate, to get the web API up and running.</li><li>Controllers, which act as the REST interface that the UI will communicate with.</li><li>High-level components, namely from the Application layer, which get injected into the controllers and called as a consequence of various controller actions. All these components are wired together using an IOC container and dependency injection.</li></ul><p>While keeping the Presentation layer decoupled from the Application layer is a must, decoupling from the UI isn’t as big of a deal. At some point in the future, should we feel the need, there is nothing to stop us from peeling off the Presentation layer and replace it with a desktop UI, implemented using WPF. In this case, the Presentation layer <em>is</em> the UI. Alternatively, we can unplug the stack starting from the Application layer on down and put it inside a different web API, one that is specifically targeted toward mobile clients. Anything is possible.</p><p>In some of the other demo solutions I studied, the web API project was treated as the Application layer. I don’t agree with this. My stance is to treat the Web API project as belonging to the Presentation Layer (as distinct from the UI). This coincides with the Taylor solution and provides for much better decoupling at an architectural level.</p><h4>Common Layer Organization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/0*DgnWQTkmLIs-1f-M.png" /></figure><p>There isn’t much going on here, just your usual cross-cutting concerns like text manipulation and the like. As always, be careful what you put into this layer and make sure that it’s a cross-cutting concern.</p><p>Here’s a short explanation of the IDateTime interface. This is in here because it’s used by virtually every layer, including the Domain layer. The actual implementation for it is in the Infrastructure layer. This is something you might take for granted, but it is an incredibly powerful pattern. Some of the benefits are:</p><ul><li>All components and logic which are dependent upon the system date/time instantly become unit testable.</li><li>What’s more, if you have a system which is highly sensitive to the current date/time, you can put a special implementation behind this, and all subsystems will stay in sync.</li><li>I’d take this further and put in the provision that all date/times must be in UTC across the whole stack, except when being presented to the user. The reasons for this are numerous, but suffice it to say, I’ve acquired this point of view after working on dozens of legacy systems which DON’T do this.</li></ul><h3>Unit Test Projects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*TiKIsFmOzfiwI-KZ.png" /></figure><p>When adding unit tests to a solution, I largely follow the conventions espoused by Roy Osherove in his book <a href="https://www.manning.com/books/the-art-of-unit-testing-third-edition">The Art of Unit Testing</a>. For instance, the folder structure of unit test projects should mirror the folder structure of the projects under test, and each test should be cohesive and test only one thing. In terms of code coverage, 100% is rarely feasible or necessary. Aim to test the most critical pieces first. Test-driven development (TDD) is easier when using CQRS, and I may touch on that in a future post. If you’ve designed them well and are using dependency injection properly, then command/query handlers should be easily unit testable.</p><h3>Points for Style: F# Projects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/0*cBxTVE5pvmTRkDHn.png" /></figure><p><a href="https://gist.github.com/JacobsDataSolutions/59146cff39c1a81864a71672afb55d55/raw/e7a17965e55c9fa8c624f2aae7facf57158ea57e/OrganizationVerifier.fs">view raw</a><a href="https://gist.github.com/JacobsDataSolutions/59146cff39c1a81864a71672afb55d55#file-organizationverifier-fs">OrganizationVerifier.fs</a> hosted with ❤ by <a href="https://github.com/">GitHub</a></p><p>Example code for a domain class built using F#.</p><p>In the demo application I’ve added an F# project to the solution, representing specialized logic in the Domain layer for a bounded context. This is just to demonstrate how easy it is to create multi-paradigm solutions, and the way that I dovetail F# code into a .NET solution which is mainly built using C#. As stated in the blog entry on DDD, functional programming techniques are extremely powerful when used to implement domain logic. In this kind of a scenario, anemic domain models are okay, because the business rules are encapsulated inside functions. I’m not going to do a lot in the future using F# in the demo application, however a complete multi-paradigm solution would probably be comprised of 80% C# code, and 20% F# code. This gives you an idea of what’s possible.</p><h3>Layer Interaction</h3><p>Simplistically, this demonstrates how the layers interact with each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/0*0DWjck3AuovBySx1.png" /></figure><h3>Conclusion</h3><p>In this entry I went into detail about how to implement Clean DDD and CQRS in a .NET Core solution. I mentioned some of the experts whose solutions I studied and spoke a little bit about some of their solutions. I presented the use case for a fictional company to create an organization management tool, and I introduced the demo application. I laid out some of the code-level conventions and project-level guidelines for organizing the solution, and I talked about functional organization vs. component organization. Finally, I went into detail about each layer of the architecture, building off the concepts presented in the previous blog entry. Finally, I introduced unit tests at a surface level, and I wrapped up by pointing the way toward building multi-paradigm solutions, which combine both functional F# code with OOP C# code.</p><h3>Experts/Authorities/Resources</h3><h3>Robert C. Martin (Uncle Bob)</h3><ul><li><a href="http://cleancoder.com/">cleancoder.com</a></li><li><a href="https://blog.cleancoder.com/uncle-bob/2011/09/30/Screaming-Architecture.html">https://blog.cleancoder.com/uncle-bob/2011/09/30/Screaming-Architecture.html</a></li></ul><h3>Roy Osherove</h3><ul><li><a href="https://osherove.com/">https://osherove.com/</a></li><li><a href="https://www.manning.com/books/the-art-of-unit-testing-third-edition">The Art of Unit Testing</a></li></ul><h3>Jason Taylor</h3><ul><li><a href="https://www.youtube.com/watch?v=_lwCVE_XgqI&amp;feature=youtu.be">Clean Architecture with ASP.NET Core 2.1</a></li><li><a href="https://github.com/JasonGT/NorthwindTraders">https://github.com/JasonGT/NorthwindTraders</a></li></ul><h3>Julie Lerman/Steve Smith</h3><ul><li><a href="https://app.pluralsight.com/library/courses/domain-driven-design-fundamentals">Domain-Driven Design Fundamentals</a></li><li><a href="https://github.com/iamijaz/domain-driven-design-fundamentals">https://github.com/iamijaz/domain-driven-design-fundamentals</a></li></ul><h3>Steve Smith</h3><ul><li><a href="https://docs.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/">Architect Modern Web Applications with ASP.NET Core and Azure</a></li><li><a href="https://github.com/ardalis/cleanarchitecture">https://github.com/ardalis/cleanarchitecture</a></li></ul><h3>Jimmy Bogard</h3><ul><li><a href="https://jimmybogard.com/">https://jimmybogard.com/</a></li><li><a href="https://lostechies.com/jimmybogard/">https://lostechies.com/jimmybogard/</a></li><li><a href="https://github.com/jbogard/MediatR">https://github.com/jbogard/MediatR</a></li></ul><h3>Matthew Renze</h3><ul><li><a href="https://app.pluralsight.com/library/courses/clean-architecture-patterns-practices-principles">Clean Architecture: Patterns, Practices, and Principles</a></li><li><a href="https://github.com/matthewrenze/clean-architecture-demo">https://github.com/matthewrenze/clean-architecture-demo</a></li></ul><h3>Vladimir Khorikov</h3><ul><li><a href="https://app.pluralsight.com/library/courses/domain-driven-design-in-practice">Domain-Driven Design in Practice</a></li><li><a href="https://github.com/vkhorikov/CqrsInPractice.git">https://github.com/vkhorikov/CqrsInPractice.git</a></li></ul><h3>Greg Young</h3><ul><li><a href="https://cqrs.files.wordpress.com/2010/11/cqrs_documents.pdf">https://cqrs.files.wordpress.com/2010/11/cqrs_documents.pdf</a></li></ul><h3>Dino Esposito</h3><ul><li><a href="https://app.pluralsight.com/library/courses/modern-software-architecture-domain-models-cqrs-event-sourcing">Modern Software Architecture: Domain Models, CQRS, and Event Sourcing</a></li></ul><h3>Microsoft — Microservice/DDD Guide</h3><ul><li><a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/">.NET Microservices: Architecture for Containerized .NET Applications</a></li><li><a href="https://github.com/dotnet-architecture/eShopOnContainers">https://github.com/dotnet-architecture/eShopOnContainers</a></li></ul><h3>Code Maid</h3><ul><li><a href="http://www.codemaid.net/">http://www.codemaid.net/</a></li><li><a href="https://www.youtube.com/watch?v=M8iwCaw61Mo">https://www.youtube.com/watch?v=M8iwCaw61Mo</a></li></ul><h3>Dapper</h3><ul><li><a href="https://github.com/StackExchange/Dapper">https://github.com/StackExchange/Dapper</a></li></ul><p>This is entry #8 in the <a href="https://blog.jacobsdata.com/category/foundational%20concepts">Foundational Concepts Series</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e386ad235f32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-alchemy/a-template-for-clean-domain-driven-design-architecture-e386ad235f32">A Template for Clean Domain-Driven Design Architecture</a> was originally published in <a href="https://medium.com/software-alchemy">Software Alchemy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>