<?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 Thang Chung on Medium]]></title>
        <description><![CDATA[Stories by Thang Chung on Medium]]></description>
        <link>https://medium.com/@thangchung?source=rss-920427ad169f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Eaqyi2GLath3uhc8UxV8gA.jpeg</url>
            <title>Stories by Thang Chung on Medium</title>
            <link>https://medium.com/@thangchung?source=rss-920427ad169f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 16:26:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thangchung/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[Clean Code for .NET Coding Craftsman]]></title>
            <link>https://medium.com/hackernoon/clean-code-for-net-coding-craftsman-7674373fccaf?source=rss-920427ad169f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7674373fccaf</guid>
            <category><![CDATA[software-craftmanship]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Thang Chung]]></dc:creator>
            <pubDate>Wed, 19 Dec 2018 03:07:15 GMT</pubDate>
            <atom:updated>2018-12-19T10:22:46.104Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GGyYJIQFbEQMsRRo8ZWjw.jpeg" /><figcaption><a href="https://pixabay.com/en/tea-plantation-landscape-vietnam-3358870/">Source</a></figcaption></figure><p>When I started my very first career in software development many years ago, I remembered that I really like to <strong>learn and achieve a lot of skills in software development</strong> via <strong>read notably books by gurus</strong> in this fields as well as read <strong>blogs of them</strong>. Some of the very famous books that I have read are <a href="https://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/073561967"><strong>Code Complete: A Practical Handbook of Software Construction</strong></a>, <a href="https://www.amazon.com/Clean-Coder-Conduct-Professional-Programmers/dp/0137081073"><strong>The Clean Coder: A Code of Conduct for Professional Programmers</strong></a>, <a href="https://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612"><strong>Design Patterns: Elements of Reusable Object-Oriented Software</strong></a>, <a href="https://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672"><strong>Refactoring: Improving the Design of Existing Code</strong></a>, and so on. And I strongly believed that all developers just like me also stepped into the software development industry in this way.</p><p>By the time, I wondered how to <strong>share what I have learned to the software development communities</strong> out there so that it will help them <strong>save their efforts for the first stage of their career</strong>. Just the last year, I saw there are couples of projects about <strong>Clean Code</strong> in <a href="https://github.com/ryanmcdermott/clean-code-javascript"><strong>JavaScript</strong> </a>and <a href="https://github.com/jupeter/clean-code-php"><strong>PHP</strong> </a>languages, and now is <a href="https://github.com/uohzxela/clean-code-ruby"><strong>Ruby</strong></a> language. Then I thought that it would be great if I started the list just like them but customized sections for <a href="https://github.com/thangchung/clean-code-dotnet"><strong>.NET/.NET Core</strong></a>, and that pushed me to start immediately in that night to <strong>create the very first Clean Code for .NET developers</strong> list at <a href="https://github.com/thangchung/clean-code-dotnet"><strong>https://github.com/thangchung/clean-code-dotnet</strong></a></p><p>To make it easy to readers, <a href="https://github.com/thangchung/clean-code-dotnet">.NET</a> developers in specially, I start with the different way by other lists (JavaScript, PHP, or Ruby language). I grouped them to the <strong>big group with collapsible sub-items</strong> which help readers couldn’t be scary when they walk through the big list with huge items accordingly. In case they want to investigate or read in details, they can click on the title of the sub-item to read more. <a href="https://github.com/ngohungphuc"><strong>Tony</strong> </a>— my colleague — is also <strong>eager to join this project</strong> so that I told him to <strong>help me and he’s a person who proposed this </strong><a href="https://github.com/thangchung/clean-code-dotnet"><strong>IDEAS</strong></a> as well, and actually it makes the list became short and succinct. Talking a lot of the history of this list, let now go into details to see what inside those group.</p><h3><a href="https://github.com/thangchung/clean-code-dotnet#2-naming">Naming</a></h3><ul><li>Avoiding using a bad name</li><li>Avoid disinformation name</li><li>Use pronounceable names</li><li>Use camel-case notation</li><li>Use domain name.</li></ul><h3><a href="https://github.com/thangchung/clean-code-dotnet#3-variables">Variables</a></h3><ul><li>Use meaningful and pronounceable variable names</li><li>Use the same vocabulary for the same type of variable</li><li>Use searchable names</li><li>Use explanatory variables</li><li>Avoid nesting too deeply and return early</li><li>Avoid Mental Mapping</li><li>Don’t add unneeded context</li><li>Use default arguments instead of short circuiting or conditionals</li><li>Avoid magic string</li></ul><h3><a href="https://github.com/thangchung/clean-code-dotnet#4-functions">Functions</a></h3><ul><li>Function arguments (2 or fewer ideally)</li><li>Functions should do one thing</li><li>Function names should say what they do</li><li>Functions should only be one level of abstraction</li><li>Don’t use flags as function parameters</li><li>Avoid Side Effects</li><li>Don’t write to global functions</li><li>Don’t use a Singleton pattern</li><li>Encapsulate conditionals</li><li>Avoid negative conditionals</li><li>Avoid conditionals</li><li>Avoid type-checking</li><li>Remove dead code</li></ul><h3><a href="https://github.com/thangchung/clean-code-dotnet#5-objects-and-data-structures">Objects and Data Structures</a></h3><ul><li>Use getters and setters</li><li>Make objects have private/protected members</li></ul><h3><a href="https://github.com/thangchung/clean-code-dotnet#6-classes">Classes</a></h3><ul><li>Use method chaining</li><li>Prefer composition over inheritance</li></ul><h3><a href="https://github.com/thangchung/clean-code-dotnet#7-solid">SOLID</a></h3><ul><li>Single Responsibility Principle (SRP)</li><li>Open/Closed Principle (OCP)</li><li>Liskov Substitution Principle (LSP)</li><li>Interface Segregation Principle (ISP)</li><li>Dependency Inversion Principle (DIP)</li><li>Don’t repeat yourself (DRY)</li></ul><h3><a href="https://github.com/thangchung/clean-code-dotnet#8-testing">Testing</a></h3><ul><li>Single concept per test</li></ul><h3><a href="https://github.com/thangchung/clean-code-dotnet#9-concurrency">Concurrency</a></h3><ul><li>Use Async Await</li></ul><h3><a href="https://github.com/thangchung/clean-code-dotnet#10-error-handling">Error Handling</a></h3><ul><li>Don’t ignore caught errors</li><li>Use consistent capitalization</li><li>Function callers and callees should be close</li></ul><h3><a href="https://github.com/thangchung/clean-code-dotnet#11-formatting">Formatting</a></h3><ul><li>Uses <em>.editorconfig</em> file</li></ul><h3><a href="https://github.com/thangchung/clean-code-dotnet#12-comments">Comments</a></h3><ul><li>Only comment things that have business logic complexity</li><li>Don’t leave commented out code in your codebase</li><li>Don’t have journal comments</li><li>Avoid positional markers</li></ul><h3><strong>Recap</strong></h3><p>We’re still working on this list, and I believe that it <strong>will be longer and accuracy</strong>. <strong>Our team looks forward to having all of you to involve, contribute and help to make this list more useful for </strong><a href="https://github.com/thangchung/clean-code-dotnet"><strong>.NET/.NET Core</strong></a><strong> Community.</strong></p><p>Again, the <strong>clean code list</strong> for <a href="https://github.com/thangchung/clean-code-dotnet">.NET/.NET Core</a> can be found at <a href="https://github.com/thangchung/clean-code-dotnet#12-comments"><strong>https://github.com/thangchung/clean-code-dotnet</strong></a></p><p>Thanks for reading! If you enjoyed this article, be sure to <strong>click</strong> 👏 symbol below so others will see it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7674373fccaf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/clean-code-for-net-coding-craftsman-7674373fccaf">Clean Code for .NET Coding Craftsman</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Domain-Driven Design in 10 minutes]]></title>
            <link>https://medium.com/hackernoon/clean-domain-driven-design-in-10-minutes-6037a59c8b7b?source=rss-920427ad169f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6037a59c8b7b</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[cloud-native]]></category>
            <dc:creator><![CDATA[Thang Chung]]></dc:creator>
            <pubDate>Thu, 06 Sep 2018 10:32:52 GMT</pubDate>
            <atom:updated>2018-09-07T12:36:18.291Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qLH9BLF-7Xm9xa9r_Tf52Q.jpeg" /><figcaption><a href="https://pixabay.com/en/water-lily-aquatic-plant-nature-3504363/">Source</a></figcaption></figure><h3>Key takeaways</h3><ul><li><a href="https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215">Domain-Driven Design</a> (DDD) works with <a href="https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html">Clean Architecture</a> (CA)</li><li>Clean DDD in a practical way (<a href="https://www.martinfowler.com/microservices/">microservices</a>)</li><li>Clean DDD on the <a href="https://landscape.cncf.io/">cloud-native way</a></li></ul><p>I wrote about CA topic last year and today I’m going to write out another part of it. CA is good to make the software architecture more succinctly and manageable, but the boilerplate codes are also huge (if you used to implement it you will get my point — a lot of requests, responses, interactors or use cases, interfaces, and classes need to be created, see my implementation at <a href="https://github.com/thangchung/blog-core">https://github.com/thangchung/blog-core</a>). Back in the time, when we implement <a href="https://martinfowler.com/bliki/CQRS.html">Command Query Responsibility Segregation</a> (<a href="https://cqrs.files.wordpress.com/2010/11/cqrs_documents.pdf">CQRS</a>) and <a href="http://codebetter.com/gregyoung/2010/02/20/why-use-event-sourcing/">Event Sourcing</a> (ES)patterns that will make many people feel unhappy with those of boilerplate codes. That’s a reason I research and write out what I know and learn about make CA more practical and maintainable ways.</p><p>For those people aren’t familiar with CA, please see my previous article at <a href="https://hackernoon.com/applying-clean-architecture-on-web-application-with-modular-pattern-7b11f1b89011">https://hackernoon.com/applying-clean-architecture-on-web-application-with-modular-pattern-7b11f1b89011</a></p><p>Let’s start with the whole picture in the application I have worked in a way of CA as following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YVxaXqiIYskqPauNKZ2OSA.png" /></figure><ol><li>Domain code that doesn’t depend on any framework or libraries. It makes these core components can re-use in the future</li><li>A bit outer layer of domain code that acts like adaptors, we use it to implement Unit of Work (UOW), Generic Repository (GR), Event Bus, Dependency Injection and a lot of more stuff</li><li>Partial CA patterns with request and response DTOs and handlers for them. We utilize <a href="https://github.com/jbogard/MediatR">MediatR </a>and <a href="https://github.com/AutoMapper/AutoMapper">AutoMapper </a>libs for simplifying this kind of work, and another reason that it’s cool 😍 Thank you <a href="https://github.com/jbogard">Jimmy</a>!</li><li>Partial presenter for Web API</li></ol><p>After implemented, it will end up with the structure of code as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nyO3sQkhzTX6eqROzmCAdg.png" /></figure><p>Nothing hyper to talk here, it quite simple and clean, right? Lets diving into the details so that we will understand more about it. I’m going to show you the Cart Service (<a href="https://thenewstack.io/miniservices-a-realistic-alternative-to-microservices">miniservices </a>pattern actually) with the business like add a new product to a cart, add more product to that cart, get the current cart with products, update that cart, delete product out of the current cart, and final action is to check out the cart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uz9yzs0cZp6JyaAdihIsNg.png" /><figcaption><a href="https://www.gartner.com/webinar/3437517">https://www.gartner.com/webinar/3437517</a></figcaption></figure><p>That’s it. Then we have the use cases like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*N5Ki5xVklljDHXp3J8SRnA.png" /></figure><p>If you like API first approach, then we should have the OpenAPI as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*1VXuRcayTTDXXDZ3QcMBag.png" /></figure><p>Let&#39;s narrow down to the code because I know that all we are developers so that the code should be easier to understand, right?</p><h3>Domain components (mainly DDD patterns)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOnHX-ofuZiBxih_WM7uGg.png" /></figure><p>Cart.cs</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d73b1de6ba31644170d71b37c4311be/href">https://medium.com/media/3d73b1de6ba31644170d71b37c4311be/href</a></iframe><p>CartItem.cs</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f41e84a156919a7d8020d541bdf45b3/href">https://medium.com/media/6f41e84a156919a7d8020d541bdf45b3/href</a></iframe><p>Product.cs</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c980e9ccc69ad6e8cd0426a20a46dc00/href">https://medium.com/media/c980e9ccc69ad6e8cd0426a20a46dc00/href</a></iframe><h3>Infrastructure components</h3><p>Unit of Work, Generic Repository, Event Bus, ClientRequest, Dependency Injection… components are in NetCoreKit — A set of cloud-native tools and utilities for .NET Core — which is developed by myself (<a href="https://github.com/cloudnative-netcore/netcorekit">https://github.com/cloudnative-netcore/netcorekit</a>).</p><h3>Request/Response handlers</h3><ul><li>Get Cart with Products</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bb06cf903f9fd38855edb756830d13f/href">https://medium.com/media/3bb06cf903f9fd38855edb756830d13f/href</a></iframe><ul><li>Add Product to a Cart</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20cf5d38886234fce7a05e8f2230eb90/href">https://medium.com/media/20cf5d38886234fce7a05e8f2230eb90/href</a></iframe><ul><li>Update Product in the Cart</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4d0701b07605ec6dd9118879916a2f4/href">https://medium.com/media/f4d0701b07605ec6dd9118879916a2f4/href</a></iframe><ul><li>Delete Product in the Cart</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43fd19d156af60f874636df8ea93e28f/href">https://medium.com/media/43fd19d156af60f874636df8ea93e28f/href</a></iframe><ul><li>Checkout</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e8da28a609c8c1fe3c22575d5c1e62d/href">https://medium.com/media/4e8da28a609c8c1fe3c22575d5c1e62d/href</a></iframe><h3>Web API Presenter</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68582de4be065c9b1a640565d99c2f31/href">https://medium.com/media/68582de4be065c9b1a640565d99c2f31/href</a></iframe><h3>Cloud-Native parts</h3><p>This is the cloud-native apps so that we can package it to a container and host it Kubernetes if we want. The work to do that as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*9GcwL0w4nm_vZFcXu10Dhw.png" /></figure><p>Dockerfile</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9017c8b92a1b37a788b300ddcbc09aa1/href">https://medium.com/media/9017c8b92a1b37a788b300ddcbc09aa1/href</a></iframe><p>Kubernetes manifests</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b2f9e70e76dffbe7714027135404c48/href">https://medium.com/media/6b2f9e70e76dffbe7714027135404c48/href</a></iframe><p>That’s it for today. Hopefully with a ton of code that doesn’t make you dizzy 🙏.</p><h3>Recap</h3><p>The world has changed a lot from years recently so that we need to learn and flow with it. In this article, I showed you how can we combine CA with DDD, and host it to the cloud-native platform( Kubernetes in this case). That knowledge is my own, you can think of it in another way or create another stack for your own.</p><blockquote><em>The source code for this article can be found at </em><a href="https://github.com/vietnam-devs/coolstore-microservices">https://github.com/vietnam-devs/coolstore-microservices</a></blockquote><p>Thanks for reading! If you enjoyed this article, be sure to click 👏 symbol below so others will see it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6037a59c8b7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/clean-domain-driven-design-in-10-minutes-6037a59c8b7b">Clean Domain-Driven Design in 10 minutes</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 steps to bring CoolStore’s Service Mesh to Azure Kubernetes Service (AKS)]]></title>
            <link>https://medium.com/hackernoon/5-steps-to-bring-coolstores-service-mesh-to-azure-kubernetes-service-aks-9cd1a5aa008a?source=rss-920427ad169f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cd1a5aa008a</guid>
            <category><![CDATA[service-mesh]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Thang Chung]]></dc:creator>
            <pubDate>Wed, 29 Aug 2018 12:02:08 GMT</pubDate>
            <atom:updated>2018-09-08T06:28:21.052Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOB0XzSmZc4pXx2CrAeW2A.jpeg" /><figcaption><a href="https://pixabay.com/en/sailboats-race-yachts-yacht-racing-1375064/">Source</a></figcaption></figure><h3>The first words</h3><p>Service Mesh is a cutting-edge terminology in these days. I have seen that a lot of people starting to talk about this topic all over the world. The first time around 4 months ago, I started to have a look at it and really surprise a lot. How beautiful can it do to help us build a complex microservices stack actually makes me keep focusing on it?</p><p>As far as we know, in order to build the system with microservices approach comes with a lot of headache problems, and the main things are we need to pay attention to many concepts of the distributed computing. Everyone knows that distributed computing. In my personally, the distributed system is quite hard and not easy to adopt for a long time after it is coined many years ago. Many big companies like Twitter, Netflix, Google, Amazon, Microsoft… spent a lot of money and efforts to find and build the neat solutions on that. A ton of libraries and tools came in since then. You can search a lot of topics to discuss how can we build and use those solutions and tooling to avoid the trap in the microservices approach. Just googling a microservices keyword and you will believe in me.</p><p>The complex problems are communication, traffic control (route), security, and observe services quite hard to adopt, even if you are know everything about how to implement it. “<a href="https://istio.io/blog/2018/delayering-istio/delayering-istio/#don-t-optimize-layers-remove-them">Don’t optimize layers, remove them</a>” is a term that we heard a lot nowadays. But what the heck if we don’t need to optimize, instead of removing it. This sentence is quite buzzwords, but actually, it is real if you follow up to the end of this article, and find out by yourself how easy it can. Believe me!</p><p>In 2017, there are coming with a lot of tooling and orchestrator which helps us a lot in managing the dynamic and flexible of changes in software development (infrastructure as software). Some of those are Docker, Kubernetes, Istio… And just last couple of days, Istio released to 1.0.0 version and promise that they will become the big tooling in the service mesh world that helps us build up the microservice stack with a small effort.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D77SdcT9mRHt_7fCDm3GUg.png" /><figcaption><a href="http://layer5.io/service-meshes/">http://layer5.io/service-meshes</a></figcaption></figure><p>To start with the big thing, we need to set up and run the small thing first, I chose CoolStore project from JBoss Demo Center and Redhat Demo Center to demonstrate what I said. This project is implemented totally in Java Stack. I borrow the ideas and build up from scratch with .NET Core 2.x and NodeJS because of the popularity of .NET in my company and generally in my country as well.</p><p>In remain of this article, we will deploy the following Coolstore project as following to AKS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sPIxhXMMhDnbtXSh06g6Ag.png" /></figure><h3>Prerequisites</h3><ul><li>Windows 10</li><li>Windows Subsystem Linux (WSL — Ubuntu OS)</li><li>Docker for Windows (Kubernetes enabled)</li><li>Azure Account with a valid subscription</li><li>kubectl</li><li>helm</li><li>istioctl</li><li>Azure CLI 2.0 (az)</li></ul><h4><strong>Step 1:</strong> Install Docker for Windows and enable Kubernetes, Ubuntu WSL, kubectl, istioctl, helm and az</h4><p><strong>Step 2:</strong> Create coolstore AKS, enabled RBAC. Minimum should have 3 nodes (istio pilot needs it)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5cENk7jPJQPWr3iESggGQ.png" /></figure><p>And make sure checking to enable RBAC as following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lUHO_7Gtp9fmhn05A_JuXg.png" /></figure><p>Follow up with next steps to finish creating the cluster. It normally takes around 20 to 30 minutes.</p><p>After it finished, we should be able to access to the Dashboard with following steps</p><pre>&gt; az aks get-credentials --resource-group coolstore --name coolstore<br>&gt; kubectl proxy</pre><p>But now, you will not be able to access to Kubernetes Dashboard. Then we need to add several steps then</p><pre>&gt; kubectl create clusterrolebinding kubernetes-dashboard -n kube-system --clusterrole=cluster-admin --serviceaccount=kube-system:kubernetes-dashboard</pre><p>Get the token subsequently</p><pre>&gt; kubectl get secret $(kubectl get serviceaccount kubernetes-dashboard -n kube-system -o jsonpath=&quot;{.secrets[0].name}&quot;) -n kube-system -o jsonpath=&quot;{.data.token}&quot; | base64 --decode</pre><p>Paste the token to login page as <a href="http://localhost:8001/api/v1/namespaces/kube-system/services/kubernetes-dashboard/proxy/#!/login">http://localhost:8001/api/v1/namespaces/kube-system/services/kubernetes-dashboard/proxy/#!/login</a></p><p><strong>Step 3:</strong> Install Istio on AKS</p><p>Due to some of the timeout issues for helm at now so that I couldn’t use helm to install, but export it to yaml file, then using kubectl to create it on AKS. Download istio 1.0.0, then upzip to somewhere on the machine. Following command to export and deploy it to AKS</p><pre>&gt; helm template install/kubernetes/helm/istio --namespace istio-system &gt; istio-dump.yaml<br>kubectl create -f istio-dump.yaml</pre><pre>&gt; kubectl create -f istio-dump.yaml</pre><p><strong>Step 4:</strong> Install Coolstore on AKS</p><p>Get the internal istio-ingress IP by using</p><pre>&gt; kubectl get services istio-ingressgateway -n istio-system -o=jsonpath={.spec.clusterIP}</pre><p>Create the values.aks.yaml with content like</p><pre>gateway:</pre><pre>  ip: 10.0.106.82</pre><p>Then run helm command</p><pre>&gt; helm template deploys/charts/coolstore -f deploys/charts/coolstore/values.aks.yaml &gt; deploys/k8s/dev-all-in-one.aks.yaml</pre><p>Finally, we inject sidecar with this command</p><pre>&gt; istioctl kube-inject -f deploys/k8s/dev-all-in-one.aks.yaml | kubectl apply -f -</pre><p><strong>Step 5:</strong> Put mapping for hosts file</p><p>Get external IP on istio ingress by using</p><pre>&gt; kubectl get svc -n istio-system</pre><p>It should print out something like</p><pre>...<br>istio-ingressgateway       LoadBalancer   10.106.52.19     localhost     80:31380/TCP,443:31390/TCP,31400:31400/TCP,15011:32131/TCP,8060:30958/TCP,15030:31983/TCP,15031:30365/TCP   8d<br>...</pre><p>Then, we only need to copy 10.106.52.19 to C:\Windows\System32\drivers\etc\hosts file as following</p><pre>10.106.52.19 id.coolstore.aks<br>10.106.52.19 api.coolstore.aks<br>10.106.52.19 coolstore.aks</pre><p>From now on, we can access website at <a href="http://coolstore.aks">http://coolstore.aks</a>, identity provider at <a href="http://id.coolstore.aks">http://id.coolstore.aks</a>, and api gateway at <a href="http://api.coolstore.aks">http://api.coolstore.aks</a></p><p>Let say we access to <a href="http://api.coolstore.aks">http://api.coolstore.aks</a>/cart/swagger, then we should see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhJ_a1WIXkc1wyn9SIn-7Q.png" /></figure><p>And the website at <a href="http://coolstore.aks">http://coolstore.aks</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJ0bhx6fJJXHUUTM7JTD7w.png" /></figure><p>Hola! We done. Lets explore and enjoy the world of Service Mesh.</p><h3>Final Thoughts</h3><p>In 2018, we have enough of tooling to make our dream comes to. We have Docker to package your piece of the application, then we don’t worry about which programming language that we used to implement the application. That means we have portability attribute in software development. From now on, we can bring this image and start to run it anytime, anywhere on any platforms (cloud-native apps). But then we need some tool for control and orchestrate your containers in Cloud Native platforms. That where Kubernetes come in to play its role. We have the tool just to control and help us to orchestrate our container to play the correct way on the correct role, and on the correct policy that we allow by define in manifest files. What makes it different finally? Service Mesh will help you to control your traffic, secure communication, define the way services connecting together, and essentially observation your activities.</p><p>We will see the emerge of Service Mesh in next couple of years. And also the next couple of articles from me in this year about this topic.</p><blockquote><em>The source code for this article can be found at </em><a href="https://github.com/vietnam-devs/coolstore-microservices">https://github.com/vietnam-devs/coolstore-microservices</a></blockquote><p>Thanks for reading! If you enjoyed this article, be sure to click 👏 symbol below so others will see it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cd1a5aa008a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/5-steps-to-bring-coolstores-service-mesh-to-azure-kubernetes-service-aks-9cd1a5aa008a">5 steps to bring CoolStore’s Service Mesh to Azure Kubernetes Service (AKS)</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement Generic Queries by combining EntityFramework Core and GraphQL.NET?]]></title>
            <link>https://medium.com/hackernoon/how-to-implement-generic-queries-by-combining-entityframework-core-and-graphql-net-77ac8faf4a22?source=rss-920427ad169f------2</link>
            <guid isPermaLink="false">https://medium.com/p/77ac8faf4a22</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[crm]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Thang Chung]]></dc:creator>
            <pubDate>Mon, 08 Jan 2018 00:01:02 GMT</pubDate>
            <atom:updated>2019-02-13T06:30:31.522Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Vj5WjMDX78oNRqSGrWzeyg.jpeg" /><figcaption><a href="https://pixabay.com/en/graph-success-cooperation-together-1019845/">Source</a></figcaption></figure><p>Currently, I have struggled with the problems such as I must implement the query many times for any entity in my data model. I thought that would be great if we can expose all entities to the APIs or maybe a way to limited some of the sensitive entities, and other sides or components subsequently simply to query it (just like a generic query to avoid boilerplate code when we implemented over and over the query function for all entities in the system).</p><p>I spend a long time look deeply in <a href="https://github.com/OData/WebApi">OData</a> project (the parser component actually), but it couldn’t end up with the satisfaction. Maybe because it is too complex and a lot of schemas need to define in the up-front time. And moreover, it is only used by .NET ecosystem (e.g. <a href="https://msdn.microsoft.com/en-us/library/gg334767%28v=crm.8%29.aspx?f=255&amp;MSPPError=-2147217396">Microsoft Dynamic CRM</a>, <a href="https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/use-odata-query-operations-in-sharepoint-rest-requests">Microsoft Sharepoint</a>…).</p><p>I really want a solution that can work, adapt and consume well to other ecosystems or components like front-end, mobile or maybe IoT devices. That is a reason I choose <a href="https://github.com/facebook/graphql">GraphQL </a>by Facebook. I think I don’t need to explain more about why it is so cool at these times. For more information about it, I highly recommend you to read this article <a href="https://dev-blog.apollodata.com/2017-the-year-in-graphql-124a050d04c6">2017: The year in GraphQL</a>.</p><p>In this article, I will show you about my POC project that tries to combine <a href="https://github.com/aspnet/EntityFrameworkCore">Entity Framework Core</a> and <a href="https://github.com/graphql-dotnet/graphql-dotnet">GraphQL.NET</a>, then we can use it to submit <a href="http://graphql.org/learn/queries/">gql DSL language</a> at the front-end and query every entity in your database via the back-end.</p><p>Thank you, <a href="https://medium.com/u/282dc6f79eac">Joe McBride</a> and <a href="https://medium.com/u/6a0d6cd86d0">Stef Heyenrath</a> for your great libraries (y)</p><h3>Prerequisites</h3><ul><li><a href="https://www.microsoft.com/net/download">.NET Core 2.0 SDK</a></li><li><a href="https://docs.microsoft.com/en-us/ef/core/">Entity Framework Core 2.x</a></li><li><a href="https://graphql-dotnet.github.io/getting-started/">GraphQL.NET</a> library</li><li><a href="https://github.com/StefH/System.Linq.Dynamic.Core">System.Linq.Dynamic.Core</a> library</li><li><a href="https://github.com/domaindrivendev/Swashbuckle.AspNetCore">Swagger UI</a></li><li><a href="https://www.visualstudio.com/downloads/">Visual Studio 2017</a></li></ul><h3>Database Schema</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*lkfUWDz9_J1ZJZuAoADXWg.png" /></figure><h3>Graph Schema Model</h3><p>We define the model for columns (metadata for a table in the database) in database as following</p><pre>public class ColumnMetadata<br>{<br>    public string ColumnName { get; set }<br>    public string DataType { get; set; }<br>}</pre><p>Then, we do the same thing for the table as below</p><pre>public class TableMetadata<br>{<br>    public string TableName { get; set; }<br>    public string AssemblyFullName { get; set; }<br>    public IEnumerable&lt;ColumnMetadata&gt; Columns { get; set; }<br>}</pre><p>Because we have attached the prefix for every table in the database (e.g. dbo.crm_Tasks) so we need a mapping table which helps us to resolve the friendly name for the entity (e.g. tasks when we submitted the query in UI)</p><pre>public interface ITableNameLookup<br>{<br>    bool InsertKeyName(string friendlyName);<br>    string GetFriendlyName(string correctName);<br>}</pre><pre>public class TableNameLookup : ITableNameLookup<br>{<br>    private IDictionary&lt;string, string&gt; _lookupTable = new Dictionary&lt;string, string&gt;();</pre><pre>    public bool InsertKeyName(string correctName)<br>    {<br>        if(!_lookupTable.ContainsKey(correctName))<br>        {<br>            var friendlyName = CanonicalName(correctName);<br>            _lookupTable.Add(correctName, friendlyName);<br>            return true;<br>        }<br>        return false;<br>    }</pre><pre>    public string GetFriendlyName(string correctName)<br>    {<br>        if (!_lookupTable.TryGetValue(correctName, out string value))<br>            throw new Exception($&quot;Could not get {correctName} out of the list.&quot;);<br>        return value;<br>    }</pre><pre>    private string CanonicalName(string correctName)<br>    {<br>        var index = correctName.LastIndexOf(&quot;_&quot;);</pre><pre>        var result = correctName.Substring(<br>                index + 1,<br>                correctName.Length - index - 1);</pre><pre>        return Char.ToLowerInvariant(result[0]) + result.Substring(1);<br>    }<br>}</pre><p>Now is the time to put all the schema models into the database metadata as below</p><pre>public interface IDatabaseMetadata<br>{<br>    void ReloadMetadata();<br>    IEnumerable&lt;TableMetadata&gt; GetTableMetadatas();<br>}</pre><pre>public sealed class DatabaseMetadata : IDatabaseMetadata<br>{<br>    private readonly DbContext _dbContext;<br>    private readonly ITableNameLookup _tableNameLookup;</pre><pre>    private string _databaseName;<br>    private IEnumerable&lt;TableMetadata&gt; _tables;</pre><pre>    public DatabaseMetadata(DbContext dbContext, ITableNameLookup tableNameLookup)<br>    {<br>        _dbContext = dbContext;<br>        _tableNameLookup = tableNameLookup;</pre><pre>        _databaseName = _dbContext.Database.GetDbConnection().Database;</pre><pre>        if (_tables == null)<br>            ReloadMetadata();<br>    }</pre><pre>    public IEnumerable&lt;TableMetadata&gt; GetTableMetadatas()<br>    {<br>        if (_tables == null)<br>            return new List&lt;TableMetadata&gt;();</pre><pre>        return _tables;<br>    }</pre><pre>    public void ReloadMetadata()<br>    {<br>        _tables = FetchTableMetaData();<br>    }</pre><pre>    private IReadOnlyList&lt;TableMetadata&gt; FetchTableMetaData()<br>    {<br>        var metaTables = new List&lt;TableMetadata&gt;();</pre><pre>        foreach (var entityType in <strong>_dbContext.Model.GetEntityTypes()</strong>)<br>        {<br>            var tableName = <strong>entityType.Relational().TableName</strong>;</pre><pre>            metaTables.Add(new TableMetadata<br>            {<br>                TableName = tableName,<br>                AssemblyFullName = <strong>entityType.ClrType.FullName</strong>,<br>                Columns = GetColumnsMetadata(entityType)<br>            });</pre><pre>            _tableNameLookup.InsertKeyName(tableName);<br>        }<br>            <br>        return metaTables;<br>    }</pre><pre>    private IReadOnlyList&lt;ColumnMetadata&gt; GetColumnsMetadata(IEntityType entityType)<br>    {<br>        var tableColumns = new List&lt;ColumnMetadata&gt;();</pre><pre>        foreach (var propertyType in entityType.GetProperties())<br>        {<br>            var relational = propertyType.Relational();<br>            tableColumns.Add(new ColumnMetadata<br>            {<br>                ColumnName = relational.ColumnName,<br>                DataType = relational.ColumnType<br>            });<br>        }</pre><pre>        return tableColumns;<br>    }<br>}</pre><p>We have the schema models on the codes which will be populated all schema information of EfCore entities when the application started.</p><h3>Graph Type</h3><p>Let define the type of the GraphQL as below</p><pre>public class TableType : ObjectGraphType&lt;object&gt;<br>{<br>    public QueryArguments TableArgs<br>    {<br>        get; set;<br>    }</pre><pre>    private IDictionary&lt;string, Type&gt; _databaseTypeToSystemType;<br>    protected IDictionary&lt;string, Type&gt; DatabaseTypeToSystemType<br>    {<br>        get<br>        {<br>            if (_databaseTypeToSystemType == null)<br>            {<br>                _databaseTypeToSystemType = new Dictionary&lt;string, Type&gt; {<br>                    { &quot;uniqueidentifier&quot;, typeof(String) },<br>                    { &quot;char&quot;, typeof(String) },<br>                    { &quot;nvarchar&quot;, typeof(String) },<br>                    { &quot;int&quot;, typeof(int) },<br>                    { &quot;decimal&quot;, typeof(decimal) },<br>                    { &quot;bit&quot;, typeof(bool) }<br>                };<br>            }<br>            return _databaseTypeToSystemType;<br>        }<br>    }</pre><pre>    public TableType(TableMetadata tableMetadata)<br>    {<br>        Name = tableMetadata.TableName;<br>        foreach (var tableColumn in tableMetadata.Columns)<br>        {<br>            InitGraphTableColumn(tableColumn);<br>        }<br>    }</pre><pre>    private void InitGraphTableColumn(ColumnMetadata columnMetadata)<br>    {<br>        var graphQLType = (ResolveColumnMetaType(columnMetadata.DataType)).GetGraphTypeFromType(true);<br>        var columnField = Field(<br>            graphQLType,<br>            columnMetadata.ColumnName<br>        );</pre><pre>        columnField.Resolver = new NameFieldResolver();<br>        FillArgs(columnMetadata.ColumnName);<br>    }</pre><pre>    private void FillArgs(string columnName)<br>    {<br>        if (TableArgs == null)<br>        {<br>            TableArgs = new QueryArguments(<br>                new QueryArgument&lt;StringGraphType&gt;()<br>                {<br>                    Name = columnName<br>                }<br>            );<br>        }<br>        else<br>        {<br>            TableArgs.Add(new QueryArgument&lt;StringGraphType&gt; { Name = columnName });<br>        }</pre><pre>        TableArgs.Add(new QueryArgument&lt;IdGraphType&gt; { Name = &quot;id&quot; });<br>        TableArgs.Add(new QueryArgument&lt;IntGraphType&gt; { Name = &quot;first&quot; });<br>        TableArgs.Add(new QueryArgument&lt;IntGraphType&gt; { Name = &quot;offset&quot; });<br>    }</pre><pre>    private Type ResolveColumnMetaType(string dbType)<br>    {<br>        if (DatabaseTypeToSystemType.ContainsKey(dbType))<br>            return DatabaseTypeToSystemType[dbType];</pre><pre>        return typeof(String);<br>    }<br>}</pre><p>The above codes help the application to identify the data type and some of the query arguments like pagination, projection… See the final part of this article when I showed you the result of the query.</p><h3>Graph Resolver</h3><p>To make the GraphQL understands the database schema which is populated, we need to create some of the revolvers as following</p><pre>public class NameFieldResolver : IFieldResolver<br>{<br>    public object Resolve(ResolveFieldContext context)<br>    {<br>        var source = context.Source;</pre><pre>        if (source == null)<br>        {<br>            return null;<br>        }</pre><pre>        var name = Char.ToUpperInvariant(context.FieldAst.Name[0]) + context.FieldAst.Name.Substring(1);<br>        var value = GetPropValue(source, name);</pre><pre>        if (value == null)<br>        {<br>            throw new InvalidOperationException($&quot;Expected to find property {context.FieldAst.Name} on {context.Source.GetType().Name} but it does not exist.&quot;);<br>        }</pre><pre>        return value;<br>    }</pre><pre>    private static object GetPropValue(object src, string propName)<br>    {<br>        return src.GetType().GetProperty(propName).GetValue(src, null);<br>    }<br>}</pre><p>And moreover, we define the resolver for each field in the database schema</p><pre>public class MyFieldResolver : IFieldResolver<br>{<br>    private TableMetadata _tableMetadata;<br>    private DbContext _dbContext;</pre><pre>    public MyFieldResolver(TableMetadata tableMetadata, DbContext dbContext)<br>    {<br>        _tableMetadata = tableMetadata;<br>        _dbContext = dbContext;<br>    }</pre><pre>    public object Resolve(ResolveFieldContext context)<br>    {<br>        var queryable = <strong>_dbContext.Query(_tableMetadata.AssemblyFullName)</strong>;<br>        if (context.FieldName.Contains(&quot;_list&quot;))<br>        {<br>            <br>            var first = context.Arguments[&quot;first&quot;] != null ? <br>                context.GetArgument(&quot;first&quot;, int.MaxValue) :<br>                int.MaxValue;</pre><pre>            var offset = context.Arguments[&quot;offset&quot;] != null ? <br>                context.GetArgument(&quot;offset&quot;, 0) : <br>                0;</pre><pre>            return queryable<br>                .Skip(offset)<br>                .Take(first)<br>                .ToDynamicList&lt;object&gt;();<br>        }<br>        else<br>        {<br>            var id = context.GetArgument&lt;Guid&gt;(&quot;id&quot;);<br>            return <strong>queryable.FirstOrDefault($&quot;Id == </strong><a href="http://twitter.com/0"><strong>@0</strong></a><strong>&quot;, id)</strong>;<br>        }<br>    }<br>}</pre><p>Noticing to the dynamic LINQ in the code above (bold text colors). Thank you for <strong>System.Linq.Dynamic.Core</strong> lib, without it we need to do a lot of works to get the same things like this. Now adding one more thing which makes us can do a query by using its assembly name as</p><pre>public static class DbContextExtensions<br>{<br>    public static IQueryable Query(this DbContext context, string entityName) =&gt;<br>     context.Query(context.Model.FindEntityType(entityName).ClrType);</pre><pre>    static readonly MethodInfo SetMethod = typeof(DbContext).GetMethod(nameof(DbContext.Set));</pre><pre>    public static IQueryable Query(this DbContext context, Type entityType) =&gt;<br>     (IQueryable)SetMethod.MakeGenericMethod(entityType).Invoke(context, null);<br>}</pre><p>If you want to know more about the solution, deep dive more at <a href="https://stackoverflow.com/questions/48041821/dynamically-access-table-in-ef-core-2-0">https://stackoverflow.com/questions/48041821/dynamically-access-table-in-ef-core-2-0</a>.</p><h3>Graph Query</h3><p>Now is the time we need to define the query for our application. Two things to notice as following</p><ul><li>If we want to query <strong>task entity</strong> , then we would like to define as <strong>{ tasks (id: “&lt;id here&gt;”) {id, name} }</strong>, based on the database schema that we have defined. The result will be returned by only one record in the output</li><li>If we want to query the <strong>list of task entities</strong>, we need to do just like <strong>{ tasks_list (offset:1, first:10) { id, name } } </strong>which has a meaning to query the list of task entities from page 1 and get 10 records firstly. The result should be a list of task records in the database via the back-end</li></ul><p>As you see above, we define 2 fields for each entity which we have in the database. For example, if you have 10 entities in DbContext, then we have 10 x 2=20 fields in the GraphQL definition. Let me show you a code</p><pre>public class GraphQLQuery : ObjectGraphType&lt;object&gt;<br>{<br>    private IDatabaseMetadata _dbMetadata;<br>    private ITableNameLookup _tableNameLookup;<br>    private DbContext _dbContext;</pre><pre>    public GraphQLQuery(<br>        DbContext dbContext, <br>        IDatabaseMetadata dbMetadata,<br>        ITableNameLookup tableNameLookup)<br>    {<br>        _dbMetadata = dbMetadata;<br>        _tableNameLookup = tableNameLookup;<br>        _dbContext = dbContext;</pre><pre>        Name = &quot;Query&quot;;</pre><pre>        foreach (var metaTable in _dbMetadata.GetTableMetadatas())<br>        {<br>            var tableType = new TableType(metaTable);<br>            var friendlyTableName = _tableNameLookup.GetFriendlyName(metaTable.TableName);</pre><pre>            AddField(new FieldType<br>            {<br>                Name = friendlyTableName,<br>                Type = tableType.GetType(),<br>                ResolvedType = tableType,<br>                Resolver = new MyFieldResolver(metaTable, _dbContext),<br>                Arguments = new QueryArguments(<br>                    tableType.TableArgs<br>                )<br>            });</pre><pre>            // lets add key to get list of current table<br>            var listType = new ListGraphType(tableType);<br>            AddField(new FieldType<br>            {<br>                Name = $&quot;{friendlyTableName}_list&quot;,<br>                Type = listType.GetType(),<br>                ResolvedType = listType,<br>                Resolver = new MyFieldResolver(metaTable, _dbContext),<br>                Arguments = new QueryArguments(<br>                    tableType.TableArgs                        <br>                )<br>            });<br>        }<br>    }<br>}</pre><p>We based on the schema that we got from previous steps to define the fields for the GraphQL query. Is it make sense to you?</p><h3>Graph Controller</h3><p>This final step of this article, we define the controller so that we can run the application. It is really simple as below</p><pre>[Route(&quot;graphql/api/query&quot;)]<br>public class GraphQLController : Controller<br>{<br>    private readonly Schema graphQLSchema;</pre><pre>    public GraphQLController(Schema schema)<br>    {<br>        graphQLSchema = schema;<br>    }</pre><pre>    [HttpPost]<br>    public async Task&lt;string&gt; Get([FromQuery] string query = &quot;{ tasks_list(offset:1, first:10) { id, name } }&quot;)<br>    {<br>        var result = await new DocumentExecuter().ExecuteAsync(<br>            new ExecutionOptions()<br>            {<br>                Schema = graphQLSchema,<br>                Query = query                    <br>            }<br>        ).ConfigureAwait(false);</pre><pre>        if (result.Errors?.Count &gt; 0)<br>        {<br>            return result.Errors.ToString();<br>        }</pre><pre>        var json = new DocumentWriter(indent: true).Write(result.Data);</pre><pre>        return json;<br>    }<br>}</pre><p>Don’t forget to wire up all components to the IOC container as</p><pre>public static class ServiceCollectionExtensions<br>{<br>    public static IServiceCollection AddMyGraphQL(this IServiceCollection services)<br>    {<br>        services.AddScoped&lt;ITableNameLookup, TableNameLookup&gt;();<br>        services.AddScoped&lt;IDatabaseMetadata, DatabaseMetadata&gt;();<br>        services.AddScoped((resolver) =&gt;<br>        {<br>            var dbContext = resolver.GetRequiredService&lt;ApplicationDbContext&gt;();<br>            var metaDatabase = resolver.GetRequiredService&lt;IDatabaseMetadata&gt;();<br>            var tableNameLookup = resolver.GetRequiredService&lt;ITableNameLookup&gt;();</pre><pre>            var schema = new Schema { Query = new GraphQLQuery(dbContext, metaDatabase, tableNameLookup) };<br>            schema.Initialize();</pre><pre>            return schema;<br>        });</pre><pre>        return services;<br>    }<br>}</pre><h3>Put it all together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*1pB1JVW757lHggQdOGBIEw.jpeg" /><figcaption><a href="https://pixabay.com/en/the-fishermen-fishing-the-work-2983615/">Source</a></figcaption></figure><p>After finished all the steps above, the structure of this as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*Xv8jzUVLqCmBNHG76ai8mA.png" /></figure><p>This is just a POC project which I will have to do more refactor in the future. Not sure just yet. Let run it by press F5, I will show you how it works</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*ieCPKilvKzN0m8w63cuZMg.png" /></figure><p>Let input some of GraphQL query above then click <strong>Try it out!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*06qhrq4VYsTp_P-fianmvg.png" /></figure><p>The database schema automatically loads as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*ADANX5gZYYdYH1QG4VmHAA.png" /></figure><p>And it builds out all the GraphQL fields as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*PCKmSlK0YGmJFU-1vlbxiA.png" /></figure><p>With <strong>{ tasks_list(offset:1, first:10) { id, name } }</strong> for the input, you will receive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*HDKk2QkqQJrZfOXOJS_zEg.png" /></figure><p>If I change it to <strong>{ tasks(id: “621CFF32-A15D-4622–9938–0028EA0C3FEE”) { name, id, taskStatus } }</strong>, it should be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*c7pYAFJrIJTyWUZcazcYqw.png" /></figure><p>That enough for today :) Let me know how do you feel.</p><h3>Source code</h3><p>All the source code can be found at <a href="https://github.com/vietnam-devs/crmcore">https://github.com/vietnam-devs/crmcore</a>. If you like it give me a clap, I will actually have more motivation to it better.</p><h3>Recap</h3><p>This article is all about the POC that I have done for combining between Entity Framework Core and GraphQL.NET. The result that we can dynamically use some of the libraries in .NET for making the query more dynamic and flexible in the real business cases. But there are some of the caveats as following</p><ul><li>Authentication and authorization for entities didn’t mention yet.</li><li>Maybe we can hide and don’t expose everything out of the world like this article.</li><li>Mutation side and other concepts of GraphQL were not mentioned just yet this article.</li><li>Not integrating with the front-end (react/redux with <a href="https://github.com/apollographql/apollo-client">Apollo client</a> lib).</li><li>Solution for child relationships with the current entity (I haven’t had a solution yet, and welcome if anyone can help on that :p)</li><li>You name it and let me know in the comments then I can improve it later.</li></ul><h3>Additional Readings</h3><ul><li><a href="http://graphql-dotnet.github.io">http://graphql-dotnet.github.io</a></li><li><a href="https://dev-blog.apollodata.com/2017-the-year-in-graphql-124a050d04c6">https://dev-blog.apollodata.com/2017-the-year-in-graphql-124a050d04c6</a></li><li><a href="https://github.com/chentsulin/awesome-graphql#lib-dotnet">https://github.com/chentsulin/awesome-graphql#lib-dotnet</a></li><li><a href="https://github.com/nreco/data/tree/master/examples/SqliteDemo.GraphQLApi">https://github.com/nreco/data/tree/master/examples/SqliteDemo.GraphQLApi</a></li><li><a href="https://github.com/landmarkhw/Dapper.GraphQL">https://github.com/landmarkhw/Dapper.GraphQL</a></li><li><a href="https://github.com/JacekKosciesza/StarWars">https://github.com/JacekKosciesza/StarWars</a></li><li><a href="https://github.com/JuergenGutsch/GraphQlDemo">https://github.com/JuergenGutsch/GraphQlDemo</a></li></ul><p><strong>Thanks for reading!</strong> If you enjoyed this article, be sure to <strong>CLICK</strong> 👏 symbol below so <strong>OTHERS</strong> will <strong>SEE</strong> it.</p><ul><li>13 Feb 2019: Correct some of meanings and typos in this article</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77ac8faf4a22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/how-to-implement-generic-queries-by-combining-entityframework-core-and-graphql-net-77ac8faf4a22">How to implement Generic Queries by combining EntityFramework Core and GraphQL.NET?</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Construct the Web Application to Sleep Well at Night?]]></title>
            <link>https://medium.com/hackernoon/how-to-construct-the-web-application-to-sleep-well-at-night-302e7e7dc39f?source=rss-920427ad169f------2</link>
            <guid isPermaLink="false">https://medium.com/p/302e7e7dc39f</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Thang Chung]]></dc:creator>
            <pubDate>Tue, 14 Nov 2017 10:45:32 GMT</pubDate>
            <atom:updated>2017-11-14T10:45:32.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*TMLTessMIUwn3J_qNvq8PQ.jpeg" /><figcaption><a href="https://pixabay.com/en/woman-girl-bella-read-sleep-2197947/">Source</a></figcaption></figure><p><strong>How many times did you struggle to pick up the appropriated technical stack for your front-end project</strong>? <strong>How hard when we structure the web skeleton for the very first in the project</strong>? <strong>How many nights could you not get to sleep well</strong>? If you like me, then this article is just for you.</p><p>Nowadays, the web development is <strong>emerging really fast</strong>. We feel like if we don’t learn new thing then we become a caveman from that day. A lot of technologies out there is for web development, but in this article, I would only like to focus on the React Ecosystem. Because I like React library and its ecosystem, I spent a lot of time to research and work on it for a long time.</p><p>The previous article from this series can be found at <a href="https://hackernoon.com/applying-clean-architecture-on-web-application-with-modular-pattern-7b11f1b89011">How to Organize CLEAN ARCHITECTURE to Modular Patterns in 10 Minutes</a></p><p>So let’s get started.</p><h3>Dependencies (framework and technologies)</h3><ul><li><a href="https://github.com/aspnet/JavaScriptServices">JavaScriptServices</a> (React/Redux template)</li><li><a href="https://github.com/mrholek/CoreUI-Free-Bootstrap-Admin-Template/tree/master/React_Full_Project">CoreUI</a> (with <a href="https://github.com/reactstrap/reactstrap">ReactStrap</a>)</li><li><a href="https://github.com/Microsoft/TypeScript">TypeScript</a></li><li><a href="https://github.com/webpack/webpack">WebPack</a></li><li><a href="https://github.com/yarnpkg/yarn">Yarn</a></li><li><a href="https://github.com/sass/sass">Sass</a></li><li>Others: <a href="https://github.com/ReactTraining/react-router">react-router</a>, <a href="https://github.com/react-tools/react-table">react-table</a>, <a href="https://github.com/erikras/redux-form">redux-form</a>, <a href="https://github.com/redux-observable/redux-observable">redux-observable</a>…</li></ul><h3>SSR and CSR</h3><p>SSR stands for <strong>Server Side Rendering</strong>, and CSR for <strong>Client Side Rendering</strong>. Check out the article at <a href="https://medium.com/walmartlabs/the-benefits-of-server-side-rendering-over-client-side-rendering-5d07ff2cefe8">The Benefits of Server Side Rendering Over Client Side Rendering</a> for a full explanation about it. I just mention a bit because I know somebody will wonder why do I use JavaScriptServices packages to make the skeleton for this article. Apparently, I am focusing in .NET Core in this time, and I have a look around other technologies like NodeJS, Java, PHP, Python, you name it, and found out that they also have a way to make the server rendering the scripts and related things like style, HTML… So in this time, I will tell you how can we do it using JavaScriptServices from the .NET world.</p><p>Some of the caveats in this approach are:</p><ul><li>It makes the development more complex because now we need to have a look at the server console startup as well, some of the cases make the debugging more complicated.</li><li>It makes the first rendering a little bit slower if you dump a lot of tasks upfront.</li></ul><p>The benefits of this approach as</p><ul><li>It makes SEO better and more consistency</li><li>End-users shall feel like the content comes up very fast because it was composed upfront on the server side already (in case we cache the output content it makes more sense)</li></ul><blockquote>To be honest, if you want to build a site that very heavy to SEO related, then you should consider it. Someone asked me the question that if they build the Web Application just for in-house users used, so could they also need to consider to build the web app with SSR approach? In this case, I would like to recommend that they should go with CSR approach for a bit naturally in term of the front-end development. But again it is up to you, I let you choose it.</blockquote><p>Stay tuned for some simple steps that make the project with SSR approach in Visual Studio 2017. Firstly, you need to choose to create a new solution for the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*0bwmHh8GAluiQDa4dmhePA.png" /></figure><p>Secondly, it will take you to the following screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*rolbFbM4sSuevVlk9kS83A.png" /></figure><p>Final step, we have the project structure as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*ozmTyUDxfcwrX2yQBevgaQ.png" /></figure><p>Simple. Isn’t it? This is just for any .NET developer with a basic level :) Let rolling out to other following excited things</p><h3>Why use TypeScript?</h3><p>In this section, I just want to make clear that the reason I use TypeScript not only because its benefits, but also my team is familiar with it. Let first analyzing a bit about the pros of it:</p><ul><li>Don’t care about a lot of ES6, ES7, ES8… releases anymore</li><li>Don’t want to have some of the naive exceptions in the production related to type constraints</li><li>A large code-based that a big team to works in, then you need to have a way to avoid common bugs (type system bugs)</li><li>A back-end team that is familiar with C#, then we will be benefits of usage TypeScript (a lot of concepts from the statically-typed language like class, interface…)</li></ul><p>Beside of that, we also struggle many nights to fighting with typing system, like in this article when I work with react-table, I try to pull the <a href="http://twitter.com/types/react-table">@types/react-table</a> package from NPM, but a lot of conflicts and incompatible with the newest react-table package. Then I just recognized that actually, that typing library has not owned to react-table’s author (other guys maintain it). Then I decide to go with any variable declaration when using this library.</p><blockquote>I don’t want to compare between TypeScript and Flow because of a lot of biases here. One more reason because I am working on TypeScript then it will be unfair if I talk about it. A lot of people do comparisons out there. Just googling it<strong>.</strong></blockquote><h4>Work with un-typing library in TypeScript (react-table)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*voHlryGHGFzFbD4xwrYqnQ.jpeg" /><figcaption><a href="https://pixabay.com/en/dogs-pensive-reluctant-pet-sad-2195708/">Source</a></figcaption></figure><p>Actually, when working on the project, we have found that sometimes we need to use the un-typing library (react-table in this case) so that we need to declare it with <a href="https://www.ecma-international.org/ecma-262/5.1/">ES 5.1</a> style. Let’s deep dive into how we make the react-table works well with others. We need to put following code into the code:</p><pre>const ReactTable: any = require(&#39;react-table&#39;).default;</pre><p>Now, we can use ReactTable instance in anywhere inside this file. Let says we process and bind the data for the table as</p><pre>const table = (<br>  &lt;ReactTable<br>    columns={columns}<br>    manual<br>    data={this.props.blogs}<br>    className=&quot;-striped -highlight&quot;<br>    defaultPageSize={10}<br>    showPageSizeOptions={false}<br>    filterable<br>    defaultSorted={[<br>      {<br>        id: &#39;title&#39;,<br>        desc: true<br>      }<br>    ]}<br>    pages={this.props.totalPages}<br>    loading={this.props.loading}<br>    onFetchData={this.fetchData}<br>    getTdProps={(state: any, rowInfo: any, column: any, instance: any) =&gt; {<br>      return {<br>        onClick: (event: any, handleOriginal: any) =&gt; {<br>          this.props.history.replace(`/admin/blog/${rowInfo.original.id}`);<br>          if (handleOriginal) {<br>            handleOriginal();<br>          }<br>        }<br>      };<br>    }}<br>    previousText={&lt;i className=&quot;icon-arrow-left&quot; /&gt;}<br>    nextText={&lt;i className=&quot;icon-arrow-right&quot; /&gt;}<br>  /&gt;<br>);</pre><p>As you can see the code above, several places declare with any type. That’s fair enough. Because now we will <strong>handle types by our-self</strong>. This is simple but the time when I started coding, I got a <strong>lot of troubles to find a way to make the un-typing library</strong> work well with others. Hope this tip will help someone like me get rid of the trouble in the upfront phase.</p><h3>Duck typing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*EmER71a0KyEt0cpr249dsw.jpeg" /><figcaption><a href="https://pixabay.com/en/geese-goose-family-family-goslings-2494952/">Source</a></figcaption></figure><blockquote>“If it walks like a duck and it quacks like a duck, then it must be a duck.” — <a href="https://en.wikipedia.org/wiki/Duck_typing">Wiki</a></blockquote><p>For the sake of well-organized code, I use duck typing for bundling reducers, action types and actions in the web application. To my experience, we need to handle the <strong>{actionTypes, actions, reducer}</strong> over and over again in our redux code. With <a href="https://github.com/erikras/ducks-modular-redux">duck typing proposed</a> by <a href="https://github.com/erikras">Erik Rasmussen</a>, we can avoid a lot of messy code (functional code), and turn them into modules (business code), it makes more sense in term of bug fixing in the future as well. Let imagine that you have a bug, and you need to find out the place that caused it, then you just need to go to one place (specific module in this case) to read the code and debug it.</p><p>Let see how can I organize the code for it in the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*WBGzhqYxxDUDF3AvZMRWZw.png" /></figure><ul><li><strong>Components</strong> folder contains all dump components</li><li><strong>Configs</strong> folder contains only configuration info, in this case, it exports the literal object to outside</li><li><strong>Containers</strong> folder contains all smart components</li><li><strong>redux</strong> folder contains modules folder which has several duck typing here and there middleware folder which manage redux side-effects</li><li><strong>utils</strong> folder contains some of the utility pieces of code that helping out for some of the complicated work, normally it is a pure function, then it can be easy to make a test</li><li><strong>boot-client.tsx</strong> is a boot client file (because we follow up with the JavaScriptServices)</li><li><strong>boot-server.tsx</strong> is a boot server file (doing some works like prepare routers, store… once again because we use JavaScriptServices)</li><li><strong>routes.tsx</strong> contains all the possible routes can have in the system</li></ul><p>In any redux application, we need having action, action creator, store, side-effect and so on. Subsequently, I will so you how can I do it with duck typing.</p><p>First of all, we add the type of structure we want to use. Let say Blog type as below</p><pre>export type Blog = {<br>  id: string;<br>  title: string;<br>  description?: string;<br>  theme?: number;<br>  image?: string;<br>  postsPerPage: number;<br>  daysToComment: number;<br>  moderateComments: boolean;<br>};</pre><p>Then, we add BlogState interface</p><pre>export interface BlogState {<br>  loading: boolean;<br>  loaded: boolean;<br>  addLoading: boolean;<br>  ids: any;<br>  blogByIds: any;<br>  blogSelected: Blog | null;<br>  themes: Theme[];<br>  error: any;<br>  page: number;<br>  totalPages: number;<br>}</pre><blockquote>Forgive me for some of <strong>any </strong>type declaration in here :(</blockquote><p>We need to declare several action types as</p><pre>// Load blogs<br>const LOAD_BLOGS = &#39;LOAD_BLOGS&#39;;<br>const LOAD_BLOGS_SUCCESSED = &#39;LOAD_BLOGS_SUCCESSED&#39;;<br>const LOAD_BLOGS_FAILED = &#39;LOAD_BLOGS_FAILED&#39;;</pre><pre>// The rest of the source code in my GitHub</pre><p>And, action for each of them</p><pre>interface LoadBlogAction extends Action {<br>  type: typeof LOAD_BLOGS;<br>  page: number;<br>}</pre><pre>interface LoadBlogSuccessedAction extends Action {<br>  type: typeof LOAD_BLOGS_SUCCESSED;<br>  items: any;<br>  totalPages: number;<br>  page: number;<br>}</pre><pre>interface LoadBlogFailedAction {<br>  type: typeof LOAD_BLOGS_FAILED;<br>  error: any;<br>}</pre><pre>// The rest of the source code in my GitHub<br>...</pre><p>Then, we define the KnownAction for the reducer</p><pre>export type KnownAction =<br> | LoadBlogAction<br> | LoadBlogSuccessedAction<br> | LoadBlogFailedAction<br> // The rest of the source code in my GitHub<br>;</pre><p>Some of the epics (redux-observable in this case) to handle the side-effect</p><pre>export const blogEpics: any = [<br>  (action$: ActionsObservable&lt;LoadBlogAction&gt;): Observable&lt;Action&gt; =&gt; {<br>    return action$<br>      .ofType(LOAD_BLOGS)<br>      .debounceTime(100)<br>      .switchMap(action =&gt;<br>        blogRequest<br>          .loadBlogs(action.page)<br>          .map(result =&gt; {<br>            return actionCreators.loadBlogsByPageSuccessed(result.response);<br>          })<br>          .catch(error =&gt;<br>            Observable.of(actionCreators.loadBlogsByPageFailed(error))<br>          )<br>      );<br>  }</pre><pre>  // The rest of the source code in my GitHub.<br>];</pre><p>I don’t gonna explain what I do with redux-observable in this article. Check out <a href="https://medium.com/dailyjs/using-redux-observable-to-handle-asynchronous-logic-in-redux-d49194742522">Using redux-observable to handle asynchronous logic in Redux</a> for more information you need.</p><p>We define Action Creator for them as the following:</p><pre>export const actionCreators = {<br>  loadBlogsByPage: (page: number): Action =&gt;<br>    &lt;LoadBlogAction&gt;{ type: LOAD_BLOGS, page },</pre><pre>  loadBlogsByPageSuccessed: (data: any) =&gt;<br>    &lt;LoadBlogSuccessedAction&gt;{ type: LOAD_BLOGS_SUCCESSED, ...data     },</pre><pre>  loadBlogsByPageFailed: (error: any) =&gt;<br>    &lt;LoadBlogFailedAction&gt;{ type: LOAD_BLOGS_FAILED, error },</pre><pre>  // The rest of the source code in my GitHub<br>};</pre><p>Final step, we define the following code for the reducer</p><pre>export const reducer: Reducer&lt;BlogState&gt; = (<br>  state: BlogState,<br>  action: KnownAction<br>) =&gt; {<br>  switch (action.type) {<br>    case LOAD_BLOGS:<br>      return {<br>        ...state,<br>        loading: true<br>      };</pre><pre>    case LOAD_BLOGS_SUCCESSED:<br>      console.log(action);<br>      return {<br>        ...state,<br>        ids: action.items.map((blog: Blog) =&gt; blog.id),<br>        blogByIds: action.items.reduce((obj: any, blog: Blog) =&gt; {<br>          obj[blog.id] = blog;<br>          return obj;<br>        }, {}),<br>        loaded: true,<br>        loading: false,<br>        page: action.page || 0,<br>        totalPages: action.totalPages,<br>        blogSelected: null<br>      };</pre><pre>     case LOAD_BLOGS_FAILED:<br>      return {<br>        ...state,<br>        ids: [],<br>        blogByIds: {},<br>        error: action.error,<br>        loaded: true,<br>        loading: false,<br>        page: 0,<br>        blogSelected: null<br>      };</pre><pre>     // The rest of the source code in my GitHub</pre><pre>     default:<br>      const exhaustiveCheck: never = action;<br>      if (typeof exhaustiveCheck != &#39;undefined&#39;) break;<br>  }</pre><pre>return (<br>    state || {<br>      loading: true,<br>      loaded: false,<br>      redirectTo: &#39;/&#39;,<br>      ids: [],<br>      blogByIds: [],<br>      blogSelected: null,<br>      themes: [<br>        {<br>          value: 1,<br>          label: &#39;Default&#39;<br>        }<br>      ],<br>      error: null,<br>      page: 0,<br>      totalPages: 0<br>    }<br>  );<br>};</pre><p>That’s it. And it should be in one file (blog.ts).</p><blockquote><strong>Sometimes, I feel that this file is too long. Do you have any suggestion for organizing effectively? Feel free to comments at the end, I am happy to discuss it.</strong></blockquote><h3>A few dot or too many dots</h3><p>Have you ever faced the following issue with your code?</p><pre>import {  ComponentA,  ComponentB,  ComponentC,  ComponentE} from &#39;../../../../components&#39;;</pre><p>It turns your code into messy and bloated structure. If you feel annoying on this issue, I will help you do it better.</p><p>First step, putting index.js file in each root folder structure to gather related stuff as the image following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*9D-0ZprRu3c8uUlPUAxjug.png" /></figure><p>And the code inside it in this case is</p><pre>export { default as Aside } from &#39;./Aside/Aside&#39;;<br>export { default as Breadcrumb } from &#39;./Breadcrumb/Breadcrumb&#39;;<br>export { default as Footer } from &#39;./Footer/Footer&#39;;<br>export { default as Header } from &#39;./Header/Header&#39;;<br>export { default as Sidebar } from &#39;./Sidebar/Sidebar&#39;;<br>export { renderTextBoxField as TextBoxField, renderNumberField as NumberField, renderSingleSelectField as SingleSelectField } from &#39;./Form/Input&#39;;<br>export { default as CheckboxField } from &#39;./Form/Checkbox&#39;;<br>export { confirmationBox as ConfirmationBox } from &#39;./Confirmation/ConfirmationBox&#39;;</pre><p>The second step, we need to let Webpack config knows about it as well</p><pre>resolve: {<br>  extensions: [&quot;.js&quot;, &quot;.jsx&quot;, &quot;.ts&quot;, &quot;.tsx&quot;],<br>  alias: {<br>    OurComponents: path.resolve(__dirname, &quot;./ClientApp/components/&quot;),<br>    OurModules: path.resolve(__dirname, &quot;./ClientApp/redux/modules/&quot;),<br>    OurConfigs: path.resolve(__dirname, &quot;./ClientApp/configs/&quot;),<br>    OurUtils: path.resolve(__dirname, &quot;./ClientApp/utils/&quot;)<br>  }<br>}</pre><p>Now Webpack will do aliases for your code into simple one, but we also need to let TypeScript interpreter knows it :). In the tsconfig.json file put following code as</p><pre>&quot;paths&quot;: {<br>  &quot;OurComponents&quot;: [&quot;./ClientApp/components&quot;],<br>  &quot;OurComponents/*&quot;: [&quot;./ClientApp/components/*&quot;],<br>  &quot;OurModules&quot;: [&quot;./ClientApp/redux/modules&quot;],<br>  &quot;OurModules/*&quot;: [&quot;./ClientApp/redux/modules/*&quot;],<br>  &quot;OurConfigs&quot;: [&quot;./ClientApp/configs&quot;],<br>  &quot;OurConfigs/*&quot;: [&quot;./ClientApp/configs/*&quot;],<br>  &quot;OurUtils&quot;: [&quot;./ClientApp/utils&quot;],<br>  &quot;OurUtils/*&quot;: [&quot;./ClientApp/utils/*&quot;]<br>}</pre><p>That’s it. Let look at how easy we can refer to our component now</p><pre>import { Breadcrumb, Sidebar, Header, Footer } from &#39;OurComponents&#39;;</pre><p>I really like this approach. How about you?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ROWyhfd-NVtlcL7g0XE3hg.jpeg" /><figcaption><a href="https://pixabay.com/en/baby-happy-clap-smile-fun-2320701/">Source</a></figcaption></figure><h3>Recap</h3><p>In this article, we walk through to <strong>several ways to organize the code more effectively</strong>. We analyze some of the reason why do we <strong>choose the SSR approach</strong>, then the reason we <strong>like TypeScript for code typing</strong>. Subsequently, we <strong>discuss Duck typing</strong> in a redux way. Finally, we give you a tip to <strong>avoid too many dots</strong> when you manipulate the file structure in code. Furthermore, we actually want to share more and more, but we want to let you suggest it. I know I have a lot of things to learn so that feel free to comment as below. I am really eager to hear from you.</p><h3>Resources</h3><p>The source code for this article can be found at my <a href="https://github.com/thangchung/blog-core">GitHub</a></p><h3>Additional Readings</h3><ul><li><a href="https://medium.com/walmartlabs/the-benefits-of-server-side-rendering-over-client-side-rendering-5d07ff2cefe8">https://medium.com/walmartlabs/the-benefits-of-server-side-rendering-over-client-side-rendering-5d07ff2cefe8</a></li><li><a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0">https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0</a></li><li><a href="https://github.com/erikras/ducks-modular-redux">https://github.com/erikras/ducks-modular-redux</a></li><li><a href="https://hackernoon.com/the-100-correct-way-to-structure-a-react-app-or-why-theres-no-such-thing-3ede534ef1ed?source=bookmarks---------18----------------">https://hackernoon.com/the-100-correct-way-to-structure-a-react-app-or-why-theres-no-such-thing-3ede534ef1ed</a></li><li><a href="https://medium.com/dailyjs/using-redux-observable-to-handle-asynchronous-logic-in-redux-d49194742522">https://medium.com/dailyjs/using-redux-observable-to-handle-asynchronous-logic-in-redux-d49194742522</a></li><li><a href="https://hackernoon.com/applying-clean-architecture-on-web-application-with-modular-pattern-7b11f1b89011">https://hackernoon.com/applying-clean-architecture-on-web-application-with-modular-pattern-7b11f1b89011</a></li></ul><p>Thanks for reading! If you enjoyed this article, be sure to <strong>CLICK</strong> 👏 symbol below so <strong>OTHERS</strong> will <strong>SEE</strong> it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=302e7e7dc39f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/how-to-construct-the-web-application-to-sleep-well-at-night-302e7e7dc39f">How to Construct the Web Application to Sleep Well at Night?</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Organize CLEAN ARCHITECTURE to Modular Patterns in 10 Minutes]]></title>
            <link>https://medium.com/hackernoon/applying-clean-architecture-on-web-application-with-modular-pattern-7b11f1b89011?source=rss-920427ad169f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b11f1b89011</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[modular]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[microsoft]]></category>
            <dc:creator><![CDATA[Thang Chung]]></dc:creator>
            <pubDate>Mon, 16 Oct 2017 13:09:03 GMT</pubDate>
            <atom:updated>2017-11-06T10:21:25.891Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cZ47i4cm7hXiqCoZx4eEg.jpeg" /></figure><p>You’re still concern about what is the <strong>Modern Software Architecture</strong> at the moment? You’re searching around to the <strong>Best Software Architecture</strong> to apply for your project. Go deeply into this article, it’s going to help you answering by your own.</p><p>In term of software development, the architecture of project is really important for the sake of <strong>maintenance and re-usability</strong> during many projects that I have worked. The software architecture ensures that the software that you build has a basis of the skeleton. It just likes the mainframe or the background of a house. Upon on that, we have a freedom to build anything we want.</p><p>The question always in my head these days is how can we <strong>combine the Clean Architecture and Modular pattern</strong>? I have done some of the experiments in the code, and finally, I decided to write it out in this article. The purpose is really straightforward for sharing what I have learned, and learn more what I get from feedback. This article is based on my experience in software development and how the modular approach gives the benefits and applies <strong>Clean Architecture concepts</strong> on it.</p><h3><strong>Modular patterns</strong></h3><p>The modular approach for the architecture is also a topic that we have talked a lot in our company. Back to 5 years ago, I worked on the big project that has a lot of people involved, and in that time, we had organized the architecture to the modular approach. And by the time, we know that with the modular we can <strong>cut the large monolith software into many vertical smaller monoliths</strong> and <strong>make the team works more easily</strong> because <strong>each team only needs to focus on the module that they work</strong>. Could anyone remember about the conflicted code in the big project? Could you spend the half of day (or more) just to merge the codes? It is really a nightmare, isn’t it.</p><p>So in the modular approach, we need to make sure that the modules should be independent enough so that it can be work by the sole developers in different teams. It should be in logical design style and gives us strong points as</p><ul><li>Help our software system is able to <strong>extensible, reusable, maintainable, and adaptable</strong>.</li><li><strong>Break large monolith stack</strong> into a flexible composite of collaborating modules (in monolith style).</li><li>Help newcomers to <strong>easy to understand the business features and the functionalities of the system</strong> (because it is small enough)</li><li>Open the door to <strong>migrate into the Microservices Architecture</strong> (if need, but it is not easy to adopt it from my point of view)</li></ul><h3><strong>Clean Architecture</strong></h3><p><a href="https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html">The Clean Architecture</a> has coined since 2012 by Uncle Bob, and by the time, <strong>it becomes an important things in the software architecture world</strong>. We can see <a href="https://github.com/android10/Android-CleanArchitecture">Android</a> using it by combination with <a href="https://msdn.microsoft.com/en-us/library/ff649571.aspx"><strong>MVP pattern</strong></a> to build the software architecture for the mobile app. A couple of articles out there also proposed to use Clean Architecture for the web application. In early this year, Uncle Bob published the book named <strong>“</strong><a href="https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164"><strong>Clean Architecture: A Craftsman’s Guide to Software Structure and Design</strong></a><strong>”</strong>. If you have never read that book before I highly recommend you to take a look at it. This book mentions a lot of best practices when using <a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod"><strong>SOLID</strong></a>, <strong>design patterns</strong> and some of <strong>tips and tricks in deployment work</strong> as well.</p><p>A bit overview about the clean architecture, if you have already known, please skip this and jump over to the implementation section. According to Clean Architecture, we need to <strong>ensure some of the important points</strong> below</p><blockquote>1. <strong>Independent of Frameworks</strong>. The architecture does not depend on the existence of some library of feature laden software. This allows you to use such frameworks as tools, rather than having to cram your system into their limited constraints.</blockquote><blockquote>2. <strong>Testable</strong>. The business rules can be tested without the UI, Database, Web Server, or any other external element.</blockquote><blockquote>3. <strong>Independent of UI</strong>. The UI can change easily, without changing the rest of the system. A Web UI could be replaced with a console UI, for example, without changing the business rules.</blockquote><blockquote>4. <strong>Independent of Database</strong>. You can swap out Oracle or SQL Server, for Mongo, BigTable, CouchDB, or something else. Your business rules are not bound to the database.</blockquote><blockquote>5. <strong>Independent of any external agency</strong>. In fact your business rules simply don’t know anything at all about the outside world.</blockquote><p>And it follows strictly the diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*B7LkQDyDqLN3rRSrNYkETA.jpeg" /></figure><h3><strong>Implementation</strong></h3><blockquote><em>“Talk is cheap. Show me the code.” — Linus Torvalds</em></blockquote><p>Let start off with the main story today, any project has to analyze and ask the customer about <strong>what they want to do for their system</strong> and <strong>what they need for their system to act for</strong>. They will give us bunch of <strong>use cases</strong> or <strong>user stories</strong> (if there is an agile project). And the final step, we will have to draw the use case diagram. For those people that could not catch what I said so far, I would like to analyze an example in the blog engine domain. Let say we want to build the blog website that have some of the features like read the blog, see the posts of this blog, add some of the comments in the public interface. And we definitely have a way to CRUD actions on blogs, posts, and comments. Beside of that, we also need to login into the system before we can modify the blogs, posts, and comments. Based on the requirement of features for this application, we’re going to end up with the use case diagram below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*CjxItXhe93qx6rooYGGJvQ.png" /></figure><p>Now is the time, I will show you how can I apply the modular pattern to this example. If you look at the diagram above, you will notice that we only have 3 main things for managing are authentication, blog, and post. Grab some ideas from Domain-Driven Design(<a href="https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215">Tackling Complexity in the Heart of Software </a>and <a href="https://www.amazon.com/Implementing-Domain-Driven-Design-Vaughn-Vernon/dp/0321834577">Implementing Domain-Driven Design</a> books are the good starting point from my point of view), in this case is <strong>Bounded Context pattern</strong>, I separate my application domain out to the Access Control Context, Blog Context and Post Context (I divide it into 3 Bounded Contexts because my domain knowledge like that, it will be different from others due to different domain experts, but at least it needs to sort out the business needs). Let put them together, and we have a diagram like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*thlo6OUZ9U8cL41Jjt1jgw.png" /></figure><p>Lets explaining a bit about the diagram above, the Access Control Context with the red color is for authentication and authorization tasks. The Blog Context filled with green color is for blog management includes setting up the blog, status assignment, and theme… The third one is the Post Context which manages its own comments and tags. As you can see, the Post Context has the relationship with others. For more information of how can we design the <strong>Bounded Context</strong> (<strong>Root aggregate</strong>) please come to <a href="https://vaughnvernon.co/?p=838">Effective Aggregate Design</a> articles, you will learn the huge of useful things. You have my promise :)</p><p>Too much for the theory, let now jump into the code. Due to the limitation of this article, I only can show you one Bounded Context code, and I would like to choose the Post Context because I think this is the most interested in. The rests, you can have a look at my GitHub codes —<strong><em> the link gives you at the end of this article</em></strong>. So far, some of you will question that what the heck Clean Architecture involves into this? Don’t panic. Let me show you the project structure, then you have the rest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*uVozyVYyjAopSg2FO5pQDw.png" /></figure><p>Is it clean for structuring the project? By the time, I found out that the <strong>simple structure</strong> does not only <strong>help new-comers easy to catch up and work on</strong> it, but also <strong>help code readers easy to figure out what we want to do and navigate through</strong> the large code base.<br> <br>For those people want to run this example project, I use <strong>.NET Core 2.0</strong> to implementation so that you need to install at least the <a href="https://www.microsoft.com/net/download/core#/runtime">run-time environment</a>.</p><p>Now I start to explain about the structure above. First, we have the <strong>Framework folder</strong> in the diagram, that contains all the stuff related to necessary toolkit for the project. <strong>Remember that we’re going to avoid using the abstraction in our code, but use the composition</strong> (<a href="https://en.wikipedia.org/wiki/Composition_over_inheritance">Composition over inheritance</a> in OOP). The BlogCore.Core will not need to depend on any framework or library, but on .NET SDK definitely (some of the cases we call its vanilla code). Additionally, we have 3 projects: BlogCore.Infrastructure, BlogCore.Infrastructure.AspNetCore and BlogCore.Infrastructure.EfCore that will depend on EntityFrameworkCore, AspNetCore and others libraries like Autofac, AutoMapper, FluentValidation, MediatR…</p><p>Second, <strong>Hosts folder</strong> in the middle of the diagram, We use it for putting the host projects there. You can see I have 2 hosts: one for the API (BlogCore.API) and another for the Single Page Application (BlogCore.App).</p><p>Third, <strong>Migrations folder</strong> is used to do the migrating works, in this case, we migrate data for the Access Control Context, Blog Context and Post Context. We can choose to migrate using Entity Framework migration and seed data for them. Otherwise, you can also use the T-SQL scripts to do the migration. It is up to you, I don’t say which one is better than others.</p><p>Finally, we have the <strong>Modules folder</strong> that contains the heart of this application. We have divided it into Bounded Context folders here, and make our architecture more clearly. Each Bounded Context has 2 sub-projects, e.g. BlogCore.PostContext and BlogCore.PostContext.Core. BlogCore.PostContext.Core only contains domain objects, contracts, and interfaces which is really good for another projects references. The rule is if we have another module that wants to use some of the classes, objects so that it should reference the &lt;Module name&gt;.Core and to the interface inside this project(<strong>only depends on the interface</strong> in another module. This will make loose-coupling for those modules. We will get a lot of benefits with this approach).</p><p>Lets see the Post Bounded Context structure in the details</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*QzvNXknzGsGHd7pu14HQng.png" /></figure><p>I think we should deep dive into some of the code to understand more about how can we implement the Clean Architecture with the Modular pattern for this project.</p><p>We have <strong>Post.cs entity</strong> that acts like Root Aggregate in the Post Context as</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baa21ba042c1eb01dae1133ee5bd67b0/href">https://medium.com/media/baa21ba042c1eb01dae1133ee5bd67b0/href</a></iframe><p>Then, we have the <strong>PostGenericRepository.cs</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ba8efa5d290f7991f5e0b6fc2fa3c7a/href">https://medium.com/media/0ba8efa5d290f7991f5e0b6fc2fa3c7a/href</a></iframe><p>We need to create the DbContext for the <strong>PostContext.cs</strong> as</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eead47721a54becec27049c252452d30/href">https://medium.com/media/eead47721a54becec27049c252452d30/href</a></iframe><p>In Clean Architecture, the use case is very important and should be designed very carefully. In my project, I named it as <strong>ListOutPostByBlogInteractor.cs</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbc3e221e40deca79d8cd01a7c268921/href">https://medium.com/media/dbc3e221e40deca79d8cd01a7c268921/href</a></iframe><p>After processing the business case for the Post Bounded Context, we need to aggregate some of the data related to the Access Control Bounded Context, and in this case, we get the Author information of it and use the IUserRepository interface to get the author’s details information. So that we introduce another class called <strong>ListOutPostByBlogPresenter.cs</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f72fad099286602565dac05c6f640f79/href">https://medium.com/media/f72fad099286602565dac05c6f640f79/href</a></iframe><p>And we need to have a place to register these dependency objects. So the <strong>Dependency Injection</strong> comes into play, and we use Autofac module in this project. The idea is the module will register all the dependency its own.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb175eed4aabf9e91b1fd10df686138f/href">https://medium.com/media/cb175eed4aabf9e91b1fd10df686138f/href</a></iframe><p>Yes, that’s enough, then we only need to introduce <strong>the API</strong> for what we did</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb260dcb8469d0ad356c54f60a92f9b2/href">https://medium.com/media/cb260dcb8469d0ad356c54f60a92f9b2/href</a></iframe><p><strong>Recap</strong></p><p>Today, I have walked you through the journey of how can we make the modular works well in the Clean Architecture. We at least know what is modular, what it’s actually important. We run through some of the overviews of Clean Architecture, and some of the strong points of it as well. And the last but not least, we know how to implement it using .NET Core 2.0.</p><p>What is not covered in this articles are the <strong>Data flow</strong>, <strong>Synchronized between Bounded Contexts</strong>, <strong>Unit Testing</strong>, <strong>Deployment </strong>for the Clean Architecture…I’m going to write more about them if you guys interested in, just drop the messages in the comment box below.</p><blockquote>The source code for this article can be found at <a href="https://github.com/thangchung/blog-core">https://github.com/thangchung/blog-core</a></blockquote><p>Thanks for reading! If you enjoyed this article, be sure to click 👏 symbol below so others will see it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b11f1b89011" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/applying-clean-architecture-on-web-application-with-modular-pattern-7b11f1b89011">How to Organize CLEAN ARCHITECTURE to Modular Patterns in 10 Minutes</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>