<?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 Džiugas Garla on Medium]]></title>
        <description><![CDATA[Stories by Džiugas Garla on Medium]]></description>
        <link>https://medium.com/@yooroo?source=rss-452b87037834------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*drXBB4PNFelh8BvF-y4h6g.png</url>
            <title>Stories by Džiugas Garla on Medium</title>
            <link>https://medium.com/@yooroo?source=rss-452b87037834------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:46:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yooroo/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[Reusable Self-Explanatory Mockings for Fast Quality Unit Test Writing.]]></title>
            <link>https://medium.com/c-sharp-programming/reusable-self-explanatory-mocks-for-fast-quality-unit-test-writing-net-code-samples-included-40226ebf5166?source=rss-452b87037834------2</link>
            <guid isPermaLink="false">https://medium.com/p/40226ebf5166</guid>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Džiugas Garla]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 11:21:24 GMT</pubDate>
            <atom:updated>2024-04-19T07:16:35.057Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reusable Self-Explanatory Mockings for Fast Quality Unit Test Writing. — .NET Code Samples included.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NmFi7lb7xKDxD980QHDVbw.png" /></figure><p><em>What is the purpose of mock objects?</em></p><p><em>A Mock Object acts as a substitute for an actual object, imitating its behavior under controlled circumstances. In software development, mocks replicate the behavior of real objects and assist in testing various components.</em></p><p><em>Much like how creators of protective vests utilize test dummies to replicate human responses of impact. Programmers create mock objects. They use them to assess the behaviour of specific objects in a system.</em></p><p><em>Developers can use mock objects. They let you create test scenarios without relying on things like databases. Mock objects simulate their behaviour. This is without the overhead of using a live database for each test.</em></p><p><em>Source: </em><a href="https://stackoverflow.com/a/3622466/12959213">https://stackoverflow.com/a/3622466/12959213</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NmFi7lb7xKDxD980QHDVbw.png" /></figure><h3>Mocking setups</h3><p>Mocking setups enhance code readability. They follow the KISS principle to keep it simple and DRY principle to avoid repetition. This is done with extension methods. They let you “add” methods to existing `Mock&lt;…&gt;` types. More information about .NET extension methods can be found <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods">here</a>.</p><p>Here are the key advantages of why I like to use mocking setups:</p><p><strong>Clear Naming</strong>: Each mocking setup is named to clearly explain its purpose. <em>A lack of self-explaining mockings will lead to confusion and extra effort to decipher mocking purpose.</em></p><p><strong>Reusability</strong>: Write once, and use multiple times. Ignoring reusability leads to duplicating code. This leads to more maintenance and potential inconsistencies.</p><p><strong>Intuitive Design</strong>: It just intuitively looks right and nice, resulting in code that looks less cluttered.</p><p>Yup, this is a good time-saving and self-explaining deal.</p><h3>How it works:</h3><p>It is pretty simple if you understand extension methods. You simply need to create an extension method for Mock&lt;...&gt;.</p><p>For instance, you have the Mock&lt;IFileIOManager&gt; mock:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*i502HFCL0OMpqhFy28cM_A.png" /><figcaption>Mock&lt;IFileIOManager&gt;</figcaption></figure><p>Now, if you need to set up a mock for its ReadStringAsync() method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*8YLoSiWjH2HrxA_8bWIX_w.png" /><figcaption>IFileIOManager contains ReadStringAsync() method which one I want to mock.</figcaption></figure><p>The creation of the mock setup extension should resemble this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JD1K1ibjVL2plPFGLWp7Og.png" /><figcaption>Setup_ReadString_ReturnString(mockRepository, str) extension mocks ReadString() method to always return predefined string.</figcaption></figure><p>Then, in your tests, you can call this extension as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*QP92alfVP7hMBYTJS2Kk5g.png" /></figure><p>The extension returns itself. Every setup can connect by a dot, like a chiuku chiuku train:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*kZIC6Cpvl-wm32Wyo3I-mw.png" /><figcaption>Easy to connect</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARLDbJYTENfDfUZsyz2nqw.png" /><figcaption>Chiuku chiuku train. <em>Image by author generated on </em><a href="http://fotor.com/"><em>Fotor</em></a><em>.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*enKU9kZ1PiYhkKFmLpvGfw.png" /></figure><blockquote>Thank you for taking the time to read this article.</blockquote><blockquote>I encourage you to share your insights to aid in enhancing future articles!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40226ebf5166" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/reusable-self-explanatory-mocks-for-fast-quality-unit-test-writing-net-code-samples-included-40226ebf5166">Reusable Self-Explanatory Mockings for Fast Quality Unit Test Writing.</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting User-Friendly Exception Middleware for .NET8: A Developer’s Dream]]></title>
            <link>https://yooroo.medium.com/crafting-user-friendly-exception-middleware-for-net8-a-developers-dream-29b196af6069?source=rss-452b87037834------2</link>
            <guid isPermaLink="false">https://medium.com/p/29b196af6069</guid>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[webapi]]></category>
            <dc:creator><![CDATA[Džiugas Garla]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 11:24:06 GMT</pubDate>
            <atom:updated>2024-04-19T07:22:25.075Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crafting User-Friendly Exception Middleware for .NET8: A Developer’s Dream</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NmFi7lb7xKDxD980QHDVbw.png" /></figure><p><em>Exception Definition:</em></p><p><em>An exception is an object signalling a program error or unexpected condition. Its role is to ease issue fixing or hand over information about the problem.</em></p><p><em>The exception object often includes a “stack trace,” pinpointing the exact error location. For example, when processing an API request and facing an issue, a software exception (usually with ‘throw’) can be generated and caught at the program’s outer loop. Then continue processing the request.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NmFi7lb7xKDxD980QHDVbw.png" /></figure><h4>Here’s why I feel a need to invest in a good exception handler:</h4><p>Dream exception handler acts as a reliable detective, providing detailed information about errors. This makes the troubleshooting process smoother, reducing the time and effort needed to address issues during development and after deployment. An effective exception handler ensures that even when issues arise, the application communicates errors in a clear and user-friendly manner.</p><p>Default .NET exception handler prints scary exceptions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NqsEM_DvbdUSUs3YSlwX8g.png" /><figcaption>Default exception</figcaption></figure><p>As evident, in most cases, the first four lines of the exception provide the most useful information, while subsequent lines just make visual distraction due to unnecessary text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAyFc2Z1a3JtorvWkDQ70Q.jpeg" /><figcaption>Scared developer. <em>Image by author generated on </em><a href="http://fotor.com/"><em>Fotor</em></a><em>.</em></figcaption></figure><p>And here is a custom exception:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLr8CEra8qQiwAB-Hlrpaw.png" /><figcaption>Custom exception</figcaption></figure><p>An effective exception handler in my opinion should deliver compact and comprehensible feedback, enabling developers to react quickly with focused and valuable information.</p><h3>How to do it?</h3><p>Firstly, let’s see a sample on how exception middleware works. It’s just like any other middleware, just with try/catch block inside it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*aLvJ6eXapstnLR-XKg2OIQ.png" /><figcaption>Sample of exception middleware</figcaption></figure><p>See, nothing complicated here. Just make sure to register the exception middleware app.UseMiddlemare&lt;ExceptionMiddleware&gt;(); before any other middleware.</p><p>Now let’s build effective exception middleware. For simplicity, I won’t use logging.</p><p>Initially, it’s essential to establish a custom exception DTO. In my web services application, each exception DTO returned to the client is an HttpExceptionDTO, encompassing a message, an HTTP status code enum, and an optional AdditionalDetailsDTO. These additional details offer developers concentrated and valuable insights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*q5QJIgCaa2zuN-iiWihXlQ.png" /><figcaption>HttpExceptionDTO</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*g9u3lQLvPYBhlC3dsazsLQ.png" /><figcaption>AdditionalDetailsDTO</figcaption></figure><p>The next step I like to do involves a slight modification to HttpResponseException, allowing me to specify both the error status code and include a custom message when throwing an exception. The default constructor of HttpResponseException only includes StatusCode or HttpResponseMessage, making the process of throwing exceptions considerably more intricate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94b515a632d7d7d49047d17ddbaade85/href">https://medium.com/media/94b515a632d7d7d49047d17ddbaade85/href</a></iframe><p>Comparing throwing an HTTP exception with and without that twist, the complexity difference is quite obvious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*J_X21ppoVbPRJqhT9DLOrQ.png" /><figcaption>Compact throwing exception with twisted HttpResponseException</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bK4ndlbEu5Rw3Pt5lb86xQ.png" /><figcaption>Throwing exception with original HttpResponseException</figcaption></figure><p>Up till now, everything was simple. Next step will be a bit more complicated. In this step, we retrieve the StackFrame of the method where an exception occurred, allowing us to display the location of errors within our own code. However, we lack visibility into the source code of external components like .NET or NuGet packages. To discern the local project, we identify project names included in our .sln solution and return the first local frame where the error occurred. Here is a code example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f4fccd0101b24d152c0ed82346048bf/href">https://medium.com/media/2f4fccd0101b24d152c0ed82346048bf/href</a></iframe><p>We’re now approaching the last phase, which involves the exception middleware itself. Within the InvokeAsync method, we capture HttpResponseException and trigger the handler method, passing along the exception, context, and status code arguments. In the case of any other exception type, a similar process is followed, but with a static status code argument set to HttpStatusCode.InternalServerError.</p><p>During the handling process, we configure the ContentType and StatusCode of the response, generate an exception DTO object containing all the previously prepared details, and proceed to write the response. A code snippet illustrating this is provided below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3267c18f150b3fbbf7f24f820e4312db/href">https://medium.com/media/3267c18f150b3fbbf7f24f820e4312db/href</a></iframe><blockquote><em>That’s it. Now we have this nice looking exception response model:</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLTiC_kDsNmYJMThmVVZfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*enKU9kZ1PiYhkKFmLpvGfw.png" /></figure><blockquote><em>Thank you for taking the time to read this article. I encourage you to share your insights to aid in enhancing future articles!</em></blockquote><p>Next suggested article:</p><p><a href="https://medium.com/c-sharp-progarmming/reusable-self-explanatory-mocks-for-fast-quality-unit-test-writing-net-code-samples-included-40226ebf5166">Reusable Self-Explanatory Mockings for Fast Quality Unit Test Writing.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29b196af6069" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Repository pattern in ASP.NET (.NET8) with some additional good practises]]></title>
            <link>https://medium.com/c-sharp-programming/repository-pattern-in-asp-net-net8-with-some-additional-good-practises-f88fa84fe771?source=rss-452b87037834------2</link>
            <guid isPermaLink="false">https://medium.com/p/f88fa84fe771</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Džiugas Garla]]></dc:creator>
            <pubDate>Fri, 10 Nov 2023 14:13:26 GMT</pubDate>
            <atom:updated>2024-04-19T07:21:11.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NmFi7lb7xKDxD980QHDVbw.png" /></figure><p><strong><em>What are those design patterns in programming, and why do we need them?</em></strong></p><p><em>In short design patterns are a repeatable solution to commonly occurring problems in code design. It is a description or template for how to solve a problem that can be used in many different situations.</em></p><p><em>Patterns offer established best practices, structuring code efficiently, maintaining consistency, saving time, aiding scalability and especially enhancing communication among developers.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NmFi7lb7xKDxD980QHDVbw.png" /></figure><h3>Repository pattern</h3><p>The pattern idea is that the data access code should be separated from the business logic code. The Repository Pattern provides a way to manage data access code in a separate layer, thus improving code maintainability.</p><p><strong>Why do we need to use a repository pattern?</strong></p><ul><li>Layers independency.</li><li>Reusability of layers and classes.</li><li>When writing logic, use repository interfaces for data retrieval. Each layer has a unique responsibility, ensuring atomic methods.</li><li>Helps to maintain code readability.</li><li>Interface-driven design alongside repository pattern allows to easily change implementations.</li></ul><p>Out of curiosity, I googled the meaning of the word “Repository” and it resulted this:</p><blockquote>A place where or receptacle in which things are or may be stored. F.e.: “a deep repository for nuclear waste”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAjvD6zSxfeB1NloWZY4Rg.jpeg" /><figcaption><em>A deep repository for nuclear waste</em></figcaption></figure><h4><strong>Layers using repository pattern</strong></h4><p>I like to separate more application layers than just repository for even better code efficiency, maintainability and so on. So great addition to this pattern would be to separate the API layer from business logic, and business logic layer from repository.</p><p>The dependencies would look like this:</p><ul><li><em>“API” </em>layer → “<em>Business” </em>layer.</li><li><em>“Business” </em>layer → “<em>Repository” </em>layer.</li><li><em>“Repository” </em>layer → “<em>Service client” </em>layer. (<em>To use external project APIs in our project, we can introduce an additional “Service client” layer. This layer will specifically collect data from third-party APIs</em>)</li></ul><p><strong>Responsibilities of each layer in short:</strong></p><p><strong><em>“API”</em></strong> → This is where application steering wheel and engine go. This layer is responsible for communicating with the app. We need it because there is no point in having business logic if we can’t use it. This layer can have controllers for API calls, hubs for websockets,<em> </em>middleware (<em>f.e.: Exception middleware</em>), ‘<em>Swagger</em>’ documentation and so on.</p><p><strong><em>“Business”</em></strong> → The brain of application. Must have business services, where all business logic goes on.</p><p><strong><em>“Repository”</em></strong> → It just gets the data that application needs. Must have repository services to get required data (<em>f.e.: from database, service client</em>).</p><p><strong><em>“Service client”</em></strong> → Gets data that repository needs from third party services. Must have service client, to get required data from others API’s (<em>f.e.: get data from </em>‘<em>Google Maps API</em>’).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1v4xsvxVutB9IJ3b0FVwgg.png" /><figcaption>Responsibilities of each layer with simplified examples.</figcaption></figure><p>Make sure that you refrain from taking any actions involving layers that aren’t part of their dependencies. For instance, only the business layer is permitted to make one-way requests to the repository layer, and no other layer should do so. Since the repository layer doesn’t rely on the business layer, it cannot make any requests to the business layer.</p><h4>Interface usage</h4><p>To ensure the isolation of data access code from other layers, a strategy is to designate every repository class as internal, preventing access from other layers. However, this approach raises the question of how business services can communicate with the repository. The solution is straightforward: utilize interfaces. This same principle can be applied to interactions between other layers.</p><p>While focusing on single responsibilities, we can implement dependency injections across layers instead of writing them into a single file. <em>Here is how it’s done:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htrpZVJar5kyQ8FXreiagw.png" /><figcaption>Dependency injections through layers</figcaption></figure><p>Now after we have done this we just add the interfaces we need in each service constructor. <em>Here is an example:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*QnBTaaAZxXnVne0_hhl-WA.png" /></figure><blockquote>Here you go. Congratulations on implementing the repository pattern!</blockquote><p><strong>Bits of Advice:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3KkuVrilNJzbxRaUxNHVoA.png" /><figcaption>“Core” layer addition</figcaption></figure><ul><li>If there is a requirement for commonly used code across multiple layers, such as string extensions, establishing a “Core” layer would serve as a dependency for all other layers.</li><li>Ensure that you avoid inadvertently using any restricted layers by reviewing your dependencies in the .csproj files.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*enKU9kZ1PiYhkKFmLpvGfw.png" /></figure><blockquote><em>Thank you for taking the time to read this article. I encourage you to share your insights to aid in enhancing future articles!</em></blockquote><p>Next suggested article:</p><p><a href="https://medium.com/c-sharp-progarmming/reusable-self-explanatory-mocks-for-fast-quality-unit-test-writing-net-code-samples-included-40226ebf5166">Reusable Self-Explanatory Mockings for Fast Quality Unit Test Writing.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f88fa84fe771" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/repository-pattern-in-asp-net-net8-with-some-additional-good-practises-f88fa84fe771">Repository pattern in ASP.NET (.NET8) with some additional good practises</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>