<?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 Özkan ARDİL on Medium]]></title>
        <description><![CDATA[Stories by Özkan ARDİL on Medium]]></description>
        <link>https://medium.com/@ozkanardil?source=rss-a94a2d59980f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mqQ8JZzcWdTFHAskFVrsSg.jpeg</url>
            <title>Stories by Özkan ARDİL on Medium</title>
            <link>https://medium.com/@ozkanardil?source=rss-a94a2d59980f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:17:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ozkanardil/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[Unit Testing Scenarios with xUnit: Writing Simple Tests for Login]]></title>
            <link>https://medium.com/@ozkanardil/unit-testing-scenarios-with-xunit-writing-simple-tests-for-login-9e9bd1ffb4bb?source=rss-a94a2d59980f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e9bd1ffb4bb</guid>
            <category><![CDATA[unitest]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[xunit]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Özkan ARDİL]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 14:36:18 GMT</pubDate>
            <atom:updated>2025-03-28T14:40:26.776Z</atom:updated>
            <content:encoded><![CDATA[<h4>Unit Test with xUnit for .NET Core</h4><h4>How to write unit tests for valid and incorrect login scenarios using xUnit and Fluent Validation in .NET Core projects?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*4Fr7H11-9SqECxu9Lg1FVA.png" /></figure><p>In this article we will write simple unit tests for login feature using <a href="https://github.com/ozkanardil/dml_starterkit">DML Starter Kit framework</a> open source project.</p><p>This article is part of our xUnit Testing Series, where we cover everything from the basics to advanced techniques.</p><p>Whether you’re a beginner or an experienced developer, I created this series to help you take your unit testing skills to the next level. In each article, I’ve tried to cover core concepts, best practices, and real-world examples to help you write robust and reliable tests.</p><p>Check out the full series below:</p><ul><li><a href="https://medium.com/@ozkanardil/the-power-of-unit-tests-why-and-how-to-implement-them-in-net-core-5a3e13541fcc">The Power of Unit Tests: Why and How to Implement Them in .NET Core</a></li><li>Unit Testing Scenarios with xUnit: Writing Simple Tests for Login <strong>(this article)</strong></li></ul><p>Without wasting any time, I’m going straight to my test. If we take a look at the project’s dependencies, we see that the following packages have been added automatically.</p><p>In the future, when writing tests, we will also install the other dependencies used in our project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*b4GAg5HKZu-C_PWY.png" /><figcaption>Default dependences of the xunit test project</figcaption></figure><p>I will write the first test for the Login class located in the features directory of the Application layer in the DML Starter Kit solution.</p><p>Therefore, as seen below, I created the GetLoginQueryHandlerTests.cs test class by forming a structure similar to the file structure in the Application layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*G5Iz-Z3JuIvb_u5N.png" /><figcaption>Folder structure of the Login unit test</figcaption></figure><p>Since a request coming to our application is first validated as input, I will create the initial tests for the validation rules. In our application, we perform all input validation processes using Fluent Validation. You will find the link to my article explaining the Fluent Validation integration steps below.</p><p><a href="https://medium.com/@ozkanardil/the-secret-weapon-to-error-free-software-fluent-validation-unveiled-38f83986e400">How to Use Fluent Validation in .NET Core MediatR: A Guide with Source Code</a></p><p>For the login process, we ask the user for their email and password. In the continuation of the article, I will write two simple tests to check whether the email is in a valid format and case-sensitive.</p><p>In my upcoming articles, I aim to provide detailed examples of how to write tests for more complex structures such as databases and dependency injection.</p><p>You can follow me to be automatically notified of my new posts.</p><p>Let’s continue with our topic.</p><p>We should give each test written an appropriate and explanatory name in conversational language.</p><p>Before writing our tests, we need to add the classes and other dependencies we will use in the tests to my class using dependency injection. Below, you can see how we injected the GetLoginQueryValidator() class.</p><pre>private readonly GetLoginQueryValidator _validator;</pre><pre> public GetLoginQueryValidatorTests()<br> {<br>     _validator = new GetLoginQueryValidator();<br> }</pre><h3>Valid Email Test</h3><p>Below, it is being tested that the verification of a valid email has been successfully completed.</p><pre>[Fact]<br>  public void Should_Pass_When_Email_Is_Valid()<br>  {<br>      // Arrange<br>      var query = new GetLoginQuery<br>      {<br>          Email = &quot;test@example.com&quot;,<br>          Password = &quot;ValidPassword123!&quot;<br>      };<br>      <br>      // Act<br>      var result = _validator.TestValidate(query);<br><br>      // Assert<br>      result.ShouldNotHaveValidationErrorFor(x =&gt; x.Email);<br>  }</pre><p>Now let me explain our test line by line.</p><pre>public void Should_Pass_When_Email_Is_Valid()</pre><p>In the signature of our test method, as I mentioned above, I gave it a name that, when read, would make it clear what the test does.</p><pre>// Arrange<br>var query = new GetLoginQuery<br>{<br>   Email = &quot;test@example.com&quot;,<br>   Password = &quot;ValidPassword123!&quot;<br>};</pre><p>In the “Arrange” part, which represents the first “A” of the AAA structure, we defined the parameters we will use in our test within a class.</p><pre>// Act<br>var result = _validator.TestValidate(query);</pre><p>We are sending the parameters to the Validation class we use in our project. TestValidate represents the GetLoginQueryValidator class that we injected into our test class using dependency injection.</p><pre>// Assert<br>result.ShouldNotHaveValidationErrorFor(x =&gt; x.Email);</pre><p>At the last line of our test, we check that no errors have occurred. If there are no errors, our test will be successfully concluded.</p><h3>Invalid Email Test</h3><p>Now we will test whether the expected error is thrown when an invalid email is sent. In this test, I will make our test more dynamic by using the InlineData structure I mentioned at the beginning of the article.</p><pre>[Theory]<br> [InlineData(&quot;testexample.com&quot;)]<br> [InlineData(&quot;test@&quot;)]<br> [InlineData(&quot;userdomain..com&quot;)]<br> public void Should_Not_Pass_When_Email_Is_Invalid(string invalidEmail)<br> {<br>     // Arrange<br>     var query = new GetLoginQuery<br>     {<br>         Email = invalidEmail,<br>         Password = &quot;ValidPassword123!&quot;<br>     };<br><br>     // Act<br>     var result = _validator.TestValidate(query);<br><br>     // Assert<br>     result.ShouldHaveValidationErrorFor(x =&gt; x.Email);<br> }</pre><p>Now let me explain our test code.</p><pre>[Theory]<br> [InlineData(&quot;testexample.com&quot;)]<br> [InlineData(&quot;test@&quot;)]<br> [InlineData(&quot;userdomain..com&quot;)]</pre><p>We indicate that the test will run multiple times with different parameters using [Theory]. By using [InlineData], we send a different parameter with each run, allowing us to execute our test under different conditions.</p><p>Since the rest of our test is the same as the previous one, I won’t repeat it.</p><p>We are checking here that an error should occur at the end of the code, while we were not expecting an error in the previous test.</p><h3>Testing Whether the Email Address is Case Sensitive</h3><p>Below, you see a simple test code that checks whether the email address is case sensitive or not.</p><pre>[Fact]<br> public void Should_Pass_When_Email_Is_CaseInsensitive()<br> {<br>     // Arrange<br>     var query = new GetLoginQuery<br>     {<br>         Email = &quot;Test@Example.COM&quot;,<br>         Password = &quot;ValidPassword123!&quot;<br>     };<br><br>     // Act<br>     var result = _validator.TestValidate(query);<br><br>     // Assert<br>     result.ShouldNotHaveValidationErrorFor(x =&gt; x.Email);<br> }</pre><p>To make it practical, I leave it to you to rewrite this test with multiple parameters.</p><h3>Running the Tests</h3><p>After writing our tests, let’s get to know the screen where we can see the test results by running them one by one or all together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/0*4DU-WmE3a84ujjpX.png" /><figcaption>Test Explorer screen in Visual Studio</figcaption></figure><p>Unlike many editors, Visual Studio offers a highly user-friendly Test Explorer. Below, it is possible to see at a glance that all tests are running successfully.</p><p>Additionally, it is possible to run the tests we want one by one using the tool bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5CIIMHT4EXo2q_s5.png" /><figcaption>Test explorer of the Visual Studio</figcaption></figure><p>In conclusion, writing unit tests is a crucial practice that enhances software quality, helps identify errors early, and improves code maintainability. By implementing comprehensive test scenarios and covering various edge cases, we can ensure the reliability of critical functionalities. Utilizing frameworks like xUnit allows developers to create effective and maintainable tests, reducing the risk of future errors during code changes. This approach is essential in modern software development to ensure the stability and accuracy of applications.</p><p>Congratulations!</p><p>You successfully wrote your first unit test.</p><p>☺️</p><p>⬇️ You can examine the libraries where I have grouped my articles.</p><ul><li><a href="https://medium.com/@ozkanardil/list/da04dd09cb75">Tutorials</a></li><li><a href="https://medium.com/@ozkanardil/list/d6a4255c73bc">.NET Core Project Starter Kit</a></li><li><a href="https://medium.com/@ozkanardil/list/a28b2f3cec1c">.NET Core / C#</a></li></ul><p>👏 <em>If you found the content useful, you can</em><strong><em> follow me</em></strong><em> and make me happy in this way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/0*5sJPAZm3mr1NYxx6.gif" /></figure><p>💬 If there is something I overlooked, you can share it in the comments or contact me on my profile.</p><p>💬 Let me know in the comment section what have I missed? Where I was wrong?</p><p>👨‍👦‍👦 You can also share this article with your friend. Argue a little on it. It is known that the truth is born in a dispute.</p><p>🙃 Stay determined, stay focused, and keep going.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e9bd1ffb4bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Unit Tests: Why and How to Implement Them in .NET Core]]></title>
            <link>https://medium.com/@ozkanardil/the-power-of-unit-tests-why-and-how-to-implement-them-in-net-core-5a3e13541fcc?source=rss-a94a2d59980f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a3e13541fcc</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[xunit]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Özkan ARDİL]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 19:37:33 GMT</pubDate>
            <atom:updated>2025-03-28T14:39:55.789Z</atom:updated>
            <content:encoded><![CDATA[<h4>Unit Test with xUnit for .NET Core</h4><h3>The Power of Unit Tests: Why and How to Implement Them in .NET Core</h3><h4>While developing software, have you ever thought, “I changed this code, but did it break something else?” If your answer is “Yes,” you’re not alone!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ePWj7bBaNXFJfc7nTIh02Q.png" /></figure><p>Unit test is an automated test written to test small and independent parts (units) of code in software projects.</p><p>Usually, a specific function of a method or class is tested. The purpose is to verify that this code works as expected.</p><p>So, instead of manually testing the code you wrote over and over again to see if it really works, unit tests automate this job!</p><p>This article is part of our xUnit Testing Series, where we cover everything from the basics to advanced techniques.</p><p>Whether you’re a beginner or an experienced developer, I created this series to help you take your unit testing skills to the next level. In each article, I’ve tried to cover core concepts, best practices, and real-world examples to help you write robust and reliable tests.</p><p>Check out the full series below:</p><ul><li>The Power of Unit Tests: Why and How to Implement Them in .NET Core (this article)</li><li><a href="https://medium.com/@ozkanardil/unit-testing-scenarios-with-xunit-writing-simple-tests-for-login-9e9bd1ffb4bb?source=your_stories_page--------------------------------------------">Unit Testing Scenarios with xUnit: Writing Simple Tests for Login</a></li></ul><h3>Why Unit Test is Important?</h3><p>Imagine, you are working on a project and a few months later, a large part of the code needs to be changed.</p><p>If you don’t have unit tests, you might unintentionally break other parts of the code while making changes. But if you have tests, you don’t have to wonder, “Did I break something?” after these changes.</p><p>The biggest advantages of unit testing for you are as follows:</p><ul><li>It improves the quality of the code,</li><li>You catch mistakes early (So you won’t have a headache later!),</li><li>You can refactor with confidence (You’ll feel at ease while improving the code),</li><li>It speeds up the development process (Yes, it saves time in the long run!)</li></ul><p>It is possible to say that writing unit tests is one of the best ways to avoid future headaches!</p><p>So, why do most people still avoid writing unit tests?</p><p>Let’s talk about that in the next section. 😎</p><p>There are many reasons why developers are reluctant to write unit tests. If we take a look at these reasons;</p><ul><li><strong>Pressure to deliver code:</strong> Most software teams work under the pressure to quickly deliver functional features. Writing unit tests is perceived as an additional workload because it does not directly contribute to the visible part of the product.</li><li><strong>Short-term thinking:</strong> The mindset of “if the code works, there’s no need for more” is common. However, this increases technical debt and error costs in the long run.</li><li><strong>Invisible value:</strong> It can be difficult to understand the value of unit tests because they do not provide direct benefits to the end user.</li><li><strong>Hidden heroes:</strong> Unless an error occurs, the contribution of unit tests goes unnoticed. As long as there are no issues, no one sees the importance of these tests.</li><li><strong>Wrong testing approach:</strong> Writing tests that are not properly isolated, poorly designed, or solely focused on “coverage” makes the process unnecessarily complex.</li><li><strong>Mock and Stub challenges:</strong> For example, mocking dependencies in .NET Core projects using xUnit can sometimes be complex (especially if tools like Moq, AutoFixture, FluentAssertions are not used correctly).</li><li><strong>Fragile tests:</strong> Poorly written unit tests can constantly break with even a small code change. This situation reinforces the perception among developers that “writing tests is cumbersome and unnecessary.”</li><li><strong>Maintenance cost:</strong> A comprehensive and poorly structured test set can turn into a maintenance nightmare over time as the product develops. Lack of testing culture: If organizations do not clearly communicate the importance of writing tests and their long-term benefits to developers, this culture will not develop.</li><li><strong>Lack of leadership:</strong> If technical leaders do not promote test-driven development (TDD, BDD), developers do not prioritize it.</li></ul><p>It’s possible to extend the list.</p><p>If we categorize the reasons I listed above and focus on the deeper causes, it is possible to mention two root causes behind avoiding writing unit tests.<br>The first is the <strong>lack of perceived value</strong>, and the second can be expressed as <strong>time and delivery pressure</strong>.</p><p>These reasons are the most significant barriers to the development and widespread adoption of a testing culture, I would say.</p><p>As someone who has been involved in small, medium, and large-scale software projects for years, I can easily say that unit tests are very important, especially as the project grows, their significance increases even more.</p><p>If new developers joined the project after it progressed and the old developers left the project, unit tests become a lifeline. In this form, it wouldn’t be wrong to say that unit tests almost function like a kind of documentation.</p><p>After briefly touching on the benefits of unit tests and the perspective on unit tests, we can start writing our first unit test.</p><p>I use the xUnit library in my projects. Therefore, I will provide my examples using the xUnit library in my writings as well.</p><h3>xUnit Setup in the Project</h3><p>To serve as an example for project development with .NET, I will be creating a unit test project on the <a href="https://github.com/ozkanardil/dml_starterkit">DML Starter Kit</a> solution I shared on GitHub, plan to share various unit test scenarios step by step from simple to complex with real application examples.</p><p>You can review the details of the DML Starter Kit project at the end of the article.</p><p>I am adding a new unit test project named DmlStarterkit.Tests to the solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*QztEf9AkbwkyagfYz7LBvg.png" /><figcaption>A new xUnit project is added to the solution</figcaption></figure><p>After the project is added, a default test class will be created as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8eaxIixWieLWCSOCsJHSQ.png" /><figcaption>Default xunit test class</figcaption></figure><p>Before starting to write tests for the DML Starter Kit project, let’s take a look at the general structure of the test classes to be written with xUnit.</p><p>In the xUnit framework, each test is marked with the [Fact] attribute. [Fact] represents a unit test that tests a specific scenario. In the xUnit framework, there is a test runner, and this framework recognizes and executes the code block marked with [Fact] as a test.</p><p>In the class above, the Test1 class, which is created by default, is marked with [Fact] if you pay attention.</p><h3>xUnit Structure: Arrange-Act-Assert (AAA) Approach</h3><p>In short, AAA is an approach that helps organize the test method in a logical and understandable structure when writing unit tests.</p><h4>Arrange (Preparation Stage):</h4><p>We prepare the necessary objects and dependencies for the test.</p><p><strong>For example:</strong> We create Query, Handler, and Mock objects.</p><h4>Act (Eylem Aşaması):</h4><p>We run the method that needs to be tested.</p><p><strong>For example:</strong> calls like handler.Handle(query) are made.</p><h4>Assert (Verification Stage):</h4><p>We check the result (output). We verify whether the expected and actual values match.</p><p>Now, I will share a simple test code below and explain what I did within this code.</p><pre>[Theory]<br>[InlineData(2, 2, 4)]<br>[InlineData(3, 3, 6)]<br>public void SampleTheoryTest(int a, int b, int expected)<br>{<br>    Assert.Equal(expected, a + b);<br>}</pre><p><strong>[Theory]</strong> is used to run the same test method with multiple different datasets.</p><p><strong>[InlineData]</strong> provides input (parameter) for each test.</p><p>Here, we are running the same test method multiple times using different parameters. By increasing the <strong>[InlineData]</strong> attribute, it becomes possible to generate tests with different parameters.</p><pre>public void SampleTheoryTest(int a, int b, int expected)</pre><p>In this line, we see the signature of the SampleTheoryTest method. Our test method has 3 parameters. These parameters will take the values specified by [InlineData], and our test method will run.</p><p>For example; for [InlineData(3, 3, 6)], the parameters in our method will match as follows.</p><p>a = 3, <br>b = 3, <br>expected = 6.</p><p>To illustrate the topic, I didn’t apply the AAA approach here and directly performed a value check with Assert.</p><pre>Assert.Equal(expected, a + b);</pre><p>In this code block, the “Assert” statement possesses many built-in validation methods. In this example, Assert is used to compare two values. I called the Equal() method and tested whether the expected value is equal to the sum of the a and b parameters.</p><p>In this article, we introduced unit testing with xUnit and covered the basic concepts. We talked about the importance of unit tests in the software development process, why developers avoid writing unit tests, and the basic building blocks of xUnit. We also saw the Arrange-Act-Assert (AAA) approach and how we can diversify test scenarios with [Theory].</p><p>In the next article, we will start writing unit tests on a real project. We will write our tests step by step from easy to difficult, and we will use the <a href="https://github.com/ozkanardil/dml_starterkit">DML Starter Kit Framework</a>, which I published as open source, as a project.</p><p>See you in other articles.</p><p>☺️</p><p>⬇️ You can examine the libraries where I have grouped my articles.</p><ul><li><a href="https://medium.com/@ozkanardil/list/d6a4255c73bc">.NET Core Project Starter Kit</a></li><li><a href="https://medium.com/@ozkanardil/list/a28b2f3cec1c">.NET Core / C#</a></li><li><a href="https://medium.com/@ozkanardil/list/63f94e8ac235">Performance Comparisons</a></li><li><a href="https://medium.com/@ozkanardil/list/b2f261161e38">Design Patterns</a></li></ul><p>👏 <em>If you found the content useful, you can</em><strong><em> follow me</em></strong><em> and make me happy in this way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/0*In4jMFu6RDToG5LL.gif" /></figure><p>💬 If there is something I overlooked, you can share it in the comments or contact me on my profile.</p><p>💬 Let me know in the comment section what have I missed? Where I was wrong?</p><p>👨‍👦‍👦 You can also share this article with your friend. Argue a little on it. It is known that the truth is born in a dispute.</p><p>🙃 Stay determined, stay focused, and keep going.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a3e13541fcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost Your C# Projects with Relevance AI: Automate Tasks Like a Pro]]></title>
            <link>https://medium.com/@ozkanardil/boost-your-c-projects-with-relevance-ai-automate-tasks-like-a-pro-e247f7f06de7?source=rss-a94a2d59980f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e247f7f06de7</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[relevance]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[automation-tools]]></category>
            <dc:creator><![CDATA[Özkan ARDİL]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 14:57:17 GMT</pubDate>
            <atom:updated>2025-03-04T14:57:17.418Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to integrate AI agents with your C# applications to save time, automate workflows, and scale your business effortlessly.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*BT0RNWTwOd1kVTvhMrTyFw.png" /></figure><p>Take your software to the next level by integrating C# applications with Relevance AI, which allows you to automate repetitive tasks.</p><p>Are you tired of dealing with repetitive tasks in the business every day that consume time, effort, and resources without adding any value?</p><p>Despite hearing about the concept of automation, are you still searching for where and how to start?</p><p>Are you receiving feedback that the application written in C# is insufficient for AI and automation integration?</p><p>If you’ve encountered at least one of these questions, then you’re at the right place.</p><p>In this article we;</p><ul><li>Will create an AI agent for a simple task,</li><li>Will develop a tool for our AI agent according to the structure of the task,</li><li>Will ensure that the output is sent to the specified email address and trigger this process with our console application.</li></ul><p>When we talk about artificial intelligence integration, we are referring to a very broad concept. To give more substance to the ambitious statement of integrating software with artificial intelligence, it is beneficial to narrow our focus.</p><p>When I examined successful ventures, I observed that time was used efficiently, the work was scaled, and the processes were automated as much as possible.</p><p>Each automation is the key to bringing us one step closer to success and sustainability.</p><p>Automation, especially for repetitive tasks that consume time and energy and have relatively low added value, involves completing each task within a system.</p><p>It may seem a bit complex conceptually.</p><p>Let’s make this concrete.</p><p>Think of a scenario where you need to produce posts for X (formerly Twitter) daily for specific content. You have a website or an article, and this content needs to be shared on your X account.</p><p>We can say that it is almost impossible for the entrepreneur to deal with this task every day. Delegating this task to a third person or institution seems like the most logical solution.</p><p>However, this also brings along the need for resources. Additionally, extra effort is required for process management, such as explaining and controlling the work done, etc.</p><p>Of course, thanks to the opportunities developed by artificial intelligence, the requirement for the person assigned to a task to be human is eliminated when delegating a job.</p><p>Imagine you’re setting up a social media or content production team, and this team is entirely composed of AI agents.</p><p>Sounds nice, doesn’t it?</p><p>I think it’s a perfect situation.</p><p>First, let’s take a look at what an AI-powered agent is.</p><p>We can say that an AI-powered agent is a tool that works with customized AI algorithms trained or equipped for a very specific topic.</p><p>These agents can write articles, send emails, and produce content on specific topics, almost like an employee, repeating the tasks assigned to them by following certain procedural steps and completing the work.</p><p>Of course, every agent, while doing their job, needs tools suitable for the nature of the work to fulfill the task assigned with very clear job descriptions.</p><p>If these conditions are met, large tasks can be completed in a very short time with AI-supported agents.</p><p>By quickly structuring agent frameworks and integrating them with software, it becomes possible to automate repetitive tasks for businesses and entrepreneurs, delegating certain processes to agents.</p><blockquote>🚀 Ready to explore more AI-driven tools and automation solutions? Discover the latest innovations and resources at <a href="https://projxplorer.com/"><strong>ProjXplorer</strong></a> and supercharge your workflow today!</blockquote><p>Moreover, integrating the systems to be set up into our C# applications is extremely easy.</p><p>Then let’s get started.</p><h4>Requirements for AI-Powered Agent Integration</h4><p>Before diving into the topic, I will discuss the scenario, the basic requirements, and the software environment we will use to create the agent.</p><p>In our scenario, I will take on the task of producing content for the X platform for the articles sent to the social media management unit.</p><p>Our social media management department is responsible for creating content for social media from the blog articles sent to them daily. These processes are repeated for each published article. The analysis of the article, the preparation of social media content suitable for the article, sharing on social media accounts, and subsequently ensuring its follow-up can be listed as related sub-tasks.</p><p>Let’s assume and accept that a decision was made to automate the steps for generating draft content for the analysis of the article and the X account in order to increase efficiency in the business.</p><p>We will use the AI-powered Relevance AI application to complete this process. With Relevance AI, it is possible to create agents, design tools, and develop automation systems by modeling business processes.</p><p>The management of the agent designed with Relevance AI (in this article, I will only provide an example for triggering) will also be done through a simple .NET Core (C#) Console application, which will represent the business software.</p><p>Let’s continue.</p><h4>Relevance AI Membership</h4><p>First of all, we need to sign up on the Relevance AI website.</p><p>At the time I wrote this article, the Relevance AI application had a free version with 100 credits per day.</p><p>Since there might be changes in pricing policies in the future, it is necessary to check the Relevance AI website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0KmTk0BakuK935mIX1Rpw.png" /><figcaption>Relevance AI Pricing Plans</figcaption></figure><p>It is possible to join the site with just one click using your email address or Gmail integration.</p><p>After becoming a member, you will be asked to enter some information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*VXYUCyVXcFQBvrblWNHz4g.png" /></figure><h4>AI-Powered Agent Creation</h4><p>When the registration process is completed, we are directed to the homepage where agent templates with various features are listed. Here, it is possible to use a ready-made agent, but we also have the option to create a new agent from scratch according to our personalized needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PyDz5slHQ2ix_DefdwB82w.png" /><figcaption>Relevance AI dashboard</figcaption></figure><p>Without getting too sidetracked, since I want to jump straight into the application, I will create a new agent from scratch.</p><p>After clicking on the Agents link in the left menu, let’s create a new agent by clicking the “Build from Scratch” button.</p><p>On the opened screen, we are asked to enter a name and a brief description of the task for the new agent we will create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eu3uQVYu5OU1hA5zBbGNMg.png" /><figcaption>Create a new AI agent</figcaption></figure><p>After entering the necessary information, our agent is ready for duty.</p><p>However, the agent we created needs tools to perform the assigned task.</p><p>Among the tools, it is possible to select pre-prepared tools and update them according to our needs. However, I prefer to create a new toolkit for the sake of example.</p><h4>Creating a Tool Kit for the Agent</h4><p>Let’s create our toolkit for the agent to work. For this, first click on the “Tools” link in the left menu, then click on the “Build from scratch” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tClF-NZ6pBJeIOPwfH_2vA.png" /><figcaption>Create a AI tool from scratch</figcaption></figure><p>In the opened window, we are asked to choose a name for the tool we will create. Additionally, we need to create input for when the tool starts working. We will also plan the processes, referred to as steps, for the input processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6t-T5mI0jU5gHj-Yll7LTw.png" /><figcaption>AI tool description, inputs and steps</figcaption></figure><p>I’m naming our tool “X-post-generator.”</p><p>Our tool will generate clickbait post content for the X social platform on a given topic.</p><p>For this, we need to add at least one input field in text format to our tool to provide the topic as a parameter.</p><p>I am defining an input field named context with the text data type. It is possible to create additional input fields as needed.</p><p>We are asked to enter a name and a description showing the purpose of use for our input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7kUQeISGbnc2QfPXJVgzw.png" /><figcaption>Input for AI agent tool</figcaption></figure><p>After the title and description, it is also possible to enter a default value for context to be used in tests. I wrote “Relevance AI: Build teams of AI agents that deliver human-quality work” for the context as per our scenario.</p><p>We now have an agent that will work on our behalf, and our toolkit is almost ready for the agent to be able to do its job.</p><p>Now we will create the process for processing the inputs we send to our toolkit, and for this, we will add a new step to our tool.</p><h4>Adding a New Step to the Tool Kit</h4><p>We can add as many steps as we want to our toolkit. Each step contains features that enable us to perform a specific action. According to our scenario, we will prepare a clickbait X post content based on the context text we provide as input.</p><p>Therefore, it would be appropriate for us to use the LLM feature that will create a post according to the criteria we will determine by interpreting the context text.</p><p>For this, we click the add Step button as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mqw3qMO71hQVeZI-pHHv7w.png" /><figcaption>Add new step to AI tool</figcaption></figure><p>In the opened window, many steps we can use are listed. As seen in the image below, we select the LLM feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-Re9Yaoln42Hf6RkVueug.png" /><figcaption>Add LLM as step to the AI tool</figcaption></figure><p>We can optionally give each step a name. I prefer to leave it as LLM.<br>The prompt section is important.</p><p>We need to write the tasks that need to be done in detail in this section. It is critical to adhere to a specific structure to achieve the desired outcome.</p><p>In this step, we can also choose the GPT model we want to work with. We should not forget that the model we choose will also affect the credits used for each transaction.</p><p>Finally, there is the output section. In the image below, it is labeled as llm in lowercase letters. It is possible to use the output as input at different steps within the same toolkit. In the following steps, we will already do this. I am leaving the output name as llm as shown in the picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EoMRpSrcWDICgpPYa7G0eA.png" /><figcaption>LLM step features</figcaption></figure><p>Below, you see the prompt text I prepared. Adding posts whose style we like as examples to the prompt text will help us achieve more focused results.</p><p>The part colored light blue in the text, {{text}}, represents the outputs of the other steps within the same toolkit.</p><p>In this example, I used the output of the input named “context.”</p><p>I prefer to continue without adding an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CjJFtEL8_ErVlrKU3rQePQ.png" /><figcaption>Prompt for LLM step</figcaption></figure><p>To email the output, we will now add a new step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*6qFFALdyFiEgQr5TtCyW4Q.png" /><figcaption>Add new step</figcaption></figure><p>After adding new step, we can give a name, but in this example, I am not changing its name.</p><p>We are adding the address to which we want the email to be sent below, as shown. It is possible to add multiple email addresses.</p><p>We have the opportunity to add variability to the email subject by using parameters.</p><p>After preparing the email content as a template, we can move on to the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUMq5AD8QIhU0YN9DyDWTA.png" /><figcaption>Send email step configuration</figcaption></figure><h4>Testing the Flow</h4><p>The agent we created on Relevance AI is ready to work. We are testing our tool to ensure that the toolkit we created works correctly before integrating it with our C# software.</p><p>At the beginning of the article, while setting the input step, we had saved the text “Relevance AI: Build teams of AI agents that deliver human-quality work” as the default value.</p><p>Therefore, since our input is ready, we can run our toolkit for testing purposes after saving it.</p><p>After clicking the save button in the upper right corner of the screen, we click the “Run tool”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*fxaL58ZfrHKWEZ8VkgFl4A.png" /><figcaption>Test Relevance AI tool</figcaption></figure><p>This process can take 5–10 seconds depending on the steps the tool has and the operations performed in those steps. In more complex tools, this duration can be extended.</p><p>As a result of the process, we expect to see a message at the bottom of the page in the “Tool Output” section indicating that the email has been sent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*grezglHLDFO74IzGI8FWSQ.png" /><figcaption>Relevance AI tool test result</figcaption></figure><h4>Review of the Incoming Email</h4><p>Our tool is working. So, what about the incoming email?</p><p>We are logging into my Gmail account to check the inbox.</p><p>Boommm!</p><p>Our email has arrived.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gN4FD1x2k37_wO6u95hwKg.png" /></figure><p>Let’s take a look at the content of the email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxmkgkft11s1l7BpEVItGg.png" /></figure><p>Our tool is working successfully. The X content created with hashtags is directly in our email.</p><p>So, what was the cost of this transaction for us?</p><p>Now, let’s examine that.</p><p>As seen in the image below, the tool we created consumed 4 credits at once. We can see the consumed credit in the “Tool output” step. We can also see our remaining credit in the bottom right corner of the screen.</p><p>This means that on average, we can produce 25 X posts for free in one day. I think it’s quite a successful step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HjpGFEPj9mAA9Q2QZ6oTOQ.png" /><figcaption>Cost of custom Relevance AI tool as credit</figcaption></figure><h4>Usage of the Tool by the Agent and API Integration Settings</h4><p>Before starting the integration, there are a couple more settings we need to complete within the Relevance AI workflow. We have an agent and a tool.</p><p>However, we have not yet linked the two together.</p><p>To do this, we select the agent we created at the beginning of the article on Relevance AI.</p><p>Later, a chat screen will appear that resembles the ChatGPT screen and allows us to interact with the agent we created. Without doing anything, we click the “Edit Agent” button in the top right corner and reach the agent settings page.</p><p>When we click on the “Tools” link in the left-side menu, we see a list of tools that we can associate with the agent. From here, we can assign the desired tool to our agent by clicking the “Add” button next to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TGDuD4roZg2hTEnrL_Cp_A.png" /><figcaption>Assign tool to the agent</figcaption></figure><p>The agent is now ready to work. By logging into our Relevance AI account, we can assign new tasks to the agent through the chat screen.</p><p>However, we want to give the agent work programmatically by making a simple integration with our C# application.</p><p>Then let’s move on to the integration step.</p><p>We enter the agent settings page we created. At the bottom of the page, we click on the API link in the “Build your own triggers” section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqG6rN1FA-griAllSen4mA.png" /><figcaption>Relevance AI agent API trigger</figcaption></figure><p>A screen like the one below will appear. Here, we see the sections for the endpoint address where we can create a request and the token generation for authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*KqXX7nLhK2Q9fImaaxxlvA.png" /><figcaption>Relevance AI API integration</figcaption></figure><p>After creating the API token, it is now possible for us to reach the agent with our software.</p><blockquote>For more insights and tools to streamline your projects, check out <a href="https://projxplorer.com/">ProjXplorer</a>.</blockquote><h4>Integration of Our C# Application with Relevance AI</h4><p>It is possible to connect at every stage of the workflow we successfully created on Relevance AI. In this article, we will see how to trigger the workflow by simply interacting with the agent.</p><p>For this, we are creating a new .NET Core Console application.</p><p>We are adding the following code to our application.</p><pre>using System.Net.Http.Headers;<br><br>using (var httpClient = new HttpClient())<br>{<br>    using (var request = new HttpRequestMessage(new HttpMethod(&quot;POST&quot;), &quot;AGENT_LINK&quot;))<br>    {<br>        request.Headers.TryAddWithoutValidation(&quot;Authorization&quot;, &quot;API_KEY&quot;);<br><br>        request.Content = new StringContent(&quot;{\&quot;message\&quot;:{\&quot;role\&quot;:\&quot;user\&quot;,\&quot;content\&quot;:\&quot;CONTEXT\&quot;},\&quot;agent_id\&quot;:\&quot;5c8c43f3-9560-4b59-ad76-99c237308725\&quot;}&quot;);<br>        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(&quot;application/json&quot;);<br><br>        var response = await httpClient.SendAsync(request);<br>    }<br>}</pre><p>We need to replace the AGENT_LINK, API_KEY, and CONTEXT variables in this code with the values we obtained from the agent settings.</p><p>Now let me explain our code step by step.</p><pre>using System.Net.Http.Headers;</pre><ul><li>This imports the System.Net.Http.Headers namespace.</li><li>It is required to work with HTTP headers (like setting Content-Type, Authorization, etc.).</li></ul><pre>using (var httpClient = new HttpClient())</pre><ul><li><strong>HttpClient</strong> is a built-in class in .NET Core used to send HTTP requests and receive responses.</li><li>The using statement ensures the httpClient object is disposed of properly after use, freeing up resources.</li></ul><pre>using (var request = new HttpRequestMessage(new HttpMethod(&quot;POST&quot;), &quot;https://api-d7b62b.stack.tryrelevance.com/latest/agents/trigger&quot;))</pre><p>This initializes a new <strong>HTTP POST</strong> request to the specified URL.</p><pre>request.Headers.TryAddWithoutValidation(&quot;Authorization&quot;, &quot;33fddc1a17de-4b74-a8a1-677dceba373f:sk-NjY2NTYzYjctZmM0NS00ZTA2LTgzYTMtZmZmMTg3NDJjNTBl&quot;);</pre><ul><li><strong>TryAddWithoutValidation</strong> adds a custom header without validating the format.</li><li>This sets an Authorization header, typically used for API authentication.</li></ul><pre>var response = await httpClient.SendAsync(request);</pre><ul><li>This asynchronously sends the prepared <strong>POST</strong> request.</li><li>await is used to <strong>asynchronously</strong> wait for the response without blocking the main thread.</li><li>The response is stored in the response variable but <strong>not processed further</strong> in this code.</li></ul><p>When we run the application, we send a request to the Relevance AI workflow.</p><p>⬇️ You can examine the libraries where I have grouped my articles.</p><ul><li><a href="https://medium.com/@ozkanardil/list/d6a4255c73bc">.NET Core Project Starter Kit</a></li><li><a href="https://medium.com/@ozkanardil/list/a28b2f3cec1c">.NET Core / C#</a></li><li><a href="https://medium.com/@ozkanardil/list/b2f261161e38">Design Patterns</a></li></ul><p>👏 <em>If you found the content useful, you can</em><strong><em> follow me</em></strong><em> and make me happy in this way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/0*C-bcQ_uv9AkxiJTu.gif" /></figure><p>💬 If there is something I overlooked, you can share it in the comments or contact me on my profile.</p><p>💬 Let me know in the comment section what have I missed? Where I was wrong?</p><p>👨‍👦‍👦 You can also share this article with your friend. Argue a little on it. It is known that the truth is born in a dispute.</p><p>🙃 Stay determined, stay focused, and keep going.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e247f7f06de7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fluent API Explained: Simplify Object-Oriented Programming with Method Chaining]]></title>
            <link>https://medium.com/@ozkanardil/fluent-api-explained-simplify-object-oriented-programming-with-method-chaining-d81655d71bd5?source=rss-a94a2d59980f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d81655d71bd5</guid>
            <category><![CDATA[fluent-api]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[readers]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Özkan ARDİL]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 16:55:13 GMT</pubDate>
            <atom:updated>2024-12-08T16:55:13.605Z</atom:updated>
            <content:encoded><![CDATA[<h4>.NET Core Fluent API Implementation</h4><h4>FluentAPI is a design pattern that makes the code more readable and understandable. It allows method calls to be made sequentially using the chaining method. In this article, I will explain how to convert complex structures into code that is close to natural language using the Fluent API design pattern.</h4><p>To better understand the FluentAPI design pattern, it is necessary to first mention the chaining method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*SxLlDjiXBDzO-3YQwtEH2g.png" /></figure><h3>Chaining Method</h3><p>The chaining method is a technique used in object-oriented programming (OOP).</p><p>This method;</p><ul><li>Allows for consecutive method calls on an object to be chained together,</li><li>The method call typically returns the object itself,</li><li>Another method call can be immediately made on the returned object,</li><li>Thus, the code becomes more readable and shorter.</li></ul><p>To better understand the topic, let’s examine the code below.</p><pre>public class Calculator<br>{<br>    private int result = 0;<br><br>    public Calculator Add(int value)<br>    {<br>        result += value;<br>        return this;<br>    }<br><br>    public Calculator Subtract(int value)<br>    {<br>        result -= value;<br>        return this;<br>    }<br><br>    public Calculator Multiply(int value)<br>    {<br>        result *= value;<br>        return this;<br>    }<br><br>    public Calculator Divide(int value)<br>    {<br>        if (value != 0)<br>        {<br>            result /= value;<br>        }<br>        return this;<br>    }<br><br>    public int Result()<br>    {<br>        return result;<br>    }<br>}</pre><p>In this Calculator class, each mathematical operation method (Add, Subtract, Multiply, Divide) returns a Calculator object. In this way, these methods can be used in a chain.</p><p>Below, I demonstrated how to perform mathematical operations using the chaining method with the Calculator class.</p><pre>class Program<br>{<br>    static void Main(string[] args)<br>    {<br>        Calculator calc = new Calculator();<br>        int result = calc.Add(10).Subtract(5).Multiply(2).Divide(3).Result();<br>        Console.WriteLine(&quot;Result: &quot; + result);<br>    }<br>}</pre><p>In this example, the Add, Subtract, Multiply, and Divide methods have been called sequentially using the chaining method.</p><p>As a result, all operations were performed within a single expression, and the result was obtained using the Result method.</p><p>It is an approach supported by EntityFramework and LinQ.</p><h3>Advantages of the Chaining Method</h3><p><strong>Readability:</strong> The chaining method makes the code more readable and understandable. The code can be written as a series of method calls that express the operations step by step.</p><p><strong>Conciseness:</strong> The chaining method reduces the use of unnecessary temporary variables, making the code shorter and cleaner.</p><p><strong>Ease of Maintenance:</strong> More readable and understandable code simplifies debugging and maintenance processes.</p><p><strong>Natural Language Proximity:</strong> The chaining method allows the code to be written fluently like a natural language. This makes it easier for developers to understand and write the code.</p><p>After seeing the chaining method and its example usage, it will be easier to explain the Fluent API design pattern. The structural focus of the Fluent API design pattern is the chaining method.</p><h3>Fluent API and the Chaining Method</h3><p>The two concepts are often used interchangeably. However, Fluent API is used in a broader context as a design pattern.</p><p>For example;</p><p>The chaining method is used to configure a class’s methods, but with the Fluent API design pattern, we create more advanced structures by using different objects and entities.</p><p>The chaining method, in terms of scope, refers to the structure within a class, while the Fluent API generally refers to a more holistic structure used in configuration, definition, and querying processes.</p><p>To better understand the topic, I am sharing a simple example of a Fluent API structure below.</p><p>Here, we have a staff class, a configuration class, and a Program class that represents an application.</p><p>First, let’s take a look at the personnel class.</p><pre>public class Person<br>{<br>    public string FirstName { get; }<br>    public string LastName { get; }<br>    public int Age { get; }<br><br>    public Person(string firstName, string lastName, int age)<br>    {<br>        FirstName = firstName;<br>        LastName = lastName;<br>        Age = age;<br>    }<br><br>    public void Display()<br>    {<br>        Console.WriteLine($&quot;Name: {FirstName} {LastName}, Age: {Age}&quot;);<br>    }<br>}</pre><p>Our Personnel class is a class that has FirstName, LastName, and Age fields, along with a Display method.</p><p>Below is the personnel configuration class developed using the chaining method.</p><pre>public class PersonBuilder<br>{<br>    private string firstName;<br>    private string lastName;<br>    private int age;<br><br>    public PersonBuilder SetFirstName(string firstName)<br>    {<br>        this.firstName = firstName;<br>        return this;<br>    }<br><br>    public PersonBuilder SetLastName(string lastName)<br>    {<br>        this.lastName = lastName;<br>        return this;<br>    }<br><br>    public PersonBuilder SetAge(int age)<br>    {<br>        this.age = age;<br>        return this;<br>    }<br><br>    public Person Build()<br>    {<br>        return new Person(firstName, lastName, age);<br>    }<br>}</pre><p>Finally, you see the Program class representing our application that uses the staff classes.</p><pre>class Program<br>{<br>    static void Main(string[] args)<br>    {<br>        Person person = new PersonBuilder()<br>            .SetFirstName(&quot;John&quot;)<br>            .SetLastName(&quot;Doe&quot;)<br>            .SetAge(30)<br>            .Build();<br><br>        person.Display();<br>    }<br>}</pre><p>The Main method runs a structure created with the Fluent API design pattern.</p><p>The chaining method, on the other hand, is limited to the structure within the PersonBuilder class.</p><p>I think the difference between the chaining method and the Fluent API is clearly understood in this structure.</p><p>Let me explain the Main method line by line.</p><pre>Person person = new PersonBuilder()<br>            .SetFirstName(&quot;John&quot;)<br>            .SetLastName(&quot;Doe&quot;)<br>            .SetAge(30)<br>            .Build();<br><br>        person.Display();</pre><p>A new instance of the PersonBuilder class is created. PersonBuilder is a class used to construct a Person object step by step using the chaining method.</p><p>The SetFirstName method sets the FirstName (Name) property of the Person object.</p><p>The SetLastName method sets the LastName (Surname) property of the Person object.</p><p>The SetAge method sets the Age property of the Person object.</p><p>The Build method creates and returns the Person object configured by the PersonBuilder.</p><p>At this stage, while the existence of the chaining method has come to an end, it is still open to developing a Fluent API in terms of functionality. However, to keep the example simple and not complicate the code, I completed our method with the Display method.</p><h3>Fluent API Design Pattern Compatibility with SOLID Principles</h3><h4><strong>Single Responsibility Principle (SRP)</strong></h4><p><strong>Principle:</strong> A class (or module) should have only one reason to change, meaning it should have only one responsibility.</p><p><strong>Evaluation: </strong>Fluent API generally consists of a chain of small methods that perform specific functions. This encourages methods to focus on a single responsibility.</p><p>During the design of a Fluent API, it should be ensured that methods do not take on too much responsibility. For example, a Builder class should determine how the object is created, but it should not be concerned with the object’s behaviors.</p><h4><strong>Open/Closed Principle (OCP)</strong></h4><p><strong>Principle: </strong>Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.</p><p><strong>Evaluation: </strong>Fluent API provides an extensible design. We can extend the API by adding new methods, but we can leave the existing methods unchanged. When adding new functions, care should be taken not to disrupt the existing structure. Changing the usage of the API can affect existing users.</p><h4><strong>Liskov Substitution Principle (LSP)</strong></h4><p><strong>Principle: </strong>The subclasses of a class should be able to substitute for instances of the class they are derived from (subclasses should be usable in place of their superclass).</p><p><strong>Evaluation: </strong>Classes and methods created using a Fluent API should work seamlessly in derived classes as well. Subclass should not change the behavior expected by the superclass. Chained method calls should be consistent in subclasses as well.</p><h4><strong>Interface Segregation Principle (ISP)</strong></h4><p><strong>Principle: </strong>A class should not contain interfaces it does not use. Smaller, specialized interfaces should be created.</p><p><strong>Evaluation: </strong>Fluent API generally does not offer multiple functionalities in a single interface. Each method carries its own responsibility. When using interfaces in Fluent API design, care should be taken to ensure that these interfaces are not too large. Small and specific interfaces should be used.</p><h4><strong>Dependency Inversion Principle (DIP)</strong></h4><p><strong>Principle: </strong>High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.</p><p><strong>Evaluation: </strong>Fluent API design is generally based on abstractions, and this can help in inverting dependencies. When using a Fluent API, using interfaces or abstract classes instead of concrete classes facilitates the management of dependencies.</p><p>The use of Fluent API is a powerful method that enhances readability and flexibility in software design. This method makes the code more understandable and manageable, especially in complex object configurations and sequential operations. After understanding the fundamental features and advantages of Fluent API, examining how this approach aligns with the SOLID principles ensures that your software design is based on solid foundations.</p><p>SOLID principles encourage writing high-quality, flexible, and maintainable code in software development processes. When Fluent API is aligned with these principles, it becomes possible to develop more modular, extensible, and sustainable software. Ensuring the compatibility of Fluent API with SOLID principles provides significant advantages in both individual projects and large-scale software systems.</p><p>It should be noted that, like every design pattern and approach, Fluent API provides the greatest benefit when used in the correct context and appropriately. By integrating Fluent API and SOLID principles into your software development processes, you can create higher quality and more sustainable solutions.</p><h3>Conclusion</h3><p>The combination of Fluent API and SOLID principles offers a powerful synergy in modern software design. The readability and flexibility provided by Fluent API, along with the modularity and sustainability brought by the SOLID principles, enhance the success of software projects. By incorporating these approaches into your project, you can ensure a more effective and efficient development process for both yourself and your team. In the world of software, adopting and applying these principles is the key to developing high-quality software.</p><p>⬇️ You can examine the libraries where I have grouped my articles.</p><ul><li><a href="https://medium.com/@ozkanardil/list/a28b2f3cec1c">.NET Core / C#</a></li><li><a href="https://medium.com/@ozkanardil/list/d6a4255c73bc">.NET Core Project Starter Kit</a></li><li><a href="https://medium.com/@ozkanardil/list/b2f261161e38">Design Patterns</a></li></ul><p>👏 <em>If you found the content useful, you can</em><strong><em> follow me</em></strong><em> and make me happy in this way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/0*6mytq-0vV4E_TVq3.gif" /></figure><p>💬 If there is something I overlooked, you can share it in the comments or contact me on my profile.</p><p>💬 Let me know in the comment section what have I missed? Where I was wrong?</p><p>👨‍👦‍👦 You can also share this article with your friend. Argue a little on it. It is known that the truth is born in a dispute.</p><p>🙃 Stay determined, stay focused, and keep going.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d81655d71bd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Fluent Validation in .NET Core MediatR: A Guide with Source Code]]></title>
            <link>https://medium.com/@ozkanardil/the-secret-weapon-to-error-free-software-fluent-validation-unveiled-38f83986e400?source=rss-a94a2d59980f------2</link>
            <guid isPermaLink="false">https://medium.com/p/38f83986e400</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[fluent-validation]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[validation]]></category>
            <dc:creator><![CDATA[Özkan ARDİL]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 12:07:27 GMT</pubDate>
            <atom:updated>2024-11-15T13:49:53.249Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fluent Validation and MediatR Integration</h4><h3>How to Use Fluent Validation in .NET Core MediatR: A Guide with Source Code</h3><h4>Tired of validation errors plaguing your software projects? Meet Fluent Validation! This powerful library ensures your data is validated correctly and boosts your project’s reliability.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*0g85RctDuuJEovXV_mUbDw.png" /></figure><p>In this article, I will explain how Fluent Validation works and its alignment with SOLID principles.</p><p>In the software development process, each component and stage has great importance.</p><p>This process can generally be addressed in three main stages: input, processing, and output. Every step has its own crucial moments, and the validation procedure is one of the most important.</p><p>Input can be defined as data or information provided to the software system from outside. In this stage, data provided by users or other systems is collected. The quality of the input directly affects the overall performance and accuracy of the software.</p><p>Incorrect or incomplete data can lead to incorrect process results. Also, malicious data input can jeopardize system security, and the accuracy of the data provided by users affects user experience and satisfaction.</p><p>An effective validation process;</p><ul><li>increases the quality of the software,</li><li>ensures user satisfaction,</li><li>and increases the reliability of the system.</li></ul><p>Therefore, the importance of validation in the software flow should not be ignored and should be implemented meticulously at every stage.</p><p>I use Fluent Validation for input validation in my own projects.</p><p>I have also integrated the Fluent Validation library into my open source project.</p><p>You will find implementation and integration detailes below.</p><p>Simply visit <a href="https://github.com/ozkanardil/dml_starterkit">DmlStartterKit repo</a> to get the source code. The fluent-validation-integration branch in the repository contains the codes in the article.</p><p>Let’s dive into it.</p><h3>What is Fluent Validation</h3><p>Fluent Validation is a library used for .NET applications that allows validation processes to be performed in a more readable and maintainable way. It’s used especially in object validation processes and allows developer to define validation rules with the “fluent interface” method.</p><p>Thanks to this method, validation rules can be easily applied to objects and written in a readable way.</p><p>Here is an explanation of the basic features of Fluent Validation and how it is used.</p><h3>Basic Features of Fluent Validation</h3><p><strong>Easy to Use:</strong> Validation rules are defined in a simple and understandable way using lambda expressions.</p><p><strong>Modular Structure:</strong> Validation rules can be defined as separate classes and reused as needed.</p><p><strong>Extensibility:</strong> You can create your own custom validation rules and add them to Fluent Validation.</p><p>I will show you how easy the Fluent Validation integration is, how powerful it is to use, and how you can be implement it without disrupting the application structure.</p><h3>Step 1: Install Nuget packages</h3><p>To use Fluent validation, you must first add the <strong>FluentValidation </strong>and <strong>FluentValidation.DependecyInjectionExtensions</strong> libraries to your project.</p><p>You can easily do this with the NuGet package manager:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*GzfidpnMWiK2_uupbBCKjg.png" /><figcaption>Fluent Validation nuget packages</figcaption></figure><h3>Step 2: Behaviour classes</h3><p>You know that I used MediatR in the project. In this article, I will continue our topic without going into detail, assuming that you have knowledge about the MediatR structure.</p><p>I created the ValidationBehavior class so that the Fluent Validation script works in harmony with MediatR.</p><p>The ValidationBehavior class is a behavior class that allows the validation of incoming requests.</p><p>This class is integrated into the pipeline structure of MediatR, allowing validation processes to be performed before each request.</p><p>In this way, it checks whether the requests are valid or not and prevents erroneous operations.</p><p>Below you will find the code for the class.</p><pre>using FluentValidation;<br>using FluentValidation.Results;<br>using MediatR;<br><br>namespace DmlStarterkit.Application.Behaviors;<br><br>public class ValidationBehavior&lt;TRequest, TResponse&gt; : IPipelineBehavior&lt;TRequest, TResponse&gt;<br>    where TRequest : class, IRequest&lt;TResponse&gt;<br>    where TResponse : class<br>{<br>    private readonly bool _hasValidators;<br>    private readonly IEnumerable&lt;IValidator&lt;TRequest&gt;&gt; _validators;<br><br>    public ValidationBehavior(IEnumerable&lt;IValidator&lt;TRequest&gt;&gt; validators)<br>    {<br>        _validators = validators;<br>        _hasValidators = _validators.Any();<br>    }<br><br>    public async Task&lt;TResponse&gt; Handle(TRequest request, RequestHandlerDelegate&lt;TResponse&gt; next, CancellationToken cancellationToken)<br>    {<br>        if (!_hasValidators)<br>            return await next();<br><br>        var context = new ValidationContext&lt;TRequest&gt;(request);<br>        ValidationResult[] validationResults =<br>                    await Task.WhenAll(_validators.Select(v =&gt;<br>                           v.ValidateAsync(context, cancellationToken)));<br><br>        List&lt;ValidationFailure&gt; failures =<br>                    validationResults.SelectMany(r =&gt; r.Errors)<br>                          .Where(f =&gt; f != null).ToList();<br><br>        if (!failures.Any())<br>            return await next();<br><br>        throw new Exception(failures[0].ErrorMessage);<br>    }<br><br>}</pre><p>Now let me explain the class step by step.</p><pre>using FluentValidation;<br>using FluentValidation.Results;<br>using MediatR;<br><br>namespace DmlStarterkit.Application.Behaviors;</pre><p>Necessary libraries are included.</p><p>FluentValidation is used for validation operations, and MediatR is used for request and response processing.</p><pre>public class ValidationBehavior&lt;TRequest, TResponse&gt; : IPipelineBehavior&lt;TRequest, TResponse&gt;<br>    where TRequest : class, IRequest&lt;TResponse&gt;<br>    where TResponse : class<br>{</pre><p>This class works with generic types (TRequest, TResponse) and implements the IPipelineBehavior&lt;TRequest, TResponse&gt; interface.</p><p>TRequest type must be classes that implement the IRequest&lt;TResponse&gt; interface.</p><pre>    private readonly bool _hasValidators;<br>    private readonly IEnumerable&lt;IValidator&lt;TRequest&gt;&gt; _validators;</pre><p>_hasValidators: Used to check if there is a validator.</p><p>_validators: List of validators of type IValidator&lt;TRequest&gt;.</p><pre>    public ValidationBehavior(IEnumerable&lt;IValidator&lt;TRequest&gt;&gt; validators)<br>    {<br>        _validators = validators;<br>        _hasValidators = _validators.Any();<br>    }</pre><p>The constructor method takes the validators and assigns them to the _validators field in the class.</p><p>It also stores whether the validators exist or not in the _hasValidators field.</p><pre>    public async Task&lt;TResponse&gt; Handle(TRequest request, RequestHandlerDelegate&lt;TResponse&gt; next, CancellationToken cancellationToken)<br>    {<br>        if (!_hasValidators)<br>            return await next();</pre><p>The handle method is called during the processing of requests in the MediatR pipeline.</p><p>If there is no validator (_hasValidators is false), the processing continues and the next handler (next()) is called.</p><pre>        var context = new ValidationContext&lt;TRequest&gt;(request);<br>        ValidationResult[] validationResults =<br>                    await Task.WhenAll(_validators.Select(v =&gt;<br>                           v.ValidateAsync(context, cancellationToken)));</pre><p>ValidationContext&lt;TRequest&gt; object creates the context for the validation process.</p><p>With the ValidateAsync method, all validators are run simultaneously and the results (validationResults) are collected.</p><pre>        List&lt;ValidationFailure&gt; failures =<br>                    validationResults.SelectMany(r =&gt; r.Errors)<br>                          .Where(f =&gt; f != null).ToList();</pre><p>From all validationResults, errors are collected and non-null ones are added to the failures list.</p><pre>        if (!failures.Any())<br>            return await next();</pre><p>If there are no errors (the failures list is empty), processing continues and the next handler is called.</p><pre>        throw new Exception(failures[0].ErrorMessage);<br>    }<br>}</pre><p>If there is an error (the failures list is full), an exception is thrown with the first error message, and the process is stopped.</p><p>In fact, the Fluent Validation library returns all errors in a list when an error occurs. However, I have posted my code in a way that it returns the first error every time for user experience in the application.</p><h3>Step 3: Registering ValidationBehavior Class</h3><p>The ValidatorBehavior class requires registration in order to be used within the MediatR lifecycle.</p><p>With the following codes, we register our ValidatorBehavior class in the Dependency Injection container.</p><pre>services.AddScoped(typeof(IPipelineBehavior&lt;,&gt;), typeof(ValidationBehavior&lt;,&gt;));<br>services.AddValidatorsFromAssemblies(AppDomain.CurrentDomain.GetAssemblies());</pre><p>Now let’s explain in detail what this code does.</p><p>First line associates the ValidationBehavior class with the IPipelineBehavior interface and adds it to the Dependency Injection container so that it has a scoped lifecycle for all requests of this type.</p><h4>Detailed description of the first line:</h4><p>The <strong>services.AddScoped(…) </strong>method registers objects of the given type with a scoped lifecycle.</p><p>The scoped lifecycle creates an instance for each HTTP request and uses the same instance throughout the request.</p><p>The <strong>typeof(IPipelineBehavior&lt;,&gt;)</strong> statement specifies the generic IPipelineBehavior interface. This interface defines behaviors in the MediatR pipeline.</p><p>The <strong>typeof(ValidationBehavior&lt;,&gt;)</strong> statement specifies the ValidationBehavior class. This class implements the IPipelineBehavior interface and provides validation of requests.</p><p>Second line finds FluentValidation validators from all available assemblies and adds them to the Dependency Injection container.</p><h4>Detailed description of the second line:</h4><p>The <strong>services.AddValidatorsFromAssemblies(…)</strong> method automatically finds and registers classes that implement the IValidator interface from the specified assemblies.</p><p>The <strong>AppDomain.CurrentDomain.GetAssemblies()</strong> statement retrieves all assemblies in the domain where the application is running.</p><p>This returns a collection containing all the assemblies currently loaded in the application.</p><p>After registering the ValidatorBehavior class, you can now create validation classes.</p><h3>Step 4: Creating a Validator Class</h3><p>Below I shared the GetLoginQuery class that I use in the login process.</p><pre>    public class GetLoginQuery : IRequest&lt;IRequestDataResult&lt;LoginResponse&gt;&gt;<br>    {<br>        public string Email { get; set; }<br>        public string Password { get; set; }<br>    }</pre><p>This class contains two fields named <strong>Email </strong>and <strong>Password</strong>. You will complete the process by creating the class that contains our validation rules for these fields.</p><pre>namespace DmlStarterkit.Application.Features.Auth.Queries<br>{<br>    public class GetLoginQueryValidator : AbstractValidator&lt;GetLoginQuery&gt;<br>    {<br>        public GetLoginQueryValidator()<br>        {<br>            RuleFor(x =&gt; x.Email)<br>                .NotEmpty().WithMessage(&quot;E-mail address is required&quot;)<br>                .EmailAddress().WithMessage(&quot;Not a valid e-mail address&quot;);<br><br>            RuleFor(x =&gt; x.Password)<br>                .NotEmpty().WithMessage(&quot;{PropertyName} is empty&quot;)<br>                .Length(4, 8).WithMessage(&quot;Password must be at least 4 and maximum 8 characters&quot;);<br>        }<br>    }<br>}</pre><p>The GetLoginQueryValidator class defines the validation rules for the query named GetLoginQuery using Fluent Validation. This class is derived from the AbstractValidator&lt;GetLoginQuery&gt; class and contains the rules required to perform validation operations on the GetLoginQuery object.</p><h4>Description of the first rule</h4><pre>RuleFor(x =&gt; x.Email)<br>    .NotEmpty().WithMessage(&quot;E-mail address is required&quot;)<br>    .EmailAddress().WithMessage(&quot;Not a valid e-mail address&quot;);</pre><p><strong>NotEmpty():</strong> Checks if the Email field is empty. If the Email field is empty, it returns the message “E-mail address is required”.</p><p><strong>EmailAddress():</strong> Checks if the Email field is in a valid email address format. If it is not a valid email address, it returns the message “Not a valid e-mail address”.</p><pre>RuleFor(x =&gt; x.Password)<br>    .NotEmpty().WithMessage(&quot;{PropertyName} is empty&quot;)<br>    .Length(4, 8).WithMessage(&quot;Password must be at least 4 and maximum 8 characters&quot;);</pre><p><strong>NotEmpty(): </strong>Checks if the Password field is empty. If the Password field is empty, it returns the message “{PropertyName} is empty”. The {PropertyName} expression automatically adds the name of the property on which the error occurred (Password in this case) to the error message.</p><p><strong>Length(4, 8):</strong> Checks the length of the Password field. It requires the password to be at least 4 characters and at most 8 characters. If it does not meet these conditions, it returns the message “Password must be at least 4 and maximum 8 characters”.</p><p>It is possible to create many validation rules with Fluent Validation. You can visit <a href="https://docs.fluentvalidation.net/en/latest/rulesets.html">this page</a> for other rules and their detailed applications.</p><h3>Testing invalid data</h3><p>Now let’s test the validation rule of the Login endpoint.</p><p>In the example below, we enter an invalid email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvwRW8C5cpAPnZvLuTdj4g.png" /></figure><p>The error message that occurs as a result of verification is returned as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*VxBQvWGpzR0X9SLUhuY93A.png" /></figure><p>In my previous article, I explained how I developed the MiddleWare structure that catches application errors and returns a standard response model. If you want to get detailed information, you can take a look at the article below.</p><p><a href="https://medium.com/@ozkanardil/custom-middleware-in-net-core-to-handle-exceptions-globally-9558073d4b89">Custom Middleware in .NET Core to Handle Exceptions Globally.</a></p><p>We have seen how the Fluent Validation library is integrated into the project in 3 steps. Now I would like to take a brief look at the Fluent Validation structure in terms of SOLID principles.</p><p>Let’s keep reading.</p><h3>Fluent Validations and SOLID Principles in C#</h3><p>The Fluent Validation application is designed in accordance with the SOLID principles in software development. SOLID principles aim to provide flexibility, extensibility, and ease of maintenance in software design. Now, let’s evaluate the Fluent Validation application in terms of these principles:</p><h4>Single Responsibility Principle (SRP)</h4><p><strong>Principle:</strong> Each class should have only one responsibility, and this responsibility should be related to the reason for the existence of the class.</p><p><strong>Evaluation:</strong> Fluent validation ensures that each validator class is responsible for defining the validation rules of only a specific model. For example, the GetLoginQueryValidator class contains only the validation rules of the GetLoginQuery model. This fully complies with the SRP and ensures that each class has a single responsibility.</p><h4>Open/Closed Principle (OCP)</h4><p><strong>Principle:</strong> Software entities (classes, modules, functions) should be open to extension but closed to modification.</p><p><strong>Evaluation:</strong> Fluent validation allows adding new validation rules. You can add new validator classes without changing existing validator classes. For example, it is possible to add new rules to the GetLoginQueryValidator class or create a new validator for another class. This is in line with OCP because you can extend the system by adding new validators instead of changing existing classes.</p><h4>Liskov Substitution Principle (LSP)</h4><p><strong>Principle:</strong> Derived class objects should be usable instead of base class objects, i.e., objects of a class’s subclass should be usable instead of objects of its own class.</p><p><strong>Evaluation:</strong> Fluent Validation uses the IValidator&lt;T&gt; interface, and every validator implements this interface. This allows validators to be used polymorphically. For example, any IValidator&lt;GetLoginQuery&gt; object can be replaced with a GetLoginQueryValidator. This complies with LSP because validator objects can be replaced with their interfaces or base classes.</p><h4>Interface Segregation Principle (ISP)</h4><p><strong>Principle:</strong> A class should not be forced to implement an interface that has methods it does not use. Small, specific interfaces are better than large, generic interfaces.</p><p><strong>Evaluation:</strong> Fluent Validation provides specific validation interfaces for each model. The IValidator&lt;T&gt; interface defines only the validation rules for a specific model and does not contain unnecessary methods. This is in line with ISP because interfaces are small and specific, containing only necessary methods.</p><h4>Dependency Inversion Principle (DIP)</h4><p><strong>Principle:</strong> High-level modules should not depend on low-level modules. Both types should depend on abstractions. Also, abstractions should not depend on details; details should depend on abstractions.</p><p><strong>Evaluation:</strong> Fluent validation encourages dependencies to be provided through abstractions. The IValidator&lt;T&gt; interface abstracts the validation rules, and validator classes implement this interface. Also, injecting validators using dependency injection (DI) is a DIP-compliant approach. Validators are injected and used through interfaces, preventing high-level modules from being dependent on low-level details.</p><p>You can also access the source code from the<a href="https://github.com/ozkanardil/dml_starterkit"> DmlStartterKit repo</a>.</p><p>The fluent-validation-integration branch in the repository contains the codes in the article.</p><h3>Why You Should Use This Project</h3><p>If you’re looking to start a new project but don’t want to spend hours setting up the basics, this template is for you.</p><p>It’s designed to be a quick start — something you can clone and get up and running in about 10 minutes.</p><p>The architecture is clean, the code is organized, and the features are what you’d expect in a robust, modern WebAPI.</p><h3>Embracing Open Source and Community Collaboration</h3><p>One of the things I love most about being a developer is the sense of community. There’s something incredibly rewarding about sharing knowledge and tools with others.</p><p>This project is available on <a href="https://github.com/ozkanardil/dml_starterkit">GitHub</a>, and I welcome anyone to use it whether it’s for educational purposes, personal projects, or <strong>even commercial applications.</strong></p><h3>💡Want Me to Handle It For You?</h3><p>You can develop the project yourself, or if this all sounds like a lot of work, you’d rather focus on someone to help you.</p><p>I am <a href="https://linktr.ee/ozkanardil">Özkan Ardil</a>, Software Developer, Sole entrepreneur and writer.</p><p>You can contact with me via <a href="https://docs.google.com/forms/d/1MSDClB3hrbNBQlTRn_DUo83p7bWEj5aAl0fb0nUzCzw/edit">this contact form</a>.</p><p>I look forward to hearing from you.</p><p>⬇️ You can examine the libraries where I have grouped my articles.</p><ul><li><a href="https://medium.com/@ozkanardil/list/d6a4255c73bc">.NET Core Project Starter Kit</a></li><li><a href="https://medium.com/@ozkanardil/list/b2f261161e38">Design Patterns</a></li><li><a href="https://medium.com/@ozkanardil/list/da04dd09cb75">Tutorials</a></li><li><a href="https://medium.com/@ozkanardil/list/63f94e8ac235">Performance Comparisons</a></li></ul><p>👏 <em>If you found the content useful, you can</em><strong><em> follow me</em></strong><em> and make me happy in this way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/0*i29xey7nIguw6OPP.gif" /></figure><p>💬 If there is something I overlooked, you can share it in the comments or contact me on my profile.</p><p>💬 Let me know in the comment section what have I missed? Where I was wrong?</p><p>👨‍👦‍👦 You can also share this article with your friend. Argue a little on it. It is known that the truth is born in a dispute.</p><p>🙃 Stay determined, stay focused, and keep going.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38f83986e400" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How This Free Tool Removed My Big Pain]]></title>
            <link>https://medium.com/@ozkanardil/how-this-free-tool-removed-my-big-pain-89520e5d2572?source=rss-a94a2d59980f------2</link>
            <guid isPermaLink="false">https://medium.com/p/89520e5d2572</guid>
            <category><![CDATA[content-writing]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[links]]></category>
            <category><![CDATA[writer]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[Özkan ARDİL]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 11:35:19 GMT</pubDate>
            <atom:updated>2024-11-03T11:35:19.407Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Free Tool For Writers and Content Creators</h4><h4>Link Map came to my rescue when I was struggling with my website’s internal link structure. This article explores how this innovative, free tool helped me visualize link relationships, identify missing links, and optimize my site’s SEO.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Ua2c2MJZnEIUF-i9EHuDOA.png" /></figure><p>Read on to find out how Link Map can improve your website’s performance and user experience.</p><p>Today, I am writing an article on a different topic than software development. A problem I have been experiencing for a long time has been solved. I wanted to share it with you.</p><p>I tried many ways to solve this problem.</p><p>I created Excel spreadsheets. I updated each article with the link I gave to the article in its content.</p><p>I wrote new articles.</p><p>Over time, my spreadsheet lost its current status. Sometimes I spent hours fixing it. Sometimes I just left it there.</p><p>It worked when the number of articles was low. But as the number of articles increased, I started to lose track. Even if I updated my spreadsheet, I couldn’t visualize it in my head.</p><p>After a while, I stopped using my spreadsheet. However, this problem continued to occur every time I wrote a new article. I couldn’t keep track of which article I gave a link to.</p><p>Until I found this free site.</p><p>This site solved a problem that was important to me. I thought it would be useful for thousands of writers who produce content in different areas like Medium, so I wanted to share it.</p><p>Before going into detail, I immediately visualized the backlink relationships of my articles. The result really scared me. What do you think?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zaN5z3H8Tnxj3DuwTLl3eQ.png" /><figcaption>Haha! My horrible link structure</figcaption></figure><p>Of course, I immediately rolled up my sleeves and started updating my article links. My goal is to create a structure similar to the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*uDdNdc9SlAEFVtNY4DJ1gQ.png" /><figcaption>Good structed links.</figcaption></figure><p>Let’s get to the details of the site.</p><p>Site is <a href="https://link-map.net/,">Link Map.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9K8bb2DmoPmUY6_D-8d-g.png" /><figcaption>Main page of the Link-Map</figcaption></figure><p>It is extremely easy to use.</p><p>It has a simple interface.</p><p>I have explained the use of the site step by step below.</p><p>Let’s continue…</p><h3>Membership to the Link Map</h3><p>You can become a member of the site with your email, name, and surname.</p><p>As I said, the site is free.</p><p>This is the best part.</p><p>After you specify your e-mail and password, you can log in directly to the site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*UVtSf41NTjQ2eOfbG2ET0A.png" /><figcaption>Sign Up page of the Link Map</figcaption></figure><p>When you log in to the site, you will be greeted by a welcome screen like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Qx2-f1LzaaT8-ZWZENlag.png" /><figcaption>Dashboard of the Link Map</figcaption></figure><p>What you need to do is enter the articles you want to visualize into the system.</p><p>To do this, you can click on the “My Articles” link in the menu on the left or the “Details” link in the articles section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rz4eU9yD-OsPWpXD5Nx4qw.png" /><figcaption>Go to articles screen of the Link Map</figcaption></figure><p>On the page that opens, all the articles you have entered will be listed.</p><p>New members will see a blank page, of course.</p><p>To add a new article, click on the “Add Article” button in the upper right corner.</p><p>A modal screen like the one below will open. On this screen, you must enter the title and link of the article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YCGqMWgoipLVwd-3uJ9yvA.png" /><figcaption>Create a new article or content</figcaption></figure><p>After entering your articles into the system, you now create create the links.</p><p>This is also extremely simple.</p><p>The number of backlinks contained in each article is shown in the “Link count” column as marked below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gztwUHQW3rPYHFWA68Liww.png" /><figcaption>Backlink numbers of the articles</figcaption></figure><p>When you click on the “Link Count” link of the article, a screen like the one below opens.</p><p>Click on the “Add Link” button at the top right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcjI3xkud-Cb0OhEf9B58g.png" /></figure><p>Then select the article you want to link to and click the save button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKvbnruJr6Y4juhbd9RzOA.png" /><figcaption>Select an article from the dropdown list.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQRlmVqRSTxEdPCBMXswrQ.png" /><figcaption>Click on the Save button to create a new link to the selected article</figcaption></figure><p>Congrats! You have added a link to your article.</p><p>After entering all the articles and the links they contain, you can now move on to the visualization phase.</p><h3>Create a Graph to Visualize Article Link Structure</h3><p>To do this, you have to access the graph creation page using the links I marked in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_jWZx5NcfUyi4ZypygUmw.png" /></figure><p>On the screen that opens, click on the “Create Graph” button at the top right to create a new graph.</p><p>A modal screen like the one below opens.</p><p>Give a name to your newly created graph image.</p><p>It is also possible to choose to whether our articles should be displayed with their titles or ID numbers.</p><p>Then, click on the “Create” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZMfw_hKQL5t5_PFDPx2Zg.png" /><figcaption>Create a new graph using Link Map</figcaption></figure><p>You can see the graphs on the list.</p><p>Open your graph by clicking on the name of the graph record.</p><p>If the image is too large, you can see that it extends beyond the screen when it is first opened as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AhLvPbxZobq2Z_aJgAXxfw.png" /></figure><p>I hope, this problem will probably be fixed soon.</p><p>When you hover over the image with the mouse and do Ctrl+zoomout, you can resize the image as we want.</p><p>The first graph I created is shown below.</p><p>I quickly realized that I needed to analyze these connections in depth and make the necessary updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXxWriUUFivDsW82zg8-CA.png" /></figure><p>Now let’s create a graph using the article ID values.</p><p>To do this, click on the “My Graphs” link from the left menu and go to the graph listing page.</p><p>Click on the “Create Graph” button and after entering the graph name on the screen that opens, select the “With ID” option as shown in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*4m-pR5dS_xOBfr_aHqfWog.png" /><figcaption>Creating a new graph with ID option.</figcaption></figure><p>The new graph created is shown below.</p><p>It is also possible to see the full title of the article when you mouse over the article box.</p><p>For more complex graphs, the ID option seems more logical to me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_qlSO-pCbCHLD1BgfS0Fg.png" /><figcaption>It is possible to see the article title when user hovers on the marticle ID box.</figcaption></figure><p>To print the created graph object, you can take a screenshot or print it directly as a PDF by pressing Ctrl+P.</p><h3>A Facility for Medium Articles</h3><p>There is a feature added for Medium articles.</p><p>It is possible to automatically pull links from Medium articles.</p><p>Let me explain how this works.</p><p>On articles list screen, click on the “Link Count” link of an article. If this article is a Medium article, the “Crawl Links” button appears in the upper right corner.</p><p>Below, you can see a Medium article of mine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BljCbBwbYFJxgWJaE6aOxA.png" /><figcaption>Crawl Links button is shown if the selected article is a Medium article</figcaption></figure><p>This article contains links to a total of 3 Medium articles.</p><p>In our scenario, there are 4 links on my link-map page.</p><p>Over time, I have updated my article but not here.</p><p>Now, instead of manually updating them one by one, Link-map will do the hard work for us.</p><p>To do this, click on the “Crawl Links” button. A list like the one below is created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7KwJOGP1YOy0oID8UmBjyg.png" /><figcaption>Crawled links of a sample article</figcaption></figure><p>The <strong>red cross</strong> here shows links that are not in the article but have already been entered into the Link-map system.</p><p>We can delete these links by clicking the cross sign.</p><p>The <strong>OK</strong> sign shows that the link in the article is also registered in the Link-map system.</p><p>We don’t need to do anything for this.</p><p>The <strong>plus sign</strong> shows links that are in the article but not in the link-map system.</p><p>We save the link to the linkmap by clicking the plus sign.</p><p>Thus, our linkmap and Medium article links are synchronized.</p><p>Then it’s time to organize our links…</p><p>Click <a href="https://link-map.net/">here</a> to go to the Link-Map.</p><p>👏 <em>If you found the content useful, you can</em><strong><em> follow me</em></strong><em> and make me happy in this way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/0*iNUSIi49v8fnXOqW.gif" /></figure><p>💬 If there is something I overlooked, you can share it in the comments or contact me on my profile.</p><p>💬 Let me know in the comment section what have I missed? Where I was wrong?</p><p>👨‍👦‍👦 You can also share this article with your friend. Argue a little on it. It is known that the truth is born in a dispute.</p><p>🙃 Stay determined, stay focused, and keep going.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89520e5d2572" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Middleware in .NET Core to Handle Exceptions Globally.]]></title>
            <link>https://medium.com/@ozkanardil/custom-middleware-in-net-core-to-handle-exceptions-globally-9558073d4b89?source=rss-a94a2d59980f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9558073d4b89</guid>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Özkan ARDİL]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 11:59:00 GMT</pubDate>
            <atom:updated>2024-10-27T12:15:40.448Z</atom:updated>
            <content:encoded><![CDATA[<h4>Custom middleware in .NET Core</h4><h3>Custom Middleware in .NET Core to Handle Exceptions Globally.</h3><p>In .NET Core applications, custom middleware for global exception handling plays a crucial role in delivering consistent and user-centric error responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*i1drWR0Ab4k7or3HYL7hdQ.png" /></figure><p>As you know, I recently shared my DML Starter Kit project as open source.</p><p>A few friends who use my project reached out to me. This made me incredibly happy. I have made some improvements to the DML Starter Kit project, which I am currently using in my SaaS project.</p><p>On this beautiful Saturday, I integrated the simple but effective “custom middleware” structure I wrote for “global exception handling” into the project.</p><p>In this way, it is possible to catch unexpected errors centrally and return a response with the standard data model. Before looking at the code in detail, I would like to talk about the importance of this topic.</p><h3>Why I Implemented a Custom Middleware for Global Exception Handling in my .NET Core Application?</h3><p>In any software application, effective error handling is essential for maintaining robust and user-friendly systems. When an application encounters an error, it can either crash, display vague messages, or return structured, helpful feedback to clients.</p><p>In .NET Core applications, custom middleware for global exception handling plays a crucial role in delivering consistent and user-centric error responses.</p><p>Handling exceptions in individual controllers or services can become complex and difficult to maintain, especially in large applications with numerous endpoints. By implementing custom middleware for global exception handling, we centralize the error management logic in one place. This middleware will ensure that any unhandled exception, regardless of where it originated in the application, is caught and managed in a structured manner.</p><p>Without centralized handling, each controller action or service might return different error messages or HTTP status codes, leading to inconsistent client experiences. By defining a custom middleware, we ensure that all error responses follow the same structure, making it easier for clients to understand and handle them. For example, the middleware can return a JSON response with specific fields like success, message, and status, which makes error handling predictable and standardized across the application.</p><p>After touching on the importance of the topic, let’s now examine the code together.</p><p>Frankly, creating middleware with .NET Core is extremely simple. The process is completed by creating a class and then registering the class we created in the .NET Core project.</p><p>To explain this with a better example, when an unexpected error occurs in the project before writing custom middleware, the application throws an error, and the resulting response looks like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYTJtOWdxANdMI5sVdGHRg.png" /><figcaption>The response of the unhandled exception thrown within project.</figcaption></figure><h3>Step 1: Creating Custom Middleware Class for Exception Handling</h3><p>Below you see a class of about 40 lines.</p><pre>using Newtonsoft.Json;<br>using System.Net;<br>using Microsoft.AspNetCore.Http;<br>using DmlStarterkit.Infrastructure.Errors.Models;<br><br>namespace DmlStarterkit.Infrastructure.Errors.Middleware<br>{<br>    public class ExceptionMiddleware : IMiddleware<br>    {<br>        public async Task InvokeAsync(HttpContext context, RequestDelegate next)<br>        {<br>            try<br>            {<br>                await next(context);<br>            }<br>            catch (Exception exception)<br>            {<br>             <br>                var errorResult = new ErrorResult<br>                {<br>                    Success = false,<br>                    Message = exception.Message,<br>                };<br><br>                var response = context.Response;<br>                if (!response.HasStarted)<br>                {<br>                    response.ContentType = &quot;application/json&quot;;<br>                    response.StatusCode = (int)HttpStatusCode.BadRequest;<br>                    await response.WriteAsync(JsonConvert.SerializeObject(errorResult));<br>                }<br>              <br>            }<br>        }<br>    }<br>}</pre><p>Now let me explain step by step how I wrote this code.</p><h4>1. Class Definition</h4><pre>public class ExceptionMiddleware : IMiddleware</pre><p>The class ExceptionMiddleware implements the IMiddleware interface, which is used to define a reusable middleware component in .NET Core.</p><p>This middleware intercepts the HTTP request pipeline to handle any exceptions that may occur during the request processing.</p><h4>2. InvokeAsync Method</h4><pre>public async Task InvokeAsync(HttpContext context, RequestDelegate next)</pre><p>The invokeAsync method is required by IMiddleware and is the core method that will be called for each HTTP request.</p><p>It takes two parameters:</p><ul><li>HttpContext context: represents the current HTTP context, which holds all the information about the request and response.</li><li>RequestDelegate next: A delegate that represents the next middleware in the pipeline, to which the request is passed if no exception occurs.</li></ul><h4>3. <strong>Try-Catch Block for Exception Handling</strong></h4><pre>try<br>{<br>    await next(context);<br>}<br>catch (Exception exception)<br>{<br>    // Exception handling code<br>}</pre><p>The try block invokes the next middleware in the pipeline by calling await next(context).</p><p>If no exception occurs, the request proceeds as normal.</p><p>If an exception is thrown, it is caught by the catch block.</p><h4>4. <strong>Creating an Error Result Object</strong></h4><pre>var errorResult = new ErrorResult<br>{<br>    Success = false,<br>    Message = exception.Message,<br>};</pre><p>When an exception is caught, an instance of ErrorResult is created.</p><p>ErrorResult presumably is a custom class designed to structure the error response, typically containing:</p><ul><li>Success: A boolean indicating whether the request was successful. Here, it is set to false.</li><li>Message: Contains the exception’s message, providing details about the error.</li></ul><p>You can review the article below to get more detailed information about using the standard response model.</p><p><a href="https://medium.com/@ozkanardil/why-standardized-response-structures-are-essential-for-high-quality-c-projects-e4f66d04a11d">Why Standardized Response Structures Are Essential for High-Quality C# Projects</a></p><h4>5. Response Handling</h4><pre>var response = context.Response;<br>if (!response.HasStarted)<br>{<br>    response.ContentType = &quot;application/json&quot;;<br>    response.StatusCode = (int)HttpStatusCode.BadRequest;<br>    await response.WriteAsync(JsonConvert.SerializeObject(errorResult));<br>}</pre><p>context.Response is used to prepare the HTTP response to send back to the client.</p><p>if (!response.HasStarted) checks if the response has already been sent, ensuring that no additional writes are made.</p><p>If the response has not been started:</p><ul><li>response.ContentType is set to &quot;application/json&quot; to specify that the response body will be in JSON format.</li><li>response.StatusCode is set to 400, corresponding to HttpStatusCode.BadRequest, indicating a client-side error.</li></ul><p>Finally, response.WriteAsync serializes the errorResult object to JSON format and writes it to the response body.</p><h4>6. Serialization of Error Object</h4><p>JsonConvert.SerializeObject(errorResult) converts the errorResult object into a JSON string, which will then be included in the response body for the client to receive a structured error message.</p><h3>Step 2: Registering Custom Middleware</h3><p>Configuring middleware with .NET Core is extremely easy.</p><p>That’s why I love developing projects with .NET Core.</p><p>We open the Program.cs class of our Web.API project to register our class in the project.</p><p>At this stage, all we need to do is write the following code in the appropriate place in the Program.cs class.</p><p>That’s it.</p><pre>app.UseMiddleware&lt;ExceptionMiddleware&gt;();</pre><p>Below I am sharing the screenshot of the part where we recorded our class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*fW_KXxryojd06_Dat1omXQ.png" /></figure><h3>Conclusion</h3><p>When we run the application, we expect it to work without any problems.</p><p>I re-trigger the error code that I triggered before updating and examine the resulting response structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*nvg4NheB7wGq2w6ouT5pyQ.png" /></figure><p>The response structure created after the update is shown.</p><p>We have returned an error message that is compatible with the standard response structure we use in the application.</p><h3>Why You Should Use This Project</h3><p>If you’re looking to start a new project but don’t want to spend hours setting up the basics, this template is for you.</p><p>It’s designed to be a quick start — something you can clone and get up and running in about 10 minutes.</p><p>The architecture is clean, the code is organized, and the features are what you’d expect in a robust, modern WebAPI.</p><h3>Embracing Open Source and Community Collaboration</h3><p>One of the things I love most about being a developer is the sense of community. There’s something incredibly rewarding about sharing knowledge and tools with others.</p><p>This project is available on <a href="https://github.com/ozkanardil/dml_starterkit">GitHub</a>, and I welcome anyone to use it whether it’s for educational purposes, personal projects, or <strong>even commercial applications.</strong></p><h3>💡Want Me to Handle It For You?</h3><p>You can develop the project yourself, or if this all sounds like a lot of work, you’d rather focus on someone to help you.</p><p>I am <a href="https://linktr.ee/ozkanardil">Özkan Ardil</a>, Software Developer, Sole entrepreneur and writer.</p><p>You can contact with me via <a href="https://docs.google.com/forms/d/1MSDClB3hrbNBQlTRn_DUo83p7bWEj5aAl0fb0nUzCzw/edit">this contact form</a>.</p><p>I look forward to hearing from you.</p><p>⬇️ Other articles related to this project.</p><ul><li><a href="https://medium.com/@ozkanardil/net-8-webapi-starterkit-open-source-contribution-to-the-dev-community-8721dd7cdce0">.NET 8 WebAPI Starterkit: Open Source Contribution to the Dev Community</a></li><li><a href="https://medium.com/@ozkanardil/dml-starterkit-installation-guide-free-open-source-net-core-starterkit-project-6246d0337f27">Dml_starterkit Installation Guide: Free open source .NET Core starterkit project</a></li></ul><p>👏 <em>If you found the content useful, you can</em><strong><em> follow me</em></strong><em> and make me happy in this way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/0*Q-MdRuxRuG6m7yO5.gif" /></figure><p>💬 If there is something I overlooked, you can share it in the comments or contact me on my profile.</p><p>💬 Let me know in the comment section what have I missed? Where I was wrong?</p><p>👨‍👦‍👦 You can also share this article with your friend. Argue a little on it. It is known that the truth is born in a dispute.</p><p>🙃 Stay determined, stay focused, and keep going.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9558073d4b89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dml_starterkit Installation Guide: Free open source .NET Core starterkit project]]></title>
            <link>https://medium.com/@ozkanardil/dml-starterkit-installation-guide-free-open-source-net-core-starterkit-project-6246d0337f27?source=rss-a94a2d59980f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6246d0337f27</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[installation]]></category>
            <category><![CDATA[starter]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Özkan ARDİL]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 16:26:57 GMT</pubDate>
            <atom:updated>2024-10-27T12:17:21.574Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dml_starterkit Installation Guide: Free open source .NET Core starterkit project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ltj47iGOaf4vQ5MqgXIPdw.png" /></figure><p>Hey there! 🎉</p><p>First off, thank you so much for checking out my .NET 8 WebAPI application.</p><p>I have spent time and effort to create this project using CQRS pattern with the help of MediatR and Entity Framework Core for ORM.</p><p>My aim is to contribute to the developer community with this open source project and I hope it helps you in some way.</p><p>If you want to get information about the project before going into detail, you can take a look at my article below.</p><p>Let’s dive right into setting up the application.</p><p>I’ve tried to keep the steps simple and straightforward! 😊</p><h3>Step 1: Install the Required Software</h3><p>Before we get started, there are a couple of things you’ll need to have installed:</p><p><strong>Visual Studio 2022:</strong> This is the IDE we’ll be using to develop and run the application. By the time you read this article, a new version of Visual Studio may have been released. In this case, you can install VS 2022 or a newer version.</p><p><strong>.NET 8 SDK:</strong> The framework required to run this application. <a href="https://visualstudio.microsoft.com/tr/vs/">Here </a>is the link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4KowZIMWNpTfaBxMNJ1eA.png" /><figcaption>Community Edition is free version.</figcaption></figure><p>If you haven’t already installed Visual Studio 2022 and .NET 8, go ahead and do that first.</p><h3>Step 2: Open Visual Studio</h3><p>Once you have Visual Studio 2022 up and running, go ahead and open it.</p><p>We’ll be pulling down the project files from GitHub in just a second.</p><h3>Step 3: Clone the Repository from GitHub</h3><p>Now, let’s get the project files onto your local machine. In Visual Studio, go to ”Git &gt; Clone…” and paste in the GitHub repository URL. This will download the project to your machine.</p><p>First, copy the repository link (<a href="https://github.com/ozkanardil/dml_starterkit.git">https://github.com/ozkanardil/dml_starterkit.git</a>) from GitHub project page as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_z2RD521P9rWO-0_T1GyCg.png" /><figcaption>Dml_starterkit repo link on GithHub</figcaption></figure><p>Create a new solution and select the “Clone a repository”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*cqhvyq6QEZXkLKHM2Vhd3A.png" /><figcaption>Create an new solution and select Clone a repository</figcaption></figure><p>Select a local location for the project and click CLONE button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*0PH4Epn4mCdyXMQ7qaDcBQ.png" /><figcaption>Select a local location for DML_starterkit</figcaption></figure><p>After the clone process is completed, go to the project directory and select the solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*6KkpNjUwNxy-eeUF-JiOeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*85lb1pw_1z0ICXQIuVKXUg.png" /><figcaption>Select the Dml_starterkit project solution file</figcaption></figure><p>Now, you need a database to connect.</p><h3>Step 4: Set Up the MySQL Database</h3><p>The application requires a MySQL database to function properly. If you don’t already have MySQL installed, you can follow the steps <a href="https://dev.mysql.com/downloads/workbench/">here</a> to get it set up.</p><p>While writing this article, I was using “MySQL Workbench 8.0 CE” version. The new version may have been released while you are reading this article.</p><p>If you already have it, great!</p><p>You can skip this step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XFCkK8CotVQb3yB_DzZjnA.png" /><figcaption>MySql Workbench download page</figcaption></figure><p>After installing Workbench, run it. You need to create a Connection to create a MySql database.</p><blockquote><strong>IMPORTANT:</strong> The username and password which will be used while creating the connection are going to be used in the ConnectionString to connect to the database later.</blockquote><p>For further details, please refer to Workbench documentation.</p><h3>Step 5: Create the Database</h3><p>When you first install the Workbench application, the schema field will be empty. We will create a new schema for our project and we will do this using the sql file that comes with the project.</p><p>Navigate to the docs folder in the project directory and import the SQL file provided.</p><p>This file will set up the necessary database structure for you.</p><p>Here’s how to do it:</p><p>Go to Server &gt; Data Import in Workbench.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*WiX0NRqIX90TYPAbAcdEJg.png" /></figure><p>Select the SQL file from the docs folder of the Dml_starterkit solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlOg4fBKDKDEJ1p56FTrMw.png" /></figure><p>If you do not have a schema defined before, you need to create a new schema. If you want to use an existing schema, you can select the schema from the drop-down list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnx4Mp0BUPffnvD-I0nmKg.png" /></figure><p>Click Import button to run the script to create the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bfobf5Oc1cxdeIg5K8Mq7g.png" /></figure><p>If there is no change in the schema list on the left after the import process is successfully completed, it may be necessary to refresh the list by right-clicking on the schema field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Obl1urMCJ96mMvFu7K_iaQ.png" /><figcaption>After import is completed, refresh the schema list</figcaption></figure><p>After the schema field is updated, the newly created schema becomes visible with its tables and queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*a21mntxeNj7y6k4iVeFplg.png" /><figcaption>Fresh created Dml_starterkit schema in MySql database</figcaption></figure><p>It is useful to list the data of tables and queries to ensure that the objects work smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KVgWH5BJYVbRkKLZWiLVMA.png" /></figure><h3>Step 7: Update Your Database Connection String</h3><p>Now that the database is set up, let’s update the connection string in the project. Open up the appsettings.json and appsettings.Development.json file in the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*tX3fHLk7MC4siA3zekz7gw.png" /><figcaption>Folder structure of the DmlStarterkit Web API Project</figcaption></figure><p>modify the “DBConnection” string with your own database name, username, and password.</p><pre>&quot;DbConnString&quot;: &quot;server=localhost;database=starterkit;user=root;password=root&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*p2AazFIgTBaxr3e50NFrbQ.png" /></figure><p>The username and password in the ConnectionString must be entered using the username and password used when creating the connection after the Workbench installation.</p><h3>Step 8: Run the Application</h3><p>You’re all set!</p><p>Just hit F5 in Visual Studio to start the application.</p><p>If everything goes smoothly, your browser should open up to the Swagger page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCUzEYPy3eQmPoX6FOHeAw.png" /></figure><h3>Step 9: Get AccessToken to Login</h3><p>Let’s create our first request to get the access token.</p><p>Expand the Auth &gt; Login (POST) line as shown below then click “Try it out” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ze10NPhzthG1VTzmwnanfQ.png" /></figure><p>The request body field should be enabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q88ajsxiImJzJmFYT9tgbg.png" /></figure><p>Update the email field to <a href="/service/mailto:starterkit@test.com">starterkit@test.com</a> and the password field to 2468 then click big blue EXECUTE button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a1nJlcpRg76B-gNiKY2xCA.png" /><figcaption>Enter the credetials to get the access token</figcaption></figure><p>And that’s it! 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXGZxZ-v25632brk-XDaFA.png" /></figure><h3>Step 9: You’re Good to Go!</h3><p>Your application is now up and running.</p><p>If you run into any issues or have any questions, feel free to reach out through GitHub’s issue tracker.</p><h3>💡Do you want my support in turning your idea into reality?</h3><p>You can develop the project yourself, or if this all sounds like a lot of work, you’d rather focus on someone to help you.</p><p>I am <a href="https://linktr.ee/ozkanardil">Özkan Ardil</a>, Software Developer, Sole entrepreneur and writer.</p><p>You can contact with me via <a href="https://docs.google.com/forms/d/1MSDClB3hrbNBQlTRn_DUo83p7bWEj5aAl0fb0nUzCzw/edit">this contact form</a>.</p><p>I look forward to hearing from you.</p><p>👏 <em>If you found the content useful, you can</em><strong><em> follow me</em></strong><em> and make me happy in this way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/0*dyHveN3FQpNgX7s6.gif" /></figure><p>💬 If there is something I overlooked, you can share it in the comments or contact me on my profile.</p><p>💬 Let me know in the comment section what have I missed? Where I was wrong?</p><p>👨‍👦‍👦 You can also share this article with your friend. Argue a little on it. It is known that the truth is born in a dispute.</p><p>🙃 Stay determined, stay focused, and keep going.</p><p>Thanks for reading.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6246d0337f27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET 8 WebAPI Starterkit: Open Source Contribution to the Dev Community]]></title>
            <link>https://medium.com/@ozkanardil/net-8-webapi-starterkit-open-source-contribution-to-the-dev-community-8721dd7cdce0?source=rss-a94a2d59980f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8721dd7cdce0</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[starter]]></category>
            <category><![CDATA[free]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Özkan ARDİL]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 16:21:55 GMT</pubDate>
            <atom:updated>2024-10-27T12:18:46.243Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Lv-oJkXlnVWqMZlF3WMfVA.png" /></figure><p>Hey Everyone!</p><p>I’m excited to share the Open Source.NET 8 WebAPI Starterkit Project.</p><p>After spending some time refining the code, I decided to contribute this project to the developer community as an open-source tool.</p><p>It’s a project that’s designed with an easy-to-use code structure, and I believe it could be a valuable resource for anyone looking to kickstart their own .NET Core Web API project.</p><p>Whether you’re an experienced developer or just starting out, this might be just what you need to save time and get going quickly.</p><blockquote>I included the article about the installation of the project at the end of the article.</blockquote><h3>Why Did I Create This?</h3><p>In the world of software development, time is everything.</p><p>We’re constantly juggling multiple tasks, trying to meet deadlines, and looking for ways to make our workflow more efficient.</p><p>I’ve been there, and I know how challenging it can be to start a new project from scratch, especially when you want to follow all the right design patterns and best practices.</p><p>That’s why I decided to create this template .NET 8 WebAPI that’s ready to go with a solid structure, essential features, and a focus on clean, maintainable code.</p><p>I will also continue to provide information about the development process of the project by writing articles. In which I plan to explain in detail the approaches I used in the project for my fellow software developers who want to improve themselves in C#.</p><p>However, I did not want to wait to write the articles to make it available as a customizable project for advanced software developers.</p><p>I know that I have a lot of work to do and a lot of features to add. There are many things that I will improve, especially the logging feature, and there are many things waiting on my to-do list.</p><p>But I wanted to publish the project with the minimum features required. I have no doubt that it will save time for those who want to start new projects.</p><p>I would also like to point out that I have successfully implemented similar projects in small startups, large corporate companies, and government institutions.</p><h3>A Peek Inside the Project</h3><p>Let’s dive into what this project actually looks like.</p><p>I’ve structured it with a layered architecture that keeps everything organized and adheres to the separation of concerns principle.</p><p>Here’s how the project is laid out:</p><p><strong>WebAPI</strong>: This is the core API layer that interfaces with the outside world.<br><strong>Application Layer</strong>: All the business logic and rules reside here.<br><strong>Infrastructure Layer</strong>: This handles cross-cutting concerns mainly.<br><strong>Persistence Layer</strong>: The go-to spot for database interactions, using Entity Framework Core.<br><strong>Domain Layer</strong>: This is where the domain models and core business logic are housed.</p><h3>Key Features</h3><p>Now, let’s talk about the features.</p><p>I wanted this project to be more than just a bare-bones template.</p><p>It’s packed with features that I believe every modern WebAPI should have:</p><p><strong>1. Standardized Response Model:</strong> Consistent and structured responses across the API, making it easier to handle errors and process responses on the client side.<br> <br><strong>2. Separation of Concerns:</strong> The code is clean, organized, and easy to maintain, with each responsibility neatly tucked into its own layer.<br> <br><strong>3. Clean Code:</strong> I’ve paid special attention to writing code that’s not just functional but also readable and maintainable. Of course, it is always possible to write better. After all, software itself is a constantly evolving organism. I look forward to your contributions on this subject.<br> <br><strong>4. JWT Bearer Token Authentication:</strong> Security is a big deal, so I’ve implemented JWT token-based authentication for secure login. It is ready to use.<br> <br><strong>5. Swagger Integration:</strong> To make API documentation a breeze, Swagger is integrated, giving you an easy way to explore and test the API.<br> <br><strong>6. Custom Middleware for Error Handling:</strong> There’s custom middleware in place to handle errors gracefully and log them efficiently.<br> <br><strong>7. Custom Logging:</strong> Speaking of logging, I’ve added a custom logging feature to help you monitor and debug your application with ease. However, I intend to integrate a library like NLog or SerialLog when I find time.</p><h3>Why You Should Use This Project</h3><p>If you’re looking to start a new project but don’t want to spend hours setting up the basics, this template is for you.</p><p>It’s designed to be a quick start — something you can clone and get up and running in about 10 minutes.</p><p>The architecture is clean, the code is organized, and the features are what you’d expect in a robust, modern WebAPI.</p><p>Security is built-in with JWT authentication, and Swagger makes it easy to document and share your API. Plus, with the standard response model and custom error handling, you’ll have a solid foundation to build on, whether you’re working on a personal project or something for a client.</p><h3>Embracing Open Source and Community Collaboration</h3><p>One of the things I love most about being a developer is the sense of community. There’s something incredibly rewarding about sharing knowledge and tools with others.</p><p>This project is available on <a href="https://github.com/ozkanardil/dml_starterkit">GitHub</a>, and I welcome anyone to use it whether it’s for educational purposes, personal projects, or <strong>even commercial applications.</strong></p><p>And if you have ideas for improvements or new features, I’d love to see your contributions.</p><p>Open source is all about collaboration, and I’m excited to see where we can take this project together.</p><h3>Source Code</h3><p>You can access the source code for my <a href="https://github.com/ozkanardil/dml_starterkit">DML Starterkit Github</a> repo. I would be very pleased if you gave stars to the project and followed me.</p><h3>Installation Guide</h3><p>If you’re ready to dive in and start building, be sure to check out the detailed <a href="https://medium.com/@ozkanardil/dml-starterkit-installation-guide-free-open-source-net-core-starterkit-project-6246d0337f27">installation guide</a> where I walk you through the step-by-step process to set up the project and get it running smoothly.</p><h3>Looking Ahead</h3><p>While I’m really happy with how this project has turned out so far, I’m far from done. I plan to keep updating and improving it.</p><p>In the future, I’m thinking about adding support for more databases, integrating other authentication methods, writing unit tests, and even exploring microservice architecture.</p><p>Your feedback and contributions will be key in shaping the future of this project. I’m always open to suggestions, and I can’t wait to see what we can build together.</p><p>This is just the beginning, and I’m excited to keep pushing this project forward with the help of the community.</p><h3>Wrapping Up</h3><p>To sum it all up, this .NET 8 WebAPI project is here to help you start your next project faster and with a solid foundation.</p><p>It’s built with modern development practices in mind — CQRS pattern, Mediatr, Entity Framework Core, and more.</p><p>So, head over to GitHub, check it out, and let me know what you think.</p><p>I hope this project saves you time, helps you learn something new, and makes your development process just a little bit easier.</p><p>Let’s continue to build, learn, and share together.</p><h3>💡Want Me to Handle It For You?</h3><p>You can develop the project yourself, or if this all sounds like a lot of work, you’d rather focus on someone to help you.</p><p>I am <a href="https://linktr.ee/ozkanardil">Özkan Ardil</a>, Software Developer, Sole entrepreneur and writer.</p><p>You can contact with me via <a href="https://docs.google.com/forms/d/1MSDClB3hrbNBQlTRn_DUo83p7bWEj5aAl0fb0nUzCzw/edit">this contact form</a>.</p><p>I look forward to hearing from you.</p><p>👏 <em>If you found the content useful, you can</em><strong><em> follow me</em></strong><em> and make me happy in this way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/0*dyHveN3FQpNgX7s6.gif" /></figure><p>💬 If there is something I overlooked, you can share it in the comments or contact me on my profile.</p><p>💬 Let me know in the comment section what have I missed? Where I was wrong?</p><p>👨‍👦‍👦 You can also share this article with your friend. Argue a little on it. It is known that the truth is born in a dispute.</p><p>🙃 Stay determined, stay focused, and keep going.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8721dd7cdce0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Standardized Response Structures Are Essential for High-Quality C# Projects]]></title>
            <link>https://medium.com/@ozkanardil/why-standardized-response-structures-are-essential-for-high-quality-c-projects-e4f66d04a11d?source=rss-a94a2d59980f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4f66d04a11d</guid>
            <category><![CDATA[quality]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[responses]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Özkan ARDİL]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 06:00:25 GMT</pubDate>
            <atom:updated>2024-07-16T06:00:25.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*1Bpqeq0nBqRlYXVN5xvrxg.png" /></figure><p>In software projects, especially in back-end (BE) projects, response models play an extremely critical role. Backend projects are in constant communication with other services and applications, and the response models returned by the BE are used by these.</p><p>Therefore, having response models adhere to a specific standard is of great importance for the development and sustainability of the project.</p><h4>The Role of Response Models in Projects</h4><p>Response models enhance the usability and clarity of the services offered by APIs. They define the structure and format of the data returned to the user. This allows frontend or service developers to rely on the format of the data returned from the backend, enabling them to create business processes related to this data more effectively.</p><p>For example, the response model for an API that retrieves product details on an e-commerce site might look like this:</p><pre>{<br>  &quot;id&quot;: 123,<br>  &quot;name&quot;: &quot;Ürün Adı&quot;,<br>  &quot;price&quot;: 49.99,<br>  &quot;description&quot;: &quot;Ürün açıklaması&quot;,<br>  &quot;category&quot;: {<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;Kategori Adı&quot;<br>  },<br>  &quot;stock&quot;: 20<br>}</pre><h4>The Importance of a Standardized Response Model</h4><p>This response model clearly shows front-end developers the structure and expected fields of the data returned from the backend. As a result, frontend developers can use this data model to create the product detail page. While the above model is usable, standardizing response models for the purpose of increasing software efficiency has many advantages.</p><h4>The Approach I Follow to Standardize Response Models</h4><p>In my projects, I use four different response models:</p><ul><li>Models that return data</li><li>Models that do not return data</li></ul><p>Additionally, I categorize them as:</p><ul><li>Successful</li><li>Unsuccessful</li></ul><p>Now, let’s take a look at each response model and an example of its usage.</p><h4>Basic Response Model</h4><p>One of the key steps in standardizing response models in a software project is to ensure that all response models share common characteristics. To achieve this, I derive response models from a specific interface.</p><p>Such an interface ensures that the response models are consistent and compatible.</p><p>Below is the IRequestResult interface that I use in my projects.</p><pre>public interface IRequestResult<br>{<br>    bool Success { get; }<br>    string Message { get; }<br>}</pre><h4>Let’s Examine This Interface Step by Step:</h4><p><strong>bool Success { get; }</strong></p><p>This property determines whether the operation was successful.</p><ul><li>The Success property is of boolean (bool) type.</li><li>A value of <strong>true</strong> indicates that the operation was completed successfully.</li><li>A value of <strong>false</strong> indicates that the operation failed.</li><li>This property serves as a fundamental component of the response model, allowing for a quick understanding of the operation’s result.</li></ul><p><strong>string Message { get; }</strong></p><p>This property provides detailed information about the result of the operation.</p><ul><li>The Message property is of string type.</li><li>It contains a message that explains the outcome of the operation.</li><li>In successful operations, it typically returns a message indicating that the operation was completed successfully (e.g., “The operation was completed successfully.”).</li><li>In failed operations, it includes a message explaining the reason for the error (e.g., “Invalid input parameters.”).</li><li>This property helps users and developers understand why the operation was successful or unsuccessful.</li></ul><p>Below is the RequestResult class that implements the IRequestResult interface. All successful or error response models we will see later will inherit from this class.</p><p>Let me explain the functionality of the code and how it works:</p><pre>public class RequestResult : IRequestResult<br>{<br>    // İki parametreli constructor. Bu constructor, Success ve Message özelliklerini ayarlamak için kullanılır.<br>    public RequestResult(bool success, string message) : this(success)<br>    {<br>        Message = message;<br>    }<br><br>    // Tek parametreli constructor. Bu constructor, sadece Success özelliğini ayarlamak için kullanılır.<br>    public RequestResult(bool success)<br>    {<br>        Success = success;<br>    }<br><br>    // Success özelliği, işlemin başarılı olup olmadığını belirtir.<br>    public bool Success { get; }<br><br>    // Message özelliği, işlemin sonucu hakkında bilgi verir.<br>    public string Message { get; }<br>}</pre><p>The <strong>RequestResult</strong> class implements the <strong>IRequestResult</strong> interface. Therefore, it has the <strong>Success</strong> and <strong>Message</strong> properties.</p><h3>Response Models Without Data: Successful and Error Models</h3><p>I derived the following SuccessRequestResult and ErrorRequestResult classes from the RequestResult class.</p><h4>SuccessRequestResult Class for Success Status:</h4><pre>public class SuccessRequestResult : RequestResult<br>{<br>    public SuccessRequestResult(string message) : base(true, message)<br>    {<br>    }<br><br>    public SuccessRequestResult() : base(true)<br>    {<br>    }<br>}</pre><p>Let Me Briefly Explain This Class:</p><p>SuccessRequestResult(string message): A constructor that contains a message for successful operations. It calls the constructor of the <strong>RequestResult</strong> class with <strong>true</strong> and the <strong>message</strong> parameter using the expression `base(true, message)`.</p><p><strong>SuccessRequestResult():</strong> A constructor without a message for successful operations. It calls the constructor of the RequestResult class with only the true parameter using the expression `base(true)`.</p><h4>ErrorRequestResult Class for Error Status:</h4><pre>public class ErrorRequestResult : RequestResult<br>{<br>    public ErrorRequestResult(string message) : base(false, message)<br>    {<br>    }<br><br>    public ErrorRequestResult() : base(false)<br>    {<br>    }<br>}</pre><p>Let Me Briefly Explain This Class:</p><p>ErrorRequestResult(string message): A constructor that contains a message for error operations. It calls the constructor of the RequestResult class with false and the message parameter using the expression `base(false, message)`.</p><p>ErrorRequestResult(): A constructor without a message for error operations. It calls the constructor of the RequestResult class with only the false parameter using the expression `base(false)`.</p><p>Up to this point, we have examined response models that do not contain data. In summary, we created two different response models for successful and unsuccessful requests, derived from a basic response model.</p><p>So, what should we do if we need to return additional data along with the status and message in the response model?</p><p>In my applications, I use the structure explained below.</p><h3>Response Model Interface with Data</h3><p>The following IRequestDataResult&lt;T&gt; interface is derived from the IRequestResult interface and represents a response model that includes a generic data type.</p><pre>public interface IRequestDataResult&lt;out T&gt; : IRequestResult<br>{<br>    T Data { get; }<br>}</pre><p>Let Me Briefly Explain This Interface:</p><p><strong>&lt;out T&gt;:</strong> The interface is defined with a generic type T. The out keyword indicates that the type T is covariant, meaning it can only be used as a return type. This allows broader types to be used as narrower types.</p><p><strong>IRequestDataResult&lt;T&gt;:</strong> This interface extends the IRequestResult interface. In addition to the Success and Message properties from the IRequestResult interface, it includes a property named Data.</p><p><strong>T Data { get; }:</strong> This property represents the data returned as a result of the request. The type T is determined based on the context in which the interface is used, providing flexibility due to its generic structure.</p><p>Since it is defined with a get accessor, this property cannot be set from outside and is read-only.</p><p>The following RequestDataResult&lt;T&gt; class is a generic response model derived from the RequestResult class and implements the IRequestDataResult&lt;T&gt; interface.</p><pre>public class RequestDataResult&lt;T&gt; : RequestResult, IRequestDataResult&lt;T&gt;<br>{<br>    public RequestDataResult(T data, bool success, string message) : base(success, message)<br>    {<br>        Data = data;<br>    }<br><br>    public RequestDataResult(T data, bool success) : base(success)<br>    {<br>        Data = data;<br>    }<br><br>    public T Data { get; }<br>}</pre><p>Let Me Briefly Explain This Class:</p><p>RequestDataResult&lt;T&gt; is derived from the RequestResult class therefore, it has the Success and Message properties. The RequestDataResult&lt;T&gt; class is a comprehensive response model that includes both the success and message information (Success, Message) as well as the returned data (Data).</p><p>Thanks to its generic structure, it can be used with any data type, providing a flexible and reusable design. By combining the structures of RequestResult and IRequestDataResult&lt;T&gt;, it ensures that response models are consistent and standardized.</p><h4>SuccessRequestDataResult&lt;T&gt; Class for Success Status:</h4><p>The following SuccessRequestDataResult&lt;T&gt; class is derived from the RequestDataResult&lt;T&gt; class and is a generic response model used for successful cases.</p><pre>public class SuccessRequestDataResult&lt;T&gt; : RequestDataResult&lt;T&gt;<br>{<br>    public SuccessRequestDataResult(T data, string message) : base(data, true, message)<br>    {<br>    }<br><br>    public SuccessRequestDataResult(T data) : base(data, true)<br>    {<br>    }<br><br>    public SuccessRequestDataResult(string message) : base(default, true, message)<br>    {<br><br>    }<br><br>    public SuccessRequestDataResult() : base(default, true)<br>    {<br><br>    }<br>}</pre><p>Let Me Briefly Explain This Class:</p><p>This class provides customized response models for successful operations. The Success property is always set to true. It offers different constructors that include combinations of data and messages for successful operations.</p><p>Thanks to its generic structure, it can be used with any data type, providing a flexible and reusable design.</p><h4>ErrorRequestDataResult&lt;T&gt; Class for Error Status:</h4><p>The following ErrorRequestDataResult&lt;T&gt; class is derived from the RequestDataResult&lt;T&gt; class and is a generic response model used for error cases.</p><pre>public class ErrorRequestDataResult&lt;T&gt; : RequestDataResult&lt;T&gt;<br>{<br>    public ErrorRequestDataResult(T data, string message) : base(data, false, message)<br>    {<br>    }<br><br>    public ErrorRequestDataResult(T data) : base(data, false)<br>    {<br>    }<br><br>    public ErrorRequestDataResult(string message) : base(default, false, message)<br>    {<br><br>    }<br><br>    public ErrorRequestDataResult() : base(default, false)<br>    {<br><br>    }<br>}</pre><p>Let Me Briefly Explain This Class:</p><p>ErrorRequestDataResult&lt;T&gt; is derived from the RequestDataResult&lt;T&gt; class therefore, it has the Data, Success, and Message properties. This class provides customized response models for error operations, with the Success property always set to false.</p><p>It offers different constructors that include combinations of data and messages for error cases. Thanks to its generic structure, it can be used with any data type, providing a flexible and reusable design.</p><p>Now, let’s see how these response models containing data are used in a Web API project. The project folder structure is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*yKjc3FAaEBy30K0MtEsJ_g.png" /><figcaption>Structure of the Standard Response Models Project</figcaption></figure><p>I placed the interfaces and classes inside the Model folder.</p><p>In the Data folder, I created the following class to simulate the data:</p><pre> public class UserModel<br> {<br>     public int Id { get; set; }<br>     public string Name { get; set; }<br><br>     public List&lt;UserModel&gt; ListUsers()<br>     {<br>         List&lt;UserModel&gt; users = new List&lt;UserModel&gt;();<br>         users.Add(new UserModel { Id = 1, Name = &quot;User Name1&quot; });<br>         users.Add(new UserModel { Id = 2, Name = &quot;User Name2&quot; });<br>         users.Add(new UserModel { Id = 3, Name = &quot;User Name3&quot; });<br><br>         return users;<br>     }<br> }</pre><p>In the project, I created four endpoints within the ResponseModelsController.cs.</p><pre>[Route(&quot;api/[controller]&quot;)]<br>[ApiController]<br>public class ResponseModelsController : ControllerBase<br>{<br>    private List&lt;UserModel&gt; _userData = new List&lt;UserModel&gt;();<br>    public ResponseModelsController()<br>    {<br>        UserModel userModel = new UserModel();<br>        _userData = userModel.ListUsers();<br>    }<br><br>    [HttpGet(&quot;SuccessResponseWithoutData&quot;)]<br>    public IActionResult SuccessWithoutData()<br>    {<br>        return Ok(new SuccessRequestResult(&quot;Success response without data&quot;));<br>    }<br><br>    [HttpGet(&quot;ErrorResponseWithoutData&quot;)]<br>    public IActionResult ErrorWithoutData()<br>    {<br>        return BadRequest(new ErrorRequestResult(&quot;Error response without data&quot;));<br>    }<br><br>    [HttpGet(&quot;SuccessResponseWithData&quot;)]<br>    public IActionResult SuccessWithData()<br>    {<br>        return Ok(new SuccessRequestDataResult&lt;List&lt;UserModel&gt;&gt;(_userData, &quot;Success response with data&quot;));<br>    }<br><br>    [HttpGet(&quot;ErrorResponseWithData&quot;)]<br>    public IActionResult ErrrorWithData()<br>    {<br>        return Ok(new ErrorRequestDataResult&lt;List&lt;UserModel&gt;&gt;(&quot;Error response with data&quot;));<br>    }<br>}</pre><p>When we run the project, the Swagger interface greets us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CJdnususwNdKSfRXjhqi6w.png" /><figcaption>Swagger Interface of the StandardResponseTypes Project</figcaption></figure><p>Below is the output of a successful response model that does not contain any data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UN0HzJTzDmxStGGHlDyUw.png" /><figcaption>Successs Response without Data</figcaption></figure><p>Below is the output of an error response model that does not contain any data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*llEQoelSjjQGk0OGCZFung.png" /><figcaption>Error Response without Data</figcaption></figure><p>Below is the output of a successful response model that contains data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4wmCa9PbkrMZBx18X-Hqw.png" /><figcaption>Successs Response with Data</figcaption></figure><p>Below is the output of an error response model that contains data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNAIUIpMnqS9O7tomzYdEQ.png" /><figcaption>Error Response with Data</figcaption></figure><h3>Source Code</h3><p>You can access the source code for my <a href="https://github.com/ozkanardil/csharp_subjects">project on Github</a>. I would be very pleased if you gave stars to the project and followed me.</p><h3>Conclusion</h3><p>In software projects, the standardization of response models plays an extremely critical role, especially in the communication between backend and frontend applications.</p><p>This standardization facilitates the development process of projects and increases their sustainability.</p><p>Standard response models provide clear and consistent data communication for all team members.</p><p>As a result, frontend developers can more easily understand and process the responses coming from the backend.</p><p>Additionally, having a uniform response structure speeds up debugging and maintenance processes because all responses are in the same format, making problem identification and resolution faster.</p><p>Standard response models also enhance code reusability and extensibility. Once a standard model is created, it can be easily used across different modules and projects.</p><p>This ensures that developers do not have to recreate the same structure repeatedly, thus speeding up the development process.</p><p>Moreover, working with standard response models improves quality and reliability in software projects.</p><p>These standards allow developers to work in a more organized and structured manner, making project management more effective.</p><p>👏 <em>If you found the content useful, you can</em><strong><em> follow me</em></strong><em> and make me happy in this way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/0*bpX8jchJt8pL_8UD.gif" /></figure><p>💬 If there is something I overlooked, you can share it in the comments or contact me on my profile.</p><p>⬇️ Check out my other articles.</p><ul><li><a href="https://medium.com/@ozkanardil/building-a-youtube-video-fetcher-with-net-core-a-step-by-step-guide-6f3c6d05e566">Building a YouTube Video Fetcher with .NET Core: A Step-by-Step Guide</a></li><li><a href="https://medium.com/@ozkanardil/reading-the-appsettings-json-file-using-ioptions-in-net-core-3bdc9e2b10e2">Reading the appsettings.json file using IOptions in .NET Core</a></li><li><a href="https://medium.com/@ozkanardil/string-and-stringbuilder-in-c-detailed-comparison-and-best-practices-ff8776852a53">Boost your C# Application with Hidden Power of StringBuilder over String</a></li></ul><p>💬 Let me know in the comment section what have I missed? Where I was wrong?</p><p>👨‍👦‍👦 You can also share this article with your friend. Argue a little on it. It is known that the truth is born in a dispute.</p><p>🙃 Stay determined, stay focused, and keep going.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4f66d04a11d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>