<?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 İbrahim Emre POLAT on Medium]]></title>
        <description><![CDATA[Stories by İbrahim Emre POLAT on Medium]]></description>
        <link>https://medium.com/@ieplt?source=rss-ec97c01c22c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*T5I0JYnUiP7C98wCQDAu8A@2x.jpeg</url>
            <title>Stories by İbrahim Emre POLAT on Medium</title>
            <link>https://medium.com/@ieplt?source=rss-ec97c01c22c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 02:11:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ieplt/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[Comparing the Best ORM Tools for ASP.NET Core: Entity Framework vs. Dapper]]></title>
            <link>https://medium.com/@ieplt/comparing-the-best-orm-tools-for-asp-net-core-entity-framework-vs-dapper-c29c0c6faf6f?source=rss-ec97c01c22c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c29c0c6faf6f</guid>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[dapper]]></category>
            <dc:creator><![CDATA[İbrahim Emre POLAT]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 06:32:37 GMT</pubDate>
            <atom:updated>2024-06-28T06:32:37.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TWfw0xBf7C_VdN4An99DVQ.png" /></figure><p>Object-Relational Mapping (ORM) tools are essential in modern web development as they simplify data manipulation and database interactions. For ASP.NET Core, two of the most popular ORM tools are Entity Framework (EF) and Dapper. Each has its own strengths and weaknesses, and choosing the right one depends on various factors such as performance requirements, ease of use, and project complexity. This article provides a detailed comparison of Entity Framework and Dapper, highlighting their differences and offering guidance on when to use each.</p><h4>Overview of Entity Framework</h4><p><strong>Entity Framework (EF)</strong> is Microsoft’s official ORM tool for .NET. It is a comprehensive and feature-rich ORM that provides a high level of abstraction, allowing developers to work with databases using .NET objects.</p><p><strong>Key Features:</strong></p><ul><li><strong>Code First, Database First, and Model First Approaches</strong>: EF supports multiple development workflows, offering flexibility in how you design and manage your database.</li><li><strong>LINQ Queries</strong>: Allows for powerful and type-safe querying directly from your code.</li><li><strong>Change Tracking</strong>: Automatically tracks changes to your entities and applies those changes to the database.</li><li><strong>Migrations</strong>: Simplifies database schema management and versioning.</li></ul><p><strong>Example Code:</strong></p><p>Creating a database context and model:</p><pre>public class ApplicationDbContext : DbContext<br>{<br>    public DbSet&lt;Customer&gt; Customers { get; set; }<br>}<br><br>public class Customer<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public string Email { get; set; }<br>}<br><br>// Adding a new customer<br>using (var context = new ApplicationDbContext())<br>{<br>    var customer = new Customer { Name = &quot;Ibrahim Emre Polat&quot;, Email = &quot;info@e-polat.dev&quot; };<br>    context.Customers.Add(customer);<br>    context.SaveChanges();<br>}</pre><p>Fetching data with LINQ:</p><pre>using (var context = new ApplicationDbContext())<br>{<br>    var customers = context.Customers.Where(c =&gt; c.Name.StartsWith(&quot;I&quot;)).ToList();<br>}</pre><h4>Overview of Dapper</h4><p><strong>Dapper</strong> is a lightweight ORM tool developed by the team at Stack Overflow. It is known for its performance and simplicity, providing a thin abstraction over raw ADO.NET.</p><p><strong>Key Features:</strong></p><ul><li><strong>Performance</strong>: Dapper is often faster than EF due to its minimal abstraction and direct mapping.</li><li><strong>Simplicity</strong>: Provides a straightforward API that is easy to use.</li><li><strong>Flexibility</strong>: Allows for writing raw SQL queries and commands while still benefiting from parameterized queries to prevent SQL injection.</li><li><strong>Extension Methods</strong>: Adds methods to the IDbConnection interface for seamless database interactions.</li></ul><p><strong>Example Code:</strong></p><p>Connecting to the database and executing a query:</p><pre>using (var connection = new SqlConnection(&quot;YourConnectionString&quot;))<br>{<br>    var sql = &quot;INSERT INTO Customers (Name, Email) VALUES (@Name, @Email)&quot;;<br>    var customer = new { Name = &quot;Ibrahim Emre POLAT&quot;, Email = &quot;info@e-polat.dev&quot; };<br>    connection.Execute(sql, customer);<br>}</pre><p>Fetching data with a query:</p><pre>using (var connection = new SqlConnection(&quot;YourConnectionString&quot;))<br>{<br>    var sql = &quot;SELECT * FROM Customers WHERE Name LIKE &#39;I%&#39;&quot;;<br>    var customers = connection.Query&lt;Customer&gt;(sql).ToList();<br>}</pre><h4>Key Differences Between Entity Framework and Dapper</h4><p><strong>Abstraction Level</strong>:</p><ul><li><strong>Entity Framework</strong>: Provides a high level of abstraction, making it easier to work with complex object graphs and relationships. It abstracts much of the underlying database operations, which can simplify development but may introduce overhead.</li><li><strong>Dapper</strong>: Offers a low level of abstraction, giving you more control and visibility over the SQL being executed. This can lead to better performance and more efficient queries, but requires more manual work.</li></ul><p><strong>Performance</strong>:</p><ul><li><strong>Entity Framework</strong>: Slower than Dapper due to the additional abstraction and features like change tracking and LINQ translation. It is suitable for applications where developer productivity and code maintainability are prioritized over raw performance.</li><li><strong>Dapper</strong>: Highly performant and suitable for scenarios where raw speed is critical. Dapper directly maps query results to objects, resulting in minimal overhead.</li></ul><p><strong>Ease of Use</strong>:</p><ul><li><strong>Entity Framework</strong>: Easier for beginners due to its high-level API and integration with Visual Studio tools. The ability to use LINQ for queries simplifies the learning curve.</li><li><strong>Dapper</strong>: Simpler and more straightforward for developers familiar with SQL and database concepts. It requires writing raw SQL queries, which can be more flexible but also more error-prone.</li></ul><p><strong>Flexibility</strong>:</p><ul><li><strong>Entity Framework</strong>: Best for applications with complex domain models and where the database schema might change frequently. It provides tools for managing schema changes through migrations.</li><li><strong>Dapper</strong>: Ideal for scenarios where you need fine-grained control over SQL queries and performance optimization. It does not impose any particular structure on your code or database schema.</li></ul><p><strong>Change Tracking</strong>:</p><ul><li><strong>Entity Framework</strong>: Automatically tracks changes to entities, which can simplify update scenarios. This feature is useful for applications where maintaining entity state is important.</li><li><strong>Dapper</strong>: Does not provide change tracking, requiring manual management of entity states. This can lead to more boilerplate code but offers better performance.</li></ul><p><strong>Migrations</strong>:</p><ul><li><strong>Entity Framework</strong>: Built-in support for migrations, making it easier to evolve your database schema. This is particularly useful in agile development environments where the schema evolves over time.</li><li><strong>Dapper</strong>: Lacks built-in migration support, so you need to manage schema changes manually or use third-party tools like FluentMigrator.</li></ul><h4>When to Use Entity Framework</h4><ul><li><strong>Complex Applications</strong>: When your application has a complex domain model with numerous relationships and entities. EF’s high-level abstraction and feature set are well-suited for managing intricate data models.</li><li><strong>Rapid Development</strong>: When you need to quickly prototype and develop applications without worrying about the underlying database details. EF’s tooling and integration with Visual Studio can speed up the development process.</li><li><strong>Change Tracking</strong>: When you benefit from automatic change tracking and entity state management. This is useful in scenarios where the business logic depends heavily on knowing the state of entities.</li><li><strong>Schema Evolution</strong>: When you need built-in support for database migrations. EF’s migration tools make it easy to apply and track schema changes over the lifecycle of your application.</li></ul><h4>When to Use Dapper</h4><ul><li><strong>Performance-Critical Applications</strong>: When raw performance is crucial, and you need to minimize the overhead of ORM abstraction. Dapper’s lightweight nature makes it ideal for high-performance applications.</li><li><strong>Simple CRUD Operations</strong>: When your application primarily performs simple CRUD operations without complex relationships. Dapper’s straightforward API is well-suited for basic data access patterns.</li><li><strong>Full Control over SQL</strong>: When you need full control over the SQL queries being executed and want to write optimized SQL. This is particularly useful for fine-tuning performance and optimizing query execution plans.</li><li><strong>Microservices and APIs</strong>: When building lightweight microservices or APIs where simplicity and performance are prioritized. Dapper’s minimal overhead and ease of use make it a good fit for these architectures.</li></ul><h4>Detailed Examples</h4><p><strong>Entity Framework Example</strong>: Managing a customer database with EF.</p><pre>public class ApplicationDbContext : DbContext<br>{<br>    public DbSet&lt;Customer&gt; Customers { get; set; }<br><br>    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)<br>    {<br>        optionsBuilder.UseSqlServer(&quot;YourConnectionString&quot;);<br>    }<br>}<br><br>public class Customer<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public string Email { get; set; }<br>}<br><br>// Adding a new customer<br>using (var context = new ApplicationDbContext())<br>{<br>    var customer = new Customer { Name = &quot;Ibrahim Emre POLAT&quot;, Email = &quot;info@e-polat.dev&quot; };<br>    context.Customers.Add(customer);<br>    context.SaveChanges();<br>}<br><br>// Fetching customers<br>using (var context = new ApplicationDbContext())<br>{<br>    var customers = context.Customers.Where(c =&gt; c.Name.StartsWith(&quot;I&quot;)).ToList();<br>}</pre><p><strong>Dapper Example</strong>: Managing a customer database with Dapper.</p><pre>public class Customer<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public string Email { get; set; }<br>}<br><br>// Adding a new customer<br>using (var connection = new SqlConnection(&quot;YourConnectionString&quot;))<br>{<br>    var sql = &quot;INSERT INTO Customers (Name, Email) VALUES (@Name, @Email)&quot;;<br>    var customer = new { Name = &quot;Ibrahim Emre POLAT&quot;, Email = &quot;info@e-polat.dev&quot; };<br>    connection.Execute(sql, customer);<br>}<br><br>// Fetching customers<br>using (var connection = new SqlConnection(&quot;YourConnectionString&quot;))<br>{<br>    var sql = &quot;SELECT * FROM Customers WHERE Name LIKE &#39;I%&#39;&quot;;<br>    var customers = connection.Query&lt;Customer&gt;(sql).ToList();<br>}</pre><h4>Conclusion</h4><p>Choosing between Entity Framework and Dapper depends on your project requirements and constraints. Entity Framework offers a high level of abstraction, ease of use, and rich features suitable for complex applications. Dapper, on the other hand, provides exceptional performance, simplicity, and flexibility for scenarios where you need direct control over SQL execution.</p><p>By understanding the strengths and weaknesses of each tool, you can make an informed decision that aligns with your project’s goals. Both Entity Framework and Dapper have their place in the ASP.NET Core ecosystem, and the right choice will depend on the specific needs of your application. For example, if your project involves complex data relationships and requires rapid development, Entity Framework is likely the better choice. On the other hand, if you need high performance and full control over your SQL queries, Dapper would be more suitable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c29c0c6faf6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering SOLID Principles with Memorable Examples in ASP.NET Core]]></title>
            <link>https://medium.com/@ieplt/mastering-solid-principles-with-memorable-examples-in-asp-net-core-7de6ad8da124?source=rss-ec97c01c22c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7de6ad8da124</guid>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[csharp-programming]]></category>
            <dc:creator><![CDATA[İbrahim Emre POLAT]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 06:32:40 GMT</pubDate>
            <atom:updated>2024-06-24T06:32:40.694Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTGAL3L_xqOpf-labTY7XA.png" /></figure><p>As developers, we often hear about SOLID principles, yet applying them correctly can sometimes be challenging. Understanding and implementing these principles correctly can transform our code from a tangled mess into clean, maintainable, and scalable software. In this article, we will explore each SOLID principle in detail, using memorable examples in ASP.NET Core. We’ll demonstrate code both with and without the principles to highlight their importance.</p><h4>What Are SOLID Principles?</h4><p>SOLID is an acronym for five key design principles:</p><ol><li><strong>S</strong>ingle Responsibility Principle (SRP)</li><li><strong>O</strong>pen/Closed Principle (OCP)</li><li><strong>L</strong>iskov Substitution Principle (LSP)</li><li><strong>I</strong>nterface Segregation Principle (ISP)</li><li><strong>D</strong>ependency Inversion Principle (DIP)</li></ol><p>These principles help developers create systems that are easy to maintain, extend, and refactor. Let’s delve into each principle with examples.</p><h3>1. Single Responsibility Principle (SRP)</h3><p>The Single Responsibility Principle states that a class should have only one reason to change, meaning it should have only one job or responsibility. This principle enhances the modularity and readability of your code.</p><p><strong>Example:</strong></p><p>Consider an ASP.NET Core application where we have a service that handles user authentication and logging. Combining these responsibilities in one class violates the SRP. Here’s how you can refactor it:</p><p><strong>Without SRP:</strong></p><pre>public class UserService<br>{<br>    public void Authenticate(string username, string password)<br>    {<br>        // Authentication logic<br>    }<br><br>    public void Log(string message)<br>    {<br>        // Logging logic<br>    }<br>}</pre><p><strong>With SRP:</strong></p><pre>public class AuthenticationService<br>{<br>    public void Authenticate(string username, string password)<br>    {<br>        // Authentication logic<br>    }<br>}<br><br>public class LoggingService<br>{<br>    public void Log(string message)<br>    {<br>        // Logging logic<br>    }<br>}</pre><p>By separating the authentication and logging responsibilities into different classes, each class now has a single responsibility, making the code more modular and easier to maintain.</p><h3>2. Open/Closed Principle (OCP)</h3><p>The Open/Closed Principle states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. This means you should be able to add new functionality without changing existing code.</p><p><strong>Example:</strong></p><p>Let’s consider an ASP.NET Core application that calculates discounts. Initially, we have a class that applies a fixed discount. If we want to add a seasonal discount, we should do so without modifying the existing class.</p><p><strong>Without OCP:</strong></p><pre>public class DiscountService<br>{<br>    public decimal ApplyDiscount(decimal price)<br>    {<br>        // Fixed discount logic<br>        return price * 0.9m;<br>    }<br>}</pre><p><strong>With OCP:</strong></p><pre>public interface IDiscountStrategy<br>{<br>    decimal ApplyDiscount(decimal price);<br>}<br><br>public class FixedDiscountStrategy : IDiscountStrategy<br>{<br>    public decimal ApplyDiscount(decimal price)<br>    {<br>        return price * 0.9m;<br>    }<br>}<br><br>public class SeasonalDiscountStrategy : IDiscountStrategy<br>{<br>    public decimal ApplyDiscount(decimal price)<br>    {<br>        return price * 0.8m;<br>    }<br>}<br><br>public class DiscountService<br>{<br>    private readonly IDiscountStrategy _discountStrategy;<br><br>    public DiscountService(IDiscountStrategy discountStrategy)<br>    {<br>        _discountStrategy = discountStrategy;<br>    }<br><br>    public decimal ApplyDiscount(decimal price)<br>    {<br>        return _discountStrategy.ApplyDiscount(price);<br>    }<br>}</pre><p>By using the strategy pattern and introducing an interface for the discount strategy, we can add new discount types without modifying the existing DiscountService class.</p><h3>3. Liskov Substitution Principle (LSP)</h3><p>The Liskov Substitution Principle states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. This principle ensures that a subclass can stand in for its superclass.</p><p><strong>Example:</strong></p><p>Consider an ASP.NET Core application where we have a base class Shape with a method to calculate the area. We need to ensure that any derived class (like Rectangle and Square) can be used interchangeably with the base class.</p><p><strong>Without LSP:</strong></p><pre>public class Shape<br>{<br>    public virtual double Area() =&gt; 0;<br>}<br><br>public class Rectangle : Shape<br>{<br>    public double Width { get; set; }<br>    public double Height { get; set; }<br><br>    public override double Area()<br>    {<br>        return Width * Height;<br>    }<br>}<br><br>public class Square : Rectangle<br>{<br>    public override double Area()<br>    {<br>        return Width * Width;<br>    }<br>}</pre><p><strong>With LSP:</strong></p><pre>public abstract class Shape<br>{<br>    public abstract double Area();<br>}<br><br>public class Rectangle : Shape<br>{<br>    public double Width { get; set; }<br>    public double Height { get; set; }<br><br>    public override double Area()<br>    {<br>        return Width * Height;<br>    }<br>}<br><br>public class Square : Shape<br>{<br>    public double Side { get; set; }<br><br>    public override double Area()<br>    {<br>        return Side * Side;<br>    }<br>}</pre><p>By making Shape an abstract class and overriding the Area method in both Rectangle and Square, we ensure that both subclasses can be used interchangeably with the base class.</p><h3>4. Interface Segregation Principle (ISP)</h3><p>The Interface Segregation Principle states that no client should be forced to depend on methods it does not use. This principle promotes the creation of smaller, more specific interfaces rather than larger, general-purpose interfaces.</p><p><strong>Example:</strong></p><p>Consider an ASP.NET Core application with a Printer interface that has methods for printing and scanning. If a class needs only the printing functionality, it should not be forced to implement the scanning method.</p><p><strong>Without ISP:</strong></p><pre>public interface IPrinter<br>{<br>    void Print(string document);<br>    void Scan(string document);<br>}<br><br>public class Printer : IPrinter<br>{<br>    public void Print(string document)<br>    {<br>        // Print logic<br>    }<br><br>    public void Scan(string document)<br>    {<br>        // Scan logic<br>    }<br>}</pre><p><strong>With ISP:</strong></p><pre>public interface IPrinter<br>{<br>    void Print(string document);<br>}<br><br>public interface IScanner<br>{<br>    void Scan(string document);<br>}<br><br>public class Printer : IPrinter<br>{<br>    public void Print(string document)<br>    {<br>        // Print logic<br>    }<br>}<br><br>public class Scanner : IScanner<br>{<br>    public void Scan(string document)<br>    {<br>        // Scan logic<br>    }<br>}</pre><p>By splitting the IPrinter interface into IPrinter and IScanner, we ensure that classes only depend on the methods they actually use.</p><h3>5. Dependency Inversion Principle (DIP)</h3><p>The Dependency Inversion Principle states that high-level modules should not depend on low-level modules. Both should depend on abstractions. Additionally, abstractions should not depend on details. Details should depend on abstractions.</p><p><strong>Example:</strong></p><p>Consider an ASP.NET Core application where a NotificationService sends notifications via email and SMS. Hardcoding the dependencies within the service violates DIP.</p><p><strong>Without DIP:</strong></p><pre>public class EmailService<br>{<br>    public void SendEmail(string message)<br>    {<br>        // Email sending logic<br>    }<br>}<br><br>public class SmsService<br>{<br>    public void SendSms(string message)<br>    {<br>        // SMS sending logic<br>    }<br>}<br><br>public class NotificationService<br>{<br>    private readonly EmailService _emailService;<br>    private readonly SmsService _smsService;<br><br>    public NotificationService()<br>    {<br>        _emailService = new EmailService();<br>        _smsService = new SmsService();<br>    }<br><br>    public void Notify(string message)<br>    {<br>        _emailService.SendEmail(message);<br>        _smsService.SendSms(message);<br>    }<br>}</pre><p><strong>With DIP:</strong></p><pre>public interface INotificationService<br>{<br>    void Notify(string message);<br>}<br><br>public class EmailNotificationService : INotificationService<br>{<br>    public void Notify(string message)<br>    {<br>        // Email sending logic<br>    }<br>}<br><br>public class SmsNotificationService : INotificationService<br>{<br>    public void Notify(string message)<br>    {<br>        // SMS sending logic<br>    }<br>}<br><br>public class NotificationService<br>{<br>    private readonly INotificationService _notificationService;<br><br>    public NotificationService(INotificationService notificationService)<br>    {<br>        _notificationService = notificationService;<br>    }<br><br>    public void Notify(string message)<br>    {<br>        _notificationService.Notify(message);<br>    }<br>}</pre><p>By using interfaces for the notification services, we can inject the specific implementations (email, SMS) into the NotificationService without hardcoding the dependencies.</p><h3>Conclusion</h3><p>Understanding and applying the SOLID principles in your ASP.NET Core applications can significantly enhance the maintainability, scalability, and readability of your code. Each principle addresses a specific aspect of object-oriented design, promoting best practices that result in cleaner and more robust software. Whether you are dealing with a small project or a large enterprise system, adhering to these principles ensures that your code remains flexible and adaptable to change.</p><p>By examining examples both with and without the application of SOLID principles, we can clearly see the benefits of these guidelines. Implementing SRP helps in achieving modularity, OCP ensures extensibility, LSP guarantees substitutability, ISP fosters focused interfaces, and DIP promotes dependency management through abstractions. Adopting these principles leads to a more organized codebase that is easier to understand, extend, and maintain.</p><p>Incorporate these principles into your daily coding practices, and you’ll find that your software projects become more manageable, less error-prone, and better suited to evolving requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7de6ad8da124" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding DDD, TDD, and BDD: Differences, Use Cases, and Real-World Examples]]></title>
            <link>https://medium.com/@ieplt/understanding-ddd-tdd-and-bdd-differences-use-cases-and-real-world-examples-850364082c35?source=rss-ec97c01c22c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/850364082c35</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[bdd]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[İbrahim Emre POLAT]]></dc:creator>
            <pubDate>Fri, 21 Jun 2024 06:32:36 GMT</pubDate>
            <atom:updated>2024-06-21T06:32:36.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sgp27lcX_j58znjTX8IPzw.png" /></figure><p>In the world of software development, three popular methodologies often come into play: Domain-Driven Design (DDD), Test-Driven Development (TDD), and Behavior-Driven Development (BDD). Understanding the differences between these approaches and knowing when to use each can significantly impact the success of your project. This article will delve into the intricacies of DDD, TDD, and BDD, providing clear examples of their use cases, and offering guidance on choosing the right methodology for your next project.</p><h4>What is Domain-Driven Design (DDD)?</h4><p>Domain-Driven Design (DDD) is a methodology focused on modeling software to match the complex business domains it aims to solve. The primary goal of DDD is to create a shared understanding of the domain among all stakeholders, including developers, domain experts, and business analysts. DDD emphasizes collaboration, creating a ubiquitous language that all stakeholders can use to communicate effectively.</p><p>Key Concepts of <strong>DDD</strong>:</p><ul><li><strong>Domain</strong>: The sphere of knowledge and activity around which the application logic revolves.</li><li><strong>Entity</strong>: Objects that have a distinct identity that runs through time and different states.</li><li><strong>Value Object</strong>: Objects that describe some characteristic or attribute but have no conceptual identity.</li><li><strong>Aggregate</strong>: A cluster of domain objects that can be treated as a single unit.</li><li><strong>Repository</strong>: A mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects.</li></ul><p>Developer’s Role in <strong>DDD</strong>:</p><ul><li><strong>Collaborator</strong>: Work closely with domain experts and stakeholders to understand the domain and create a shared language.</li><li><strong>Modeler</strong>: Develop and refine the domain model, ensuring it accurately represents the business processes.</li><li><strong>Integrator</strong>: Implement and integrate the domain model into the application architecture, ensuring it aligns with business goals.</li></ul><p>Example Use Case for <strong>DDD</strong>:</p><p>Consider a shipping carrier system that manages various aspects such as shipments, routes, and tracking. Using DDD, you can model the domain entities (e.g., Shipment, Route, Tracking) and their relationships. By working closely with domain experts, you ensure that the software accurately reflects the business processes and terminologies.</p><h4>What is Test-Driven Development (TDD)?</h4><p>Test-Driven Development (TDD) is a software development process that relies on the repetition of a very short development cycle. First, the developer writes an initially failing automated test case that defines a desired improvement or new function. Then, they produce the minimum amount of code to pass that test, and finally refactor the new code to acceptable standards.</p><p>Key Concepts of <strong>TDD</strong>:</p><ul><li><strong>Red-Green-Refactor Cycle</strong>: Write a test that fails (Red), write code to make the test pass (Green), then refactor the code.</li><li><strong>Unit Tests</strong>: Tests that verify the functionality of a specific section of code.</li><li><strong>Mocking</strong>: Using simulated objects that mimic the behavior of real objects in controlled ways.</li></ul><p>Developer’s Role in <strong>TDD</strong>:</p><ul><li><strong>Tester</strong>: Write unit tests before writing the actual code, ensuring each function works correctly.</li><li><strong>Coder</strong>: Implement the minimum code required to pass the tests, focusing on small, incremental improvements.</li><li><strong>Refactorer</strong>: Continuously refactor the code to improve its structure and maintainability without changing its behavior.</li></ul><p>Example Use Case for <strong>TDD</strong>:</p><p>Imagine you are developing a financial application that handles transactions and balances. Using TDD, you would start by writing unit tests for each function, such as adding a transaction or calculating the balance. This ensures that every piece of code is tested and functions correctly, making the system reliable and easier to maintain.</p><h4>What is Behavior-Driven Development (BDD)?</h4><p>Behavior-Driven Development (BDD) is an extension of TDD that focuses on the behavioral aspect of the software. BDD encourages collaboration between developers, QA, and non-technical or business participants in a software project. BDD uses natural language constructs (Gherkin syntax) to describe the functionality in terms of user stories and acceptance criteria.</p><p>Key Concepts of BDD:</p><ul><li><strong>User Stories</strong>: Descriptions of software features from an end-user perspective.</li><li><strong>Gherkin Syntax</strong>: A language used to write BDD tests in a format that is easy to understand for non-technical stakeholders.</li></ul><p>Example:</p><pre>Feature: User Login<br>  Scenario: Successful login with valid credentials<br>    Given the user is on the login page<br>    When the user enters valid credentials<br>    Then the user is redirected to the dashboard</pre><ul><li><strong>Scenarios</strong>: Specific examples of how the software should behave in certain situations.</li></ul><p>Developer’s Role in BDD:</p><ul><li><strong>Collaborator</strong>: Work with QA and business stakeholders to define the expected behavior of the application.</li><li><strong>Scenario Writer</strong>: Write executable scenarios using Gherkin syntax that describe how the application should behave.</li><li><strong>Implementer</strong>: Develop the application to meet the specified behaviors, ensuring the scenarios pass.</li></ul><p>Example Use Case for BDD:</p><p>Suppose you are developing an e-commerce platform. BDD would be beneficial as it allows you to write scenarios in plain language that describe how users interact with the system, such as adding items to the cart, proceeding to checkout, and making a payment. This ensures that the development team, QA, and business stakeholders have a shared understanding of the desired behavior.</p><h4>Differences Between DDD, TDD, and BDD</h4><p><strong>Focus</strong>:</p><ul><li><strong>DDD</strong> centers around the domain and its complexities.</li><li><strong>TDD</strong> focuses on testing individual units of code.</li><li><strong>BDD</strong> emphasizes the behavior and interaction of the system from a user’s perspective.</li></ul><p><strong>Stakeholder Involvement</strong>:</p><ul><li><strong>DDD</strong> involves domain experts and business stakeholders in the modeling process.</li><li><strong>TDD</strong> is mainly developer-centric.</li><li><strong>BDD</strong> bridges the gap between technical and non-technical stakeholders.</li></ul><p><strong>Output</strong>:</p><ul><li><strong>DDD</strong> results in a robust domain model.</li><li><strong>TDD</strong> results in a comprehensive suite of unit tests.</li><li><strong>BDD</strong> produces executable specifications and acceptance tests.</li></ul><h4>Choosing the Right Methodology for Your Project</h4><p>When to Choose <strong>DDD</strong>:</p><ul><li><strong>Complex Domains</strong>: When the business domain is complex and requires deep understanding.</li><li><strong>High Collaboration</strong>: When there is a need for close collaboration between developers and domain experts.</li><li><strong>Long-Term Projects</strong>: Projects that will evolve over time and require a robust, flexible model.</li></ul><p>When to Choose <strong>TDD</strong>:</p><ul><li><strong>Critical Systems</strong>: When developing systems where reliability and correctness are critical (e.g., financial systems).</li><li><strong>Code Quality</strong>: When there is a strong emphasis on maintaining high code quality and preventing regressions.</li><li><strong>Refactoring</strong>: When frequent refactoring is needed to improve code without fear of breaking functionality.</li></ul><p>When to Choose <strong>BDD</strong>:</p><ul><li><strong>User-Focused Features</strong>: When the project involves features that directly impact user behavior and experience.</li><li><strong>Collaboration</strong>: When collaboration between developers, QA, and business stakeholders is crucial.</li><li><strong>Acceptance Testing</strong>: When acceptance criteria need to be clear and testable.</li></ul><h4>Real-World Example: Developing a Shipping Carrier System</h4><p>Imagine you are tasked with developing a shipping carrier system. Here’s how you might choose the appropriate methodology:</p><p><strong>Domain-Driven Design (DDD)</strong>:</p><ul><li><strong>Why</strong>: The shipping domain is complex, involving shipments, tracking, routes, and various business rules.</li><li><strong>Use Case</strong>: Using DDD, you would model entities like Shipment, Route, Tracking, and their relationships. Collaborating with domain experts ensures that the system accurately reflects the business processes.</li><li><strong>Outcome</strong>: A robust domain model that evolves with business needs.</li></ul><p><strong>Test-Driven Development (TDD)</strong>:</p><ul><li><strong>Why</strong>: Reliability is critical, as shipping systems must handle transactions accurately.</li><li><strong>Use Case</strong>: You start by writing unit tests for core functions like creating shipments, calculating routes, and updating tracking information. This ensures each function works correctly and helps catch bugs early.</li><li><strong>Outcome</strong>: A suite of unit tests that ensure code reliability and facilitate refactoring.</li></ul><p><strong>Behavior-Driven Development (BDD)</strong>:</p><ul><li><strong>Why</strong>: The system involves user interactions, such as booking shipments and tracking packages.</li><li><strong>Use Case</strong>: Using BDD, you define scenarios in plain language, describing how users book shipments, track their packages, and receive notifications. This aligns the development team and stakeholders on expected behaviors.</li><li><strong>Outcome</strong>: Executable specifications that validate the system’s behavior from a user’s perspective.</li></ul><h4>Basic Flow Example for Shipping Carrier System using BDD</h4><p>Feature: Booking a Shipment</p><pre>Scenario: Successful shipment booking<br>  Given the user is on the booking page<br>  When the user enters shipment details<br>  And the user confirms the booking<br>  Then the system creates a shipment record<br>  And the user receives a booking confirmation</pre><p>Feature: Tracking a Shipment</p><pre>Scenario: Tracking an existing shipment<br>  Given the user is on the tracking page<br>  When the user enters a valid tracking number<br>  Then the system displays the shipment status<br>  And the user sees the estimated delivery date</pre><h4>Conclusion</h4><p>Understanding the differences between DDD, TDD, and BDD, and knowing when to apply each, can significantly improve the development process and outcome of your projects. Whether you’re dealing with complex domains, ensuring code reliability, or focusing on user behavior, choosing the right methodology helps you achieve your project goals effectively. For a shipping carrier system, DDD helps model the complex domain, TDD ensures reliable code, and BDD clarifies user interactions and expectations. By leveraging these methodologies appropriately, you can build robust, maintainable, and user-friendly systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=850364082c35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Heap and Stack Memory in ASP.NET: Advantages, Usage, and Storing Costs of Value Types]]></title>
            <link>https://medium.com/@ieplt/understanding-heap-and-stack-memory-in-asp-net-advantages-usage-and-storing-costs-of-value-types-5431f27a2fba?source=rss-ec97c01c22c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5431f27a2fba</guid>
            <category><![CDATA[reference-type]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[İbrahim Emre POLAT]]></dc:creator>
            <pubDate>Mon, 17 Jun 2024 06:31:21 GMT</pubDate>
            <atom:updated>2024-06-17T06:31:21.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gAk4fpi95OIifHDj9py4zw.png" /></figure><p>Memory management is a critical aspect of efficient programming in ASP.NET. Understanding how data is stored in RAM, specifically in heap and stack memory, can help developers optimize their applications. This article delves into the differences between heap and stack memory, their advantages, usage of value types, storing costs, and provides practical code examples to illustrate these concepts.</p><h3>Heap Memory vs. Stack Memory</h3><p>In .NET, memory is divided into two main types: heap memory and stack memory. Both serve different purposes and have distinct characteristics.</p><h4>Stack Memory</h4><p><strong>Definition</strong>: Stack memory is used for static memory allocation and stores value types and function call memory. It follows a Last-In-First-Out (LIFO) approach.</p><p><strong>Characteristics</strong>:</p><ul><li>Fast access</li><li>Limited size</li><li>Automatically managed by the runtime</li></ul><p><strong>Usage</strong>: Typically used for local variables, function calls, and value types.</p><p><strong>Storing Cost</strong>: Low. The cost is mainly due to its limited size and the fast allocation/deallocation process. It has a fixed allocation size, making it very efficient in terms of access speed.</p><h4>Heap Memory</h4><p><strong>Definition</strong>: Heap memory is used for dynamic memory allocation, storing reference types and objects that need to persist beyond the scope of a function.</p><p><strong>Characteristics</strong>:</p><ul><li>Slower access compared to stack</li><li>Larger size</li><li>Requires garbage collection</li></ul><p><strong>Usage</strong>: Used for objects, arrays, and global variables.</p><p><strong>Storing Cost</strong>: Higher. The cost includes the overhead of dynamic memory management and garbage collection, which can introduce latency and fragmentation over time.</p><h3>Value Types: Usage and Storage</h3><p>In C#, value types are typically stored in stack memory, while reference types are stored in heap memory. However, there are exceptions based on the context of the value type usage.</p><h4>Value Types</h4><ul><li><strong>Examples</strong>: int, float, double, char, struct</li><li><strong>Storage</strong>: Primarily in stack memory, but can be stored in heap memory if they are part of an object or an array.</li></ul><h4>Reference Types</h4><ul><li><strong>Examples</strong>: class, array, string, delegate</li><li><strong>Storage</strong>: Always in heap memory.</li></ul><h3>Code Example</h3><p>Let’s look at a practical example to illustrate how value types and reference types are stored in heap and stack memory.</p><pre>using System;<br><br>namespace MemoryDemo<br>{<br>    public class Program<br>    {<br>        public static void Main(string[] args)<br>        {<br>            int valueType = 42; // Stored in stack<br>            MyClass referenceType = new MyClass(); // Stored in heap<br>            <br>            Console.WriteLine($&quot;Value Type: {valueType}&quot;);<br>            Console.WriteLine($&quot;Reference Type: {referenceType.Value}&quot;);<br>        }<br>    }<br><br>    public class MyClass<br>    {<br>        public int Value { get; set; }<br><br>        public MyClass()<br>        {<br>            Value = 100; // Value is stored in heap because it&#39;s part of a reference type<br>        }<br>    }<br>}</pre><h3>Advantages and Disadvantages of Heap and Stack Memory</h3><p>To better understand the pros and cons of heap and stack memory, let’s look at a comparison table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*AbM51GGdVcqD48MO_mLXMw.png" /></figure><h3>Practical Use Cases</h3><p>Let’s consider a real-world example in software development. Suppose you’re developing a high-frequency trading application where speed is crucial. In this case, you’ll need to make careful decisions about memory storage for optimal performance.</p><ul><li><strong>Stack Memory</strong>: Use stack memory for storing temporary data that requires quick access, such as loop counters, method parameters, and local variables. For example, in a method that calculates moving averages for stock prices, the loop counters and temporary results should be stored in the stack for faster access.</li></ul><pre>public double CalculateMovingAverage(double[] prices)<br>{<br>    double sum = 0;<br>    int count = prices.Length;<br><br>    for (int i = 0; i &lt; count; i++)<br>    {<br>        sum += prices[i];<br>    }<br><br>    return sum / count;<br>}</pre><ul><li><strong>Heap Memory</strong>: Use heap memory for storing large datasets or objects that need to persist across multiple method calls. For example, an array of stock prices or a collection of trading orders should be stored in heap memory.</li></ul><pre>public class TradingOrder<br>{<br>    public int OrderId { get; set; }<br>    public double Price { get; set; }<br>    public int Quantity { get; set; }<br><br>    public TradingOrder(int orderId, double price, int quantity)<br>    {<br>        OrderId = orderId;<br>        Price = price;<br>        Quantity = quantity;<br>    }<br>}<br><br>public class OrderManager<br>{<br>    private List&lt;TradingOrder&gt; orders = new List&lt;TradingOrder&gt;();<br><br>    public void AddOrder(TradingOrder order)<br>    {<br>        orders.Add(order); // Stored in heap<br>    }<br><br>    public List&lt;TradingOrder&gt; GetOrders()<br>    {<br>        return orders;<br>    }<br>}</pre><h3>Conclusion</h3><p>Understanding how ASP.NET stores data in RAM using heap and stack memory is essential for optimizing performance and managing resources efficiently. By leveraging the advantages of each memory type, understanding their storing costs, and knowing where value types and reference types are stored, developers can write more efficient and robust applications.</p><p>By mastering these concepts, you can ensure that your ASP.NET applications are both performant and reliable, providing a solid foundation for building scalable web solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5431f27a2fba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Purpose in Writing an Article]]></title>
            <link>https://medium.com/@ieplt/my-purpose-in-writing-an-article-150654338745?source=rss-ec97c01c22c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/150654338745</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[lifetime-learner]]></category>
            <dc:creator><![CDATA[İbrahim Emre POLAT]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 06:32:32 GMT</pubDate>
            <atom:updated>2024-06-15T06:32:32.319Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQwFt7cvx--K1WmTGKLN1w.png" /></figure><p>When I first started learning ASP.NET, I was both excited and overwhelmed. The framework’s extensive features and capabilities made it difficult to find clear, concise resources. As I navigated through these challenges, I realized the importance of sharing what I learned to help others. This article explains my purpose in writing articles about ASP.NET Core, including my journey, the challenges I faced, and how my articles aim to facilitate learning for others.</p><h4>My Journey with ASP.NET</h4><p>My journey with ASP.NET began out of a desire to dive into web development. However, the learning curve was steep. I often struggled to find resources that provided practical, step-by-step guidance on the various features of ASP.NET Core. Despite these challenges, I persevered, investing significant time and effort to master the framework.</p><h4>Teaching and Sharing Knowledge</h4><p>As I became more proficient, I started teaching those around me. I discovered that explaining concepts to others not only reinforced my own understanding but also helped my colleagues and peers. This inspired me to take it a step further by sharing my knowledge through written articles. My goal is to provide resources that make learning ASP.NET Core easier for others, just as I wished for when I started.</p><h4>Facilitating Learning for Newcomers</h4><p>My articles are designed to help those who are new to ASP.NET Core or looking to explore its features. By sharing my experiences and solutions to common problems, I hope to make the learning process smoother and more accessible. I aim to create content that is straightforward and directly addresses the needs of developers, especially those just starting out.</p><h4>Specific Examples and Practical Solutions</h4><p>Occasionally, I will share articles on specific topics, such as USPS Address Validation, that are directly aimed at practical applications. These articles provide targeted solutions to real-world problems, making it easier for developers to implement these features in their projects. By focusing on practical examples, I aim to address the exact purposes and needs of developers.</p><h4>Lifelong Learning and Development</h4><p>Learning is an ongoing journey. Each time I encounter a new challenge or a concept I’ve never faced before, it adds to my experience and knowledge. This continuous learning process enriches my life and professional development. I am always eager to learn more, develop my skills, and grow as a developer. My hunger for knowledge drives me to explore new technologies and share my insights with others.</p><h4>Conclusion</h4><p>Writing articles about ASP.NET Core is my way of giving back to the developer community. By sharing what I’ve learned and providing clear, practical guidance, I hope to make the learning journey less daunting for others. Whether you’re just starting out or looking to deepen your knowledge of ASP.NET Core, my articles are here to help you along the way. Learning never ends, and as I continue to grow and face new challenges, I will keep sharing my knowledge to support others in their learning journeys.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=150654338745" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide to Using JSON and Newtonsoft.Json in .NET]]></title>
            <link>https://medium.com/@ieplt/comprehensive-guide-to-using-json-and-newtonsoft-json-in-net-ac67b7963e35?source=rss-ec97c01c22c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac67b7963e35</guid>
            <category><![CDATA[deserialization]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[newtonsoft]]></category>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[İbrahim Emre POLAT]]></dc:creator>
            <pubDate>Fri, 14 Jun 2024 06:32:33 GMT</pubDate>
            <atom:updated>2024-06-14T06:32:33.238Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ckJUkJUzvzsbAD0IPAm7Q.png" /></figure><h3>Comprehensive Guide to Using JSON and Newtonsoft.Json in .NET</h3><h3>Introduction to JSON</h3><p>JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. JSON is widely used for data exchange between a server and a web application, as well as in many other scenarios where structured data needs to be transmitted or stored.</p><h3>Why We Use JSON</h3><ul><li><strong>Human-Readable</strong>: JSON is written in a text format that is readable and easy to understand, which makes debugging and development straightforward.</li><li><strong>Language Independent</strong>: JSON is language-agnostic, meaning it can be used across different programming languages, making it ideal for cross-platform data interchange.</li><li><strong>Lightweight</strong>: JSON is compact and lightweight, which is efficient for data transmission over networks.</li><li><strong>Interoperability</strong>: JSON’s format is based on key-value pairs, making it compatible with many modern programming languages and libraries.</li></ul><h3>Common Use Cases for JSON</h3><p>JSON is used in various domains, each benefiting from its simplicity and versatility. Below are some common use cases with examples.</p><h3>Microservices</h3><p>In a microservices architecture, services often communicate with each other using message brokers like Kafka, RabbitMQ, and Azure Service Bus. These services need a standardized format to serialize and deserialize data, and JSON is commonly chosen for this purpose due to its aforementioned benefits.</p><p>For instance, when a microservice sends a message containing user information to another service, it often uses JSON to format this data. Here is an example of a JSON message:</p><pre>{<br>  &quot;userId&quot;: 12345,<br>  &quot;userName&quot;: &quot;john_doe&quot;,<br>  &quot;email&quot;: &quot;john.doe@example.com&quot;<br>}</pre><p>This JSON message can be published to a message queue or topic and consumed by another service, which will then deserialize it into a corresponding object.</p><h3>Web APIs</h3><p>RESTful APIs commonly use JSON to format data sent to and received from clients. For example, a weather API might return weather data in JSON format:</p><pre>{<br>  &quot;location&quot;: &quot;New York&quot;,<br>  &quot;temperature&quot;: &quot;20°C&quot;,<br>  &quot;conditions&quot;: &quot;Sunny&quot;<br>}</pre><p>A client application can then parse this JSON to display the weather information to users.</p><h3>Configuration Files</h3><p>Many applications use JSON to store configuration settings. For instance, a web application might have a configuration file named config.json that stores settings for connecting to a database:</p><pre>{<br>  &quot;database&quot;: {<br>    &quot;host&quot;: &quot;localhost&quot;,<br>    &quot;port&quot;: 5432,<br>    &quot;username&quot;: &quot;admin&quot;,<br>    &quot;password&quot;: &quot;secret&quot;<br>  },<br>  &quot;logging&quot;: {<br>    &quot;level&quot;: &quot;debug&quot;<br>  }<br>}</pre><p>This JSON file can be read by the application during startup to configure the database connection and logging levels.</p><h3>Data Storage</h3><p>NoSQL databases like MongoDB use JSON-like documents to store data. For example, a user document in a MongoDB collection might look like this:</p><pre>{<br>  &quot;_id&quot;: &quot;507f191e810c19729de860ea&quot;,<br>  &quot;username&quot;: &quot;johndoe&quot;,<br>  &quot;email&quot;: &quot;john.doe@example.com&quot;,<br>  &quot;created_at&quot;: &quot;2023-06-10T10:00:00Z&quot;<br>}</pre><p>This document format allows for flexible and dynamic schemas, which is a key advantage of NoSQL databases.</p><h3>Getting Data from Third-Party Services</h3><p>Many third-party services and APIs provide data in JSON format, allowing easy integration and data manipulation. For example, a stock market API might return the latest stock prices in JSON:</p><pre>{<br>  &quot;symbol&quot;: &quot;AAPL&quot;,<br>  &quot;price&quot;: 150.00,<br>  &quot;timestamp&quot;: &quot;2023-06-10T10:00:00Z&quot;<br>}</pre><p>Applications can consume this JSON data to display stock prices or perform further analysis.</p><h3>Mobile Applications</h3><p>JSON is widely used in mobile applications to transmit data between the server and the client. For example, a mobile app might send a request to a server to get a list of products, and the server responds with a JSON array of products:</p><pre>[<br>  {<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;Product 1&quot;,<br>    &quot;price&quot;: 19.99<br>  },<br>  {<br>    &quot;id&quot;: 2,<br>    &quot;name&quot;: &quot;Product 2&quot;,<br>    &quot;price&quot;: 29.99<br>  }<br>]</pre><p>The mobile app can then parse this JSON array to display the products in a list view.</p><h3>Serializing JSON with Newtonsoft.Json</h3><p>Serialization is the process of converting an object into a format that can be easily stored or transmitted. Newtonsoft.Json makes it simple to serialize .NET objects into JSON strings. Let’s explore how to serialize objects using Newtonsoft.Json.</p><h3>Basic Serialization</h3><p>To serialize an object into a JSON string, you can use the JsonConvert.SerializeObject method. Here&#39;s a basic example:</p><pre>using Newtonsoft.Json;<br>using System;<br><br>public class User<br>{<br>  public int UserId { get; set; }<br>  public string UserName { get; set; }<br>  public string Email { get; set; }<br>}<br><br>class Program<br>{<br>  static void Main()<br>  {<br>    User user = new User<br>    {<br>      UserId = 12345,<br>      UserName = &quot;john_doe&quot;,<br>      Email = &quot;john.doe@example.com&quot;<br>    };<br><br>    string json = JsonConvert.SerializeObject(user);<br>    Console.WriteLine(json);<br>  }<br>}</pre><p>In this example, the User object is serialized into a JSON string. The JsonConvert.SerializeObject method automatically converts the object&#39;s properties into JSON format.</p><h3>Formatting JSON Output</h3><p>You can format the JSON output to make it more readable by using the Formatting enum:</p><pre>string json = JsonConvert.SerializeObject(user, Formatting.Indented);<br>Console.WriteLine(json);</pre><p>This will produce a nicely formatted JSON string:</p><pre>{<br>  &quot;UserId&quot;: 12345,<br>  &quot;UserName&quot;: &quot;john_doe&quot;,<br>  &quot;Email&quot;: &quot;john.doe@example.com&quot;<br>}</pre><h3>Using JsonProperty Attribute</h3><p>Just as with deserialization, you can use the JsonProperty attribute to control how properties are serialized:</p><pre>public class User<br>{<br>  [JsonProperty(&quot;user_id&quot;)]<br>  public int UserId { get; set; }<br><br>  [JsonProperty(&quot;user_name&quot;)]<br>  public string UserName { get; set; }<br><br>  [JsonProperty(&quot;email_address&quot;)]<br>  public string Email { get; set; }<br>}<br><br>User user = new User<br>{<br>  UserId = 12345,<br>  UserName = &quot;john_doe&quot;,<br>  Email = &quot;john.doe@example.com&quot;<br>};<br><br>string json = JsonConvert.SerializeObject(user, Formatting.Indented);<br>Console.WriteLine(json);</pre><p>This will produce:</p><pre>{<br>  &quot;user_id&quot;: 12345,<br>  &quot;user_name&quot;: &quot;john_doe&quot;,<br>  &quot;email_address&quot;: &quot;john.doe@example.com&quot;<br>}</pre><h3>Handling Null Values</h3><p>You can control how null values are handled during serialization using the NullValueHandling setting:</p><pre>JsonSerializerSettings settings = new JsonSerializerSettings<br>{<br>  NullValueHandling = NullValueHandling.Ignore<br>};<br><br>string json = JsonConvert.SerializeObject(user, settings);<br>Console.WriteLine(json);</pre><p>If Email was null, it would be omitted from the JSON output.</p><h3>Custom Converters</h3><p>For more complex scenarios, you can create custom converters by inheriting from JsonConverter. This allows you to define custom serialization logic:</p><pre>public class DateTimeConverter : JsonConverter&lt;DateTime&gt;<br>{<br>  private readonly string _format = &quot;yyyy-MM-dd&quot;;<br><br>  public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)<br>  {<br>    writer.WriteValue(value.ToString(_format));<br>  }<br><br>  public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)<br>  {<br>    return DateTime.ParseExact((string)reader.Value, _format, null);<br>  }<br>}</pre><p>You can then use this custom converter in your class:</p><pre>public class Event<br>{<br>  public string Name { get; set; }<br><br>  [JsonConverter(typeof(DateTimeConverter))]<br>  public DateTime Date { get; set; }<br>}<br><br>Event ev = new Event<br>{<br>  Name = &quot;Conference&quot;,<br>  Date = new DateTime(2024, 6, 10)<br>};<br><br>string json = JsonConvert.SerializeObject(ev, Formatting.Indented);<br>Console.WriteLine(json);</pre><p>This will produce:</p><pre>{<br>  &quot;Name&quot;: &quot;Conference&quot;,<br>  &quot;Date&quot;: &quot;2024-06-10&quot;<br>}</pre><h3>Deserializing JSON with Newtonsoft.Json</h3><p>Deserialization is the process of converting a JSON string back into an object. Newtonsoft.Json makes it simple to deserialize JSON strings into .NET objects. Let’s explore how to deserialize JSON into objects using Newtonsoft.Json.</p><h3>Basic Deserialization</h3><p>To deserialize JSON into a C# object, you can use the JsonConvert.DeserializeObject&lt;T&gt; method. Here&#39;s a basic example:</p><pre>using Newtonsoft.Json;<br>using System;<br><br>public class User<br>{<br>  public int UserId { get; set; }<br>  public string UserName { get; set; }<br>  public string Email { get; set; }<br>}<br><br>class Program<br>{<br>  static void Main()<br>  {<br>    string json = &quot;{\&quot;UserId\&quot;:12345, \&quot;UserName\&quot;:\&quot;john_doe\&quot;, \&quot;Email\&quot;:\&quot;john.doe@example.com\&quot;}&quot;;<br>    User user = JsonConvert.DeserializeObject&lt;User&gt;(json);<br><br>    Console.WriteLine($&quot;UserId: {user.UserId}, UserName: {user.UserName}, Email: {user.Email}&quot;);<br>  }<br>}</pre><p>In this example, the JSON string is deserialized into an instance of the User class. The JsonConvert.DeserializeObject&lt;T&gt; method automatically maps the JSON properties to the corresponding properties of the User object.</p><h3>Using JsonProperty Attribute</h3><p>In some cases, JSON property names may not match the property names in your C# class. You can use the JsonProperty attribute to map JSON properties to class properties:</p><pre>public class User<br>{<br>  [JsonProperty(&quot;user_id&quot;)]<br>  public int UserId { get; set; }<br>  <br>  [JsonProperty(&quot;user_name&quot;)]<br>  public string UserName { get; set; }<br>  <br>  [JsonProperty(&quot;email_address&quot;)]<br>  public string Email { get; set; }<br>}</pre><p>This ensures that the JSON properties are correctly mapped even if their names differ from the class properties.</p><h3>Handling Missing or Extra Properties</h3><p>By default, Newtonsoft.Json will ignore extra properties in the JSON that are not present in the target class. However, you can handle these scenarios explicitly using settings like MissingMemberHandling and DefaultValueHandling:</p><pre>JsonSerializerSettings settings = new JsonSerializerSettings<br>{<br>  MissingMemberHandling = MissingMemberHandling.Error,<br>  DefaultValueHandling = DefaultValueHandling.Populate<br>};<br><br>User user = JsonConvert.DeserializeObject&lt;User&gt;(json, settings);</pre><h3>Null Value Handling</h3><p>You can control how null values are handled during deserialization using the NullValueHandling setting:</p><pre>JsonSerializerSettings settings = new JsonSerializerSettings<br>{<br>  NullValueHandling = NullValueHandling.Ignore<br>};<br><br>User user = JsonConvert.DeserializeObject&lt;User&gt;(json, settings);</pre><h3>Custom Converters</h3><p>For more complex scenarios, you can create custom converters by inheriting from JsonConverter. This allows you to define custom serialization and deserialization logic:</p><pre>public class DateTimeConverter : JsonConverter&lt;DateTime&gt;<br>{<br>  private readonly string _format = &quot;yyyy-MM-dd&quot;;<br><br>  public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)<br>  {<br>    writer.WriteValue(value.ToString(_format));<br>  }<br><br>  public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)<br>  {<br>    return DateTime.ParseExact((string)reader.Value, _format, null);<br>  }<br>}</pre><p>You can then use this custom converter in your class:</p><pre>public class Event<br>{<br>  public string Name { get; set; }<br>  <br>  [JsonConverter(typeof(DateTimeConverter))]<br>  public DateTime Date { get; set; }<br>}</pre><h3>Conclusion</h3><p>Newtonsoft.Json is a powerful and flexible library for handling JSON in .NET applications. Its wide array of features and settings allows for precise control over the serialization and deserialization process, making it suitable for a variety of use cases, from simple data mapping to complex custom conversions.</p><p>Understanding how to effectively use Newtonsoft.Json can greatly enhance your ability to work with JSON data in .NET, ensuring robust and maintainable code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac67b7963e35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding RDBMS and Working with Entity Framework in ASP.NET Core]]></title>
            <link>https://medium.com/@ieplt/understanding-rdbms-and-working-with-entity-framework-in-asp-net-core-f84e4a584976?source=rss-ec97c01c22c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f84e4a584976</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[mssql]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[İbrahim Emre POLAT]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 06:32:31 GMT</pubDate>
            <atom:updated>2024-06-12T06:32:31.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sPtoxH-ST-ROejgwNlo-oA.png" /><figcaption>y</figcaption></figure><p>Relational Database Management Systems (RDBMS) are foundational to modern application development. They provide a structured way to store, retrieve, and manage data. Entity Framework (EF) is an Object-Relational Mapper (ORM) that simplifies data access in ASP.NET Core applications by allowing developers to work with data using .NET objects. In this article, we’ll explore the principles of RDBMS and demonstrate how to use Entity Framework to map objects to database fields in ASP.NET Core.</p><h4>What is an RDBMS?</h4><p>A Relational Database Management System (RDBMS) is a type of database management system that stores data in a structured format using rows and columns. This structure allows for the efficient querying and manipulation of data using Structured Query Language (SQL). Examples of popular RDBMS include Microsoft SQL Server, MySQL, PostgreSQL, and Oracle Database.</p><p><strong>Key Features of RDBMS:</strong></p><ul><li><strong>Tables:</strong> Data is organized into tables, where each table consists of rows and columns.</li><li><strong>Relationships:</strong> Tables can be related to each other through foreign keys, enabling complex queries and data integrity.</li><li><strong>Transactions:</strong> RDBMS support transactions, ensuring that a series of operations either complete successfully or fail together, maintaining data consistency.</li><li><strong>Normalization:</strong> The process of organizing data to reduce redundancy and improve data integrity.</li></ul><h4>Entity Framework Overview</h4><p>Entity Framework (EF) is an ORM that enables .NET developers to work with a database using .NET objects. EF abstracts the underlying database and allows developers to interact with it using LINQ (Language Integrated Query), eliminating the need for most of the boilerplate SQL code.</p><p><strong>Advantages of Using Entity Framework:</strong></p><ul><li><strong>Productivity:</strong> Reduces the amount of data access code developers need to write.</li><li><strong>Maintainability:</strong> Easier to maintain and evolve applications by working with high-level abstractions.</li><li><strong>Compatibility:</strong> Supports multiple database providers, allowing for flexibility in database choice.</li></ul><h4>Setting Up Entity Framework in ASP.NET Core</h4><p><strong>Install Entity Framework Core:</strong> Start by adding the EF Core package to your ASP.NET Core project for each RDBMS you plan to use. You can do this via the NuGet Package Manager or the .NET CLI:</p><p><strong>For SQL Server:</strong></p><pre>dotnet add package Microsoft.EntityFrameworkCore.SqlServer</pre><p><strong>For PostgreSQL:</strong></p><pre>dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL</pre><p><strong>For Oracle:</strong></p><pre>dotnet add package Oracle.EntityFrameworkCore</pre><p><strong>Using the Options Pattern for Configuration:</strong> The options pattern in ASP.NET Core is a preferred way to manage settings. This pattern can be used to retrieve the connection string.</p><p><strong>Add a Configuration Class:</strong></p><pre>public class DatabaseSettings<br>{<br>    public string ConnectionString { get; set; }<br>}</pre><p><strong>Configure the Settings in </strong><strong>appsettings.json:</strong></p><pre>{<br>    &quot;DatabaseSettings&quot;: {<br>        &quot;ConnectionString&quot;: &quot;YourConnectionStringHere&quot;<br>    }<br>}</pre><p><strong>Register the Configuration in </strong><strong>Startup.cs:</strong></p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.Configure&lt;DatabaseSettings&gt;(Configuration.GetSection(&quot;DatabaseSettings&quot;));<br><br>    services.AddDbContext&lt;AppDbContext&gt;((serviceProvider, options) =&gt;<br>    {<br>        var dbSettings = serviceProvider.GetRequiredService&lt;IOptions&lt;DatabaseSettings&gt;&gt;().Value;<br>        options.UseSqlServer(dbSettings.ConnectionString);<br>        // Use Npgsql for PostgreSQL<br>        // options.UseNpgsql(dbSettings.ConnectionString);<br>        // Use Oracle for Oracle Database<br>        // options.UseOracle(dbSettings.ConnectionString);<br>    });<br><br>    services.AddControllersWithViews();<br>}</pre><p><strong>Define Your Model Classes with Data Annotations:</strong></p><p>Model classes represent the tables in your database. Each property in a model class corresponds to a column in the table. Data Annotations are attributes you can apply to your model classes and properties to configure the mappings.</p><pre>public class Product<br>{<br>    [Key]<br>    public int Id { get; set; }<br><br>    [Required]<br>    [MaxLength(100)]<br>    public string Name { get; set; }<br><br>    [Column(TypeName = &quot;decimal(18,2)&quot;)]<br>    public decimal Price { get; set; }<br>}<br><br>public class Order<br>{<br>    [Key]<br>    public int Id { get; set; }<br><br>    [Required]<br>    public DateTime OrderDate { get; set; }<br><br>    [Required]<br>    public int Quantity { get; set; }<br><br>    [Column(TypeName = &quot;decimal(18,2)&quot;)]<br>    public decimal TotalPrice { get; set; }<br><br>    public virtual ICollection&lt;Product&gt; Products { get; set; }<br>}</pre><p><strong>Create a Database Context:</strong></p><p>The DbContext class is the bridge between your application and the database. It manages the entity objects during runtime, including querying, saving, and updating data. For flexibility, the connection string can be passed through configuration.</p><pre>public class AppDbContext : DbContext<br>{<br>    public DbSet&lt;Product&gt; Products { get; set; }<br>    public DbSet&lt;Order&gt; Orders { get; set; }<br><br>    public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options) : base(options) { }<br><br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        modelBuilder.Entity&lt;Product&gt;(entity =&gt;<br>        {<br>            entity.HasKey(e =&gt; e.Id);<br>            entity.Property(e =&gt; e.Name).IsRequired().HasMaxLength(100);<br>            entity.Property(e =&gt; e.Price).HasColumnType(&quot;decimal(18,2)&quot;);<br>        });<br><br>        modelBuilder.Entity&lt;Order&gt;(entity =&gt;<br>        {<br>            entity.HasKey(e =&gt; e.Id);<br>            entity.Property(e =&gt; e.OrderDate).IsRequired();<br>            entity.Property(e =&gt; e.Quantity).IsRequired();<br>            entity.Property(e =&gt; e.TotalPrice).HasColumnType(&quot;decimal(18,2)&quot;);<br><br>            entity.HasMany(e =&gt; e.Products)<br>                  .WithMany();<br>        });<br>    }<br>}</pre><h4>Performing CRUD Operations</h4><p>Once your models and DbContext are set up, you can perform CRUD (Create, Read, Update, Delete) operations using EF Core. It’s important to use the using statement to ensure that the DbContext is properly disposed of after use. This ensures that database connections are released and resources are cleaned up, preventing potential memory leaks and other issues.</p><p><strong>Create:</strong></p><pre>using (var context = new AppDbContext(options))<br>{<br>    var product1 = new Product { Name = &quot;Laptop&quot;, Price = 1200m };<br>    var product2 = new Product { Name = &quot;Mouse&quot;, Price = 20m };<br>    context.Products.AddRange(product1, product2);<br>    context.SaveChanges();<br><br>    var order = new Order <br>    { <br>        OrderDate = DateTime.Now, <br>        Quantity = 2, <br>        TotalPrice = 1220m,<br>        Products = new List&lt;Product&gt; { product1, product2 }<br>    };<br>    context.Orders.Add(order);<br>    context.SaveChanges();<br>}</pre><p><strong>Read:</strong></p><pre>using (var context = new AppDbContext(options))<br>{<br>    var orders = context.Orders<br>                        .Include(o =&gt; o.Products)<br>                        .ToList();<br>    foreach (var order in orders)<br>    {<br>        Console.WriteLine($&quot;Order {order.Id}:&quot;);<br>        foreach (var product in order.Products)<br>        {<br>            Console.WriteLine($&quot;- {product.Name} - {product.Price}&quot;);<br>        }<br>        Console.WriteLine($&quot;Total: {order.TotalPrice}&quot;);<br>    }<br>}</pre><p><strong>Update:</strong></p><pre>using (var context = new AppDbContext(options))<br>{<br>    var order = context.Orders.Include(o =&gt; o.Products).FirstOrDefault(o =&gt; o.Id == 1);<br>    if (order != null)<br>    {<br>        var additionalProduct = new Product { Name = &quot;Keyboard&quot;, Price = 50m };<br>        context.Products.Add(additionalProduct);<br>        order.Products.Add(additionalProduct);<br>        order.Quantity += 1;<br>        order.TotalPrice += additionalProduct.Price;<br>        context.SaveChanges();<br>    }<br>}</pre><p><strong>Delete:</strong></p><pre>using (var context = new AppDbContext(options))<br>{<br>    var order = context.Orders.Include(o =&gt; o.Products).FirstOrDefault(o =&gt; o.Id == 1);<br>    if (order != null)<br>    {<br>        context.Orders.Remove(order);<br>        context.SaveChanges();<br>    }<br>}</pre><h4>Why Use using with DbContext?</h4><p>The using statement ensures that the DbContext object is disposed of correctly after use. When the code execution leaves the using block, the Dispose method of the DbContext is automatically called. This method releases all the resources used by the DbContext, such as open database connections. Properly disposing of DbContext instances is crucial for resource management and performance, especially in web applications where database connections are limited.</p><h4>Querying Data with LINQ</h4><p>Entity Framework allows querying data using LINQ (Language Integrated Query), which provides a more readable and concise syntax compared to raw SQL.</p><p><strong>Example Queries:</strong></p><ul><li><strong>Simple Query:</strong></li></ul><pre>using (var context = new AppDbContext(options))<br>{<br>    var products = from p in context.Products<br>                   where p.Price &gt; 100<br>                   select p;<br><br>    foreach (var product in products)<br>    {<br>        Console.WriteLine($&quot;{product.Id} - {product.Name} - {product.Price}&quot;);<br>    }<br>}</pre><p><strong>Join Query:</strong></p><pre>using (var context = new AppDbContext(options))<br>{<br>    var orders = from o in context.Orders<br>                 join p in context.Products on o.Products.FirstOrDefault().Id equals p.Id<br>                 select new { o.Id, p.Name, o.Quantity, o.TotalPrice };<br><br>    foreach (var order in orders)<br>    {<br>        Console.WriteLine($&quot;Order {order.Id}: {order.Name} x {order.Quantity} - {order.TotalPrice}&quot;);<br>    }<br>}</pre><h4>Inspecting and Managing Your Database</h4><p>To inspect and manage your database, you can use tools like SQL Server Management Studio (SSMS) for SQL Server, pgAdmin for PostgreSQL, or Oracle SQL Developer for Oracle Database. These tools allow you to run SQL queries, view table structures, and manage database objects.</p><h4>Conclusion</h4><p>Entity Framework Core provides a powerful and flexible way to interact with relational databases in ASP.NET Core applications. By understanding how to map your objects to database fields and using a well-structured DbContext, you can leverage the full potential of EF Core to build robust and maintainable applications. Whether you’re using SQL Server, PostgreSQL, or Oracle, EF Core simplifies the complexities of data access, allowing you to focus on your application’s business logic. Properly managing DbContext instances and utilizing the using statement ensures efficient resource management and optimal performance in your applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f84e4a584976" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Your ASP.NET]]></title>
            <link>https://medium.com/@ieplt/securing-your-asp-net-dbcb51d56334?source=rss-ec97c01c22c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbcb51d56334</guid>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[api-security]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[middleware]]></category>
            <dc:creator><![CDATA[İbrahim Emre POLAT]]></dc:creator>
            <pubDate>Mon, 10 Jun 2024 05:32:28 GMT</pubDate>
            <atom:updated>2024-06-10T05:32:28.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqhvZanxBMUeQ5wWpSNRYA.png" /></figure><h3>Securing Your ASP.NET Core API with API Key and Token Middleware Using PostgreSQL and Entity Framework</h3><p>Securing your API is essential to prevent unauthorized access and ensure data integrity. Using API keys and tokens is a common method for protecting APIs. In this article, we’ll walk through how to implement API key and token authorization as middleware in an ASP.NET Core Web API project named AuthorizationWithMiddleware. We&#39;ll use PostgreSQL and Entity Framework for user login and generate API keys with a specific lifetime.</p><p>Before diving into the implementation, ensure you have the following prerequisites:</p><ul><li>.NET 6.0 SDK or later</li><li>Visual Studio 2022 or later (or any other IDE that supports .NET 6.0)</li><li>PostgreSQL database</li></ul><p>NuGet packages:</p><ul><li>Microsoft.EntityFrameworkCore</li><li>Microsoft.EntityFrameworkCore.Design</li><li>Npgsql.EntityFrameworkCore.PostgreSQL</li><li>Swashbuckle.AspNetCore</li><li>Microsoft.AspNetCore.Authentication</li><li>Microsoft.AspNetCore.Authorization</li></ul><p><strong>Setting Up the Project</strong></p><p><strong>Create a New ASP.NET Core Web API Project:</strong></p><p>Open Visual Studio and create a new ASP.NET Core Web Application named AuthorizationWithMiddleware. Choose the &quot;API&quot; template and click &quot;Create&quot;.</p><p><strong>Install Required Packages:</strong></p><p>Open the NuGet Package Manager and install the following packages:</p><ul><li>Microsoft.EntityFrameworkCore</li><li>Microsoft.EntityFrameworkCore.Design</li><li>Npgsql.EntityFrameworkCore.PostgreSQL</li><li>Swashbuckle.AspNetCore</li><li>Microsoft.AspNetCore.Authentication</li><li>Microsoft.AspNetCore.Authorization</li></ul><p><strong>Configure PostgreSQL and Entity Framework</strong></p><p>Add Connection String in appsettings.json:</p><pre>{<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;DefaultConnection&quot;: &quot;Host=localhost;Database=yourdatabase;Username=yourusername;Password=yourpassword&quot;<br>  },<br>  &quot;ApiSettings&quot;: {<br>    &quot;ApiKeyLifetimeMinutes&quot;: 60<br>  }<br>}</pre><p><strong>Create the Data Context and Models:</strong></p><p>Create a new folder named Models and add the following classes:</p><ul><li><strong>Models/User.cs</strong>:</li></ul><pre>using System;<br>using System.ComponentModel.DataAnnotations;<br><br>namespace AuthorizationWithMiddleware.Models<br>{<br>    public class User<br>    {<br>        [Key]<br>        public int Id { get; set; }<br>        public string Username { get; set; }<br>        public string Password { get; set; }<br>    }<br>}</pre><p><strong>Models/ApiKey.cs</strong>:</p><pre>using System;<br>using System.ComponentModel.DataAnnotations;<br><br>namespace AuthorizationWithMiddleware.Models<br>{<br>    public class ApiKey<br>    {<br>        [Key]<br>        public int Id { get; set; }<br>        public string Key { get; set; }<br>        public DateTime Expiration { get; set; }<br>        public int UserId { get; set; }<br>        public User User { get; set; }<br>    }<br>}</pre><p>Create the Data Context:</p><p>Create a new folder named Data and add the following class:</p><p><strong>Data/AppDbContext.cs</strong>:</p><pre>using Microsoft.EntityFrameworkCore;<br>using AuthorizationWithMiddleware.Models;<br><br>namespace AuthorizationWithMiddleware.Data<br>{<br>    public class AppDbContext : DbContext<br>    {<br>        public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options) : base(options) { }<br><br>        public DbSet&lt;User&gt; Users { get; set; }<br>        public DbSet&lt;ApiKey&gt; ApiKeys { get; set; }<br><br>        protected override void OnModelCreating(ModelBuilder modelBuilder)<br>        {<br>            base.OnModelCreating(modelBuilder);<br><br>            // Seed a test user<br>            modelBuilder.Entity&lt;User&gt;().HasData(<br>                new User<br>                {<br>                    Id = 1,<br>                    Username = &quot;testuser&quot;,<br>                    Password = &quot;testpassword&quot; <br>                }<br>            );<br>        }<br>    }<br>}</pre><p><strong>Create the Settings Class:</strong></p><p>Create a new folder named Settings and add the following class:</p><p><strong>Settings/ApiSettings.cs</strong>:</p><pre>namespace AuthorizationWithMiddleware.Settings<br>{<br>    public class ApiSettings<br>    {<br>        public int ApiKeyLifetimeMinutes { get; set; }<br>    }<br>}</pre><p><strong>Configure Services in </strong><strong>Program.cs:</strong></p><p>Update your Program.cs file to add the database context and configure Swagger:</p><pre><br>using Microsoft.EntityFrameworkCore;<br>using AuthorizationWithMiddleware.Data;<br>using AuthorizationWithMiddleware.Models;<br>using AuthorizationWithMiddleware.Settings;<br>using AuthorizationWithMiddleware.Filters;<br>using Microsoft.Extensions.Options;<br>using Swashbuckle.AspNetCore.SwaggerGen;<br>using Microsoft.OpenApi.Models;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>// Add services to the container.<br>builder.Services.AddControllers();<br>builder.Services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>    options.UseNpgsql(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));<br>builder.Services.Configure&lt;ApiSettings&gt;(builder.Configuration.GetSection(&quot;ApiSettings&quot;));<br>builder.Services.AddScoped&lt;IUserService, UserService&gt;();<br><br>// Add Swagger services<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen(c =&gt;<br>{<br>    c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;AuthorizationWithMiddleware API&quot;, Version = &quot;v1&quot; });<br>    c.OperationFilter&lt;AddRequiredHeaderParameter&gt;();<br>});<br><br>var app = builder.Build();<br><br>// Configure the HTTP request pipeline.<br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}<br><br>app.UseHttpsRedirection();<br><br>app.UseAuthorization();<br><br>// Add the custom API Key Middleware<br>app.UseMiddleware&lt;ApiKeyMiddleware&gt;();<br><br>app.MapControllers();<br><br>app.Run();</pre><p>C<strong>reate the Operation Filter:</strong></p><p>Create a new folder named Filters and add the following class:</p><p><strong>Filters/AddRequiredHeaderParameter.cs</strong>:</p><pre>using Microsoft.OpenApi.Models;<br>using Swashbuckle.AspNetCore.SwaggerGen;<br><br>public class AddRequiredHeaderParameter : IOperationFilter<br>{<br>    public void Apply(OpenApiOperation operation, OperationFilterContext context)<br>    {<br>        if (operation.Parameters == null)<br>            operation.Parameters = new List&lt;OpenApiParameter&gt;();<br><br>        if (context.ApiDescription.HttpMethod != &quot;POST&quot; ||<br>            !context.ApiDescription.RelativePath.Contains(&quot;auth/login&quot;))<br>        {<br>            operation.Parameters.Add(new OpenApiParameter<br>            {<br>                Name = &quot;ApiKey&quot;,<br>                In = ParameterLocation.Header,<br>                Required = true<br>            });<br>        }<br>    }<br>}</pre><p><strong>Create User and API Key Services</strong></p><p><strong>Create Interfaces:</strong></p><p>Create a new folder named Services and add the following interface:</p><p><strong>Services/IUserService.cs</strong>:</p><pre>public interface IUserService<br>{<br>    User Authenticate(string username, string password);<br>    ApiKey GenerateApiKey(User user);<br>    bool ValidateApiKey(string apiKey);<br>}</pre><p><strong>Implement Services:</strong></p><p>Create a file named UserService.cs in the Services folder:</p><p><strong>Services/UserService.cs</strong>:</p><pre>using System;<br>using System.Linq;<br>using Microsoft.Extensions.Options;<br>using AuthorizationWithMiddleware.Data;<br>using AuthorizationWithMiddleware.Models;<br>using AuthorizationWithMiddleware.Settings;<br><br>public class UserService : IUserService<br>{<br>    private readonly AppDbContext _context;<br>    private readonly ApiSettings _apiSettings;<br><br>    public UserService(AppDbContext context, IOptions&lt;ApiSettings&gt; apiSettings)<br>    {<br>        _context = context;<br>        _apiSettings = apiSettings.Value;<br>    }<br><br>    public User Authenticate(string username, string password)<br>    {<br>        return _context.Users.SingleOrDefault(u =&gt; u.Username == username &amp;&amp; u.Password == password);<br>    }<br><br>    public ApiKey GenerateApiKey(User user)<br>    {<br>        var apiKey = new ApiKey<br>        {<br>            Key = Guid.NewGuid().ToString(),<br>            Expiration = DateTime.UtcNow.AddMinutes(_apiSettings.ApiKeyLifetimeMinutes),<br>            UserId = user.Id<br>        };<br>        _context.ApiKeys.Add(apiKey);<br>        _context.SaveChanges();<br>        return apiKey;<br>    }<br><br>    public bool ValidateApiKey(string apiKey)<br>    {<br>        var key = _context.ApiKeys.SingleOrDefault(k =&gt; k.Key == apiKey);<br>        return key != null &amp;&amp; key.Expiration &gt; DateTime.UtcNow;<br>    }<br>}</pre><p><strong>Implement API Key Middleware</strong></p><p><strong>Create the Middleware Class:</strong></p><p>Create a file named ApiKeyMiddleware.cs in the root of your project:</p><p><strong>ApiKeyMiddleware.cs</strong>:</p><pre>using Microsoft.AspNetCore.Http;<br>using System.Threading.Tasks;<br>using AuthorizationWithMiddleware.Services;<br>using Microsoft.AspNetCore.Mvc.Controllers;<br><br>public class ApiKeyMiddleware<br>{<br>    private readonly RequestDelegate _next;<br><br>    public ApiKeyMiddleware(RequestDelegate next)<br>    {<br>        _next = next;<br>    }<br><br>    public async Task InvokeAsync(HttpContext context, IUserService userService)<br>    {<br>        // Check if the request is for the login endpoint<br>        var endpoint = context.GetEndpoint();<br>        if (endpoint != null)<br>        {<br>            var descriptor = endpoint.Metadata.GetMetadata&lt;ControllerActionDescriptor&gt;();<br>            if (descriptor != null &amp;&amp; descriptor.ControllerName == &quot;Auth&quot; &amp;&amp; descriptor.ActionName == &quot;Login&quot;)<br>            {<br>                await _next(context);<br>                return;<br>            }<br>        }<br><br>        // Proceed with API key validation<br>        if (!context.Request.Headers.TryGetValue(&quot;ApiKey&quot;, out var extractedApiKey))<br>        {<br>            context.Response.StatusCode = 401;<br>            await context.Response.WriteAsync(&quot;API Key is required.&quot;);<br>            return;<br>        }<br><br>        if (!userService.ValidateApiKey(extractedApiKey))<br>        {<br>            context.Response.StatusCode = 401;<br>            await context.Response.WriteAsync(&quot;Unauthorized client.&quot;);<br>            return;<br>        }<br><br>        await _next(context);<br>    }<br>}</pre><p><strong>Create Authentication and Test Endpoints</strong></p><p><strong>Create a Login Controller:</strong></p><p>Create a new folder named Controllers and add the following controller:</p><p><strong>Controllers/AuthController.cs</strong>:</p><pre>using Microsoft.AspNetCore.Mvc;<br>using AuthorizationWithMiddleware.Services;<br>using AuthorizationWithMiddleware.Models;<br><br>[Route(&quot;api/[controller]&quot;)]<br>[ApiController]<br>public class AuthController : ControllerBase<br>{<br>    private readonly IUserService _userService;<br><br>    public AuthController(IUserService userService)<br>    {<br>        _userService = userService;<br>    }<br><br>    [HttpPost(&quot;login&quot;)]<br>    public IActionResult Login([FromBody] User user)<br>    {<br>        var authenticatedUser = _userService.Authenticate(user.Username, user.Password);<br>        if (authenticatedUser == null)<br>            return Unauthorized(&quot;Invalid username or password&quot;);<br><br>        var apiKey = _userService.GenerateApiKey(authenticatedUser);<br>        return Ok(new { ApiKey = apiKey.Key });<br>    }<br>}</pre><p>Create a Test Controller:</p><p>Create a new controller file TestController.cs in the Controllers folder:</p><p><strong>Controllers/TestController.cs</strong>:</p><pre>using Microsoft.AspNetCore.Mvc;<br><br>[Route(&quot;api/[controller]&quot;)]<br>[ApiController]<br>public class TestController : ControllerBase<br>{<br>    [HttpGet]<br>    public IActionResult Get()<br>    {<br>        return Ok(&quot;API is secured with API Key.&quot;);<br>    }<br>}</pre><p><strong>Running the Program</strong></p><p><strong>Open PowerShell in the Project Directory:</strong></p><p>Open PowerShell and navigate to the project directory.</p><pre>cd path\to\your\project</pre><p><strong>Add Migrations and Update Database:</strong></p><p>Run the following commands in PowerShell:</p><pre>dotnet ef migrations add InitialCreate<br>dotnet ef database update</pre><p><strong>Test with Postman or Swagger:</strong></p><p>Open Postman and create a new POST request to https://localhost:5001/api/auth/login with the following JSON body:</p><pre>{<br>    &quot;Username&quot;: &quot;testuser&quot;,<br>    &quot;Password&quot;: &quot;testpassword&quot;<br>}</pre><ul><li>Copy the ApiKey from the response.</li><li>Create a new GET request to <a href="https://localhost:5001/api/test.">https://localhost:5001/api/test.</a></li><li>Add a header ApiKey with the copied value.</li><li>Send the request.</li></ul><p>If the API key is correct and valid, you should receive a response saying, API is Secured with API Key.If not, you will receive an unauthorized response.</p><p><strong>Conclusion</strong></p><p>In this article, we’ve shown how to secure your ASP.NET Core Web API using API key and token authorization as middleware. We used PostgreSQL and Entity Framework for user login and generated API keys with a specific lifetime. By following these steps, you can ensure that only authorized clients can access your API, enhancing its security.</p><p>You can find the full project on GitHub <a href="https://github.com/epolat/AuthorizationWithMiddleware">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbcb51d56334" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Validate Addresses Using USPS API in ASP.NET: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@ieplt/how-to-validate-addresses-using-usps-api-in-asp-net-a-step-by-step-guide-f48a38ebd0f5?source=rss-ec97c01c22c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f48a38ebd0f5</guid>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[usps-address-validation]]></category>
            <dc:creator><![CDATA[İbrahim Emre POLAT]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 05:32:08 GMT</pubDate>
            <atom:updated>2024-06-07T05:32:08.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npOXkWmSYbXG8hAipEZ6KQ.png" /></figure><p>Address validation is crucial for many applications, ensuring that user-provided addresses are correct and deliverable. Using the USPS (United States Postal Service) for address validation is a reliable way to achieve this. In this article, we’ll walk through creating a function to validate addresses using USPS in an ASP.NET application, complete with the necessary class for validation.</p><p>First, you need to obtain a USPS user ID. Follow these steps:</p><ul><li>Go to the <a href="https://registration.shippingapis.com/">USPS Registration Page</a>.</li><li>Fill out the necessary fields to register.</li><li>Once registered, you will receive a USPS user ID via email.</li></ul><p><strong>Creating the Validation Class in ASP.NET</strong></p><p>Let’s set up our ASP.NET project and create the validation class.</p><p><strong>Set Up the Project:</strong></p><p>Open Visual Studio and create a new ASP.NET Core Web Application. Choose the “API” template and click “Create”.</p><p><strong>Install Required Packages:</strong></p><p>Open the NuGet Package Manager and install the RestSharp package, which we&#39;ll use to make HTTP requests.</p><p><strong>Define the Address Model:</strong></p><p>Create a new class file AddressModel.cs:</p><pre>public class AddressModel<br>{<br>    public string Address { get; set; }<br>    public string City { get; set; }<br>    public string State { get; set; }<br>    public string Zip { get; set; }<br>}</pre><p><strong>Add USPS Settings in </strong><strong>appsettings.json:</strong></p><pre>{<br>  &quot;USPSSettings&quot;: {<br>    &quot;USPSUserId&quot;: &quot;YOUR_USPS_USER_ID&quot;,<br>    &quot;USPSBaseUrl&quot;: &quot;https://secure.shippingapis.com/ShippingAPI.dll&quot;<br>  }<br>}</pre><p>Create a Settings Class:</p><p>Create a new class file Settings.cs in a Settings namespace:</p><pre>namespace AdressValidation.Settings<br>{<br>    public class Settings<br>    {<br>        public string USPSUserId { get; set; }<br>        public string USPSBaseUrl { get; set; }<br>    }<br>}</pre><p>Define the USPS Client Interface:</p><p>Create a new interface file IUSPSClient.cs:</p><pre>public interface IUSPSClient<br>{<br>    bool ValidateAddress(AddressModel address);<br>}</pre><p><strong>Implement the USPS Client:</strong></p><p>Create a new class file USPSClient.cs:</p><pre>using Microsoft.Extensions.Options;<br>using RestSharp;<br>using System.Xml.Linq;<br>using AdressValidation.Settings;<br><br>public class USPSClient : IUSPSClient<br>{<br>    private readonly string _userId;<br>    private readonly string _baseUrl;<br>    private const string ApiAction = &quot;Verify&quot;;<br><br>    public USPSClient(IOptions&lt;Settings&gt; settings)<br>    {<br>        _userId = settings.Value.USPSUserId;<br>        _baseUrl = settings.Value.USPSBaseUrl;<br>    }<br><br>    public bool ValidateAddress(AddressModel address)<br>    {<br>        var client = new RestClient(_baseUrl);<br>        var request = new RestRequest(&quot;&quot;, Method.GET);<br>        request.AddParameter(&quot;API&quot;, ApiAction);<br>        request.AddParameter(&quot;XML&quot;, BuildRequestXml(address));<br><br>        var response = client.Execute(request);<br>        return IsValidResponse(response.Content);<br>    }<br><br>    private string BuildRequestXml(AddressModel address)<br>    {<br>        return $&quot;&lt;AddressValidateRequest USERID=\&quot;{_userId}\&quot;&gt;&lt;Address&gt;&lt;Address1&gt;&lt;/Address1&gt;&lt;Address2&gt;{address.Address}&lt;/Address2&gt;&lt;City&gt;{address.City}&lt;/City&gt;&lt;State&gt;{address.State}&lt;/State&gt;&lt;Zip5&gt;{address.Zip}&lt;/Zip5&gt;&lt;Zip4&gt;&lt;/Zip4&gt;&lt;/Address&gt;&lt;/AddressValidateRequest&gt;&quot;;<br>    }<br><br>    private bool IsValidResponse(string responseContent)<br>    {<br>        var xml = XDocument.Parse(responseContent);<br>        var error = xml.Descendants(&quot;Error&quot;).FirstOrDefault();<br>        return error == null;<br>    }<br>}</pre><p><strong>Dependency Injection Setup</strong></p><p>To use dependency injection, we’ll need to register our USPSClient service and configure the USPS settings.</p><p>Configure Services in Program.cs:</p><pre>using AdressValidation.Settings;<br>using Microsoft.Extensions.Options;<br>using Microsoft.AspNetCore.Builder;<br>using Microsoft.Extensions.DependencyInjection;<br>using Microsoft.Extensions.Hosting;<br><br>namespace AdressValidation<br>{<br>    public class Program<br>    {<br>        public static void Main(string[] args)<br>        {<br>            var builder = WebApplication.CreateBuilder(args);<br><br>            // Add services to the container.<br>            builder.Services.AddControllers();<br>            builder.Services.AddEndpointsApiExplorer();<br>            builder.Services.AddSwaggerGen();<br><br>            // Add configuration for USPS settings<br>            builder.Services.Configure&lt;Settings&gt;(builder.Configuration.GetSection(&quot;USPSSettings&quot;));<br>            builder.Services.AddScoped&lt;IUSPSClient, USPSClient&gt;();<br><br>            var app = builder.Build();<br><br>            // Configure the HTTP request pipeline.<br>            if (app.Environment.IsDevelopment())<br>            {<br>                app.UseSwagger();<br>                app.UseSwaggerUI();<br>            }<br><br>            app.UseHttpsRedirection();<br>            app.UseAuthorization();<br>            app.MapControllers();<br>            app.Run();<br>        }<br>    }<br>}</pre><p><strong>Creating the Controller</strong></p><p>Now that we have our USPS client set up with dependency injection, let’s use it in a controller to validate addresses.</p><p><strong>Create the Validation Controller:</strong></p><p>Create a new controller file AddressValidationController.cs:</p><pre>using Microsoft.AspNetCore.Mvc;<br><br>[Route(&quot;api/[controller]&quot;)]<br>[ApiController]<br>public class AddressValidationController : ControllerBase<br>{<br>    private readonly IUSPSClient _uspsClient;<br><br>    public AddressValidationController(IUSPSClient uspsClient)<br>    {<br>        _uspsClient = uspsClient;<br>    }<br><br>    [HttpPost]<br>    public IActionResult ValidateAddress([FromBody] AddressModel address)<br>    {<br>        var isValid = _uspsClient.ValidateAddress(address);<br>        return Ok(new { isValid });<br>    }<br>}</pre><p><strong>Example Usage</strong></p><p>To test the address validation, you can use Postman or any API testing tool to send a POST request to /api/addressvalidation with the following JSON body:</p><pre>{<br>    &quot;Address&quot;: &quot;350 5th Ave&quot;,<br>    &quot;City&quot;: &quot;New York&quot;,<br>    &quot;State&quot;: &quot;NY&quot;,<br>    &quot;Zip&quot;: &quot;10118&quot;<br>}</pre><p>The response will indicate whether the address is valid or not.</p><p><strong>Conclusion</strong></p><p>In this article, we’ve shown how to validate addresses using the USPS API in an ASP.NET application. We covered registering for a USPS user ID, creating a validation class with an interface, reading configuration from appsettings.json, and implementing a controller to handle validation requests using dependency injection. By following these steps, you can ensure that the addresses in your application are accurate and deliverable.</p><p>You can find the full project on GitHub <a href="https://github.com/epolat/USPSAdressValidation">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f48a38ebd0f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Testing a Student Track System in ASP.NET Core with AutoBogus, Shouldly, and Moq]]></title>
            <link>https://medium.com/@ieplt/building-and-testing-a-student-track-system-in-asp-net-core-with-autobogus-shouldly-and-moq-99247b033385?source=rss-ec97c01c22c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/99247b033385</guid>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[İbrahim Emre POLAT]]></dc:creator>
            <pubDate>Wed, 05 Jun 2024 22:20:49 GMT</pubDate>
            <atom:updated>2024-06-06T05:40:28.667Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SS10LheC_NIFEtg7PTIV4Q.png" /></figure><p>Unit testing is essential for ensuring the reliability and maintainability of your application. In this article, we will build a Student Track System with endpoints to create students, create student classes, create exams, and add exam results to students. We will then write unit tests for each feature using AutoBogus, Shouldly, and Moq, while adhering to SOLID, KISS, DRY, and YAGNI principles.</p><h3>Setting Up the Project</h3><p><strong>Create a new ASP.NET Core Web API project:</strong></p><ul><li>Open Visual Studio.</li><li>Create a new ASP.NET Core Web Application.</li><li>Choose the “API” template.</li></ul><p><strong>Add the necessary NuGet packages:</strong></p><p>Open the Package Manager Console and run the following commands:</p><pre>Install-Package AutoBogus<br>Install-Package Shouldly<br>Install-Package xunit<br>Install-Package xunit.runner.visualstudio<br>Install-Package Moq</pre><h3>Designing the Student Track System</h3><h4>Models</h4><pre>public class Student<br>{<br>    public int Id { get; set; }<br>    public string FirstName { get; set; }<br>    public string LastName { get; set; }<br>    public List&lt;ExamResult&gt; ExamResults { get; set; } = new List&lt;ExamResult&gt;();<br>}<br><br>public class StudentClass<br>{<br>    public int Id { get; set; }<br>    public string ClassName { get; set; }<br>    public List&lt;Student&gt; Students { get; set; } = new List&lt;Student&gt;();<br>}<br><br>public class Exam<br>{<br>    public int Id { get; set; }<br>    public string Subject { get; set; }<br>    public DateTime Date { get; set; }<br>}<br><br>public class ExamResult<br>{<br>    public int Id { get; set; }<br>    public int StudentId { get; set; }<br>    public int ExamId { get; set; }<br>    public double Score { get; set; }<br>}</pre><h4>Services</h4><p>Applying the Single Responsibility Principle (SRP) and Dependency Injection (DI):</p><pre>public interface IStudentService<br>{<br>    void CreateStudent(Student student);<br>    Student GetStudentById(int id);<br>}<br><br>public interface IClassService<br>{<br>    void CreateStudentClass(StudentClass studentClass);<br>}<br><br>public interface IExamService<br>{<br>    void CreateExam(Exam exam);<br>    void AddExamResult(ExamResult examResult);<br>}<br><br>public class StudentService : IStudentService<br>{<br>    private readonly IRepository&lt;Student&gt; _studentRepository;<br><br>    public StudentService(IRepository&lt;Student&gt; studentRepository)<br>    {<br>        _studentRepository = studentRepository;<br>    }<br><br>    public void CreateStudent(Student student)<br>    {<br>        _studentRepository.Add(student);<br>    }<br><br>    public Student GetStudentById(int id)<br>    {<br>        return _studentRepository.GetById(id);<br>    }<br>}<br><br>public class ClassService : IClassService<br>{<br>    private readonly IRepository&lt;StudentClass&gt; _classRepository;<br><br>    public ClassService(IRepository&lt;StudentClass&gt; classRepository)<br>    {<br>        _classRepository = classRepository;<br>    }<br><br>    public void CreateStudentClass(StudentClass studentClass)<br>    {<br>        _classRepository.Add(studentClass);<br>    }<br>}<br><br>public class ExamService : IExamService<br>{<br>    private readonly IRepository&lt;Exam&gt; _examRepository;<br>    private readonly IRepository&lt;ExamResult&gt; _examResultRepository;<br><br>    public ExamService(IRepository&lt;Exam&gt; examRepository, IRepository&lt;ExamResult&gt; examResultRepository)<br>    {<br>        _examRepository = examRepository;<br>        _examResultRepository = examResultRepository;<br>    }<br><br>    public void CreateExam(Exam exam)<br>    {<br>        _examRepository.Add(exam);<br>    }<br><br>    public void AddExamResult(ExamResult examResult)<br>    {<br>        _examResultRepository.Add(examResult);<br>    }<br>}</pre><h4>Repositories</h4><p>A generic repository for handling CRUD operations, promoting the DRY principle:</p><pre>public interface IRepository&lt;T&gt;<br>{<br>    void Add(T entity);<br>    T GetById(int id);<br>    IEnumerable&lt;T&gt; GetAll();<br>}<br><br>public class InMemoryRepository&lt;T&gt; : IRepository&lt;T&gt; where T : class<br>{<br>    private readonly List&lt;T&gt; _storage = new List&lt;T&gt;();<br><br>    public void Add(T entity)<br>    {<br>        _storage.Add(entity);<br>    }<br><br>    public T GetById(int id)<br>    {<br>        var propertyInfo = typeof(T).GetProperty(&quot;Id&quot;);<br>        return _storage.FirstOrDefault(e =&gt; (int)propertyInfo.GetValue(e) == id);<br>    }<br><br>    public IEnumerable&lt;T&gt; GetAll()<br>    {<br>        return _storage;<br>    }<br>}</pre><h4>Controllers</h4><p>Following the KISS principle, we keep the controllers straightforward:</p><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class StudentsController : ControllerBase<br>{<br>    private readonly IStudentService _studentService;<br><br>    public StudentsController(IStudentService studentService)<br>    {<br>        _studentService = studentService;<br>    }<br><br>    [HttpPost(&quot;create-student&quot;)]<br>    public IActionResult CreateStudent(Student student)<br>    {<br>        _studentService.CreateStudent(student);<br>        return Ok(&quot;Student created successfully.&quot;);<br>    }<br><br>    [HttpGet(&quot;get-student/{id}&quot;)]<br>    public IActionResult GetStudent(int id)<br>    {<br>        var student = _studentService.GetStudentById(id);<br>        return student != null ? Ok(student) : NotFound();<br>    }<br>}<br><br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class ClassesController : ControllerBase<br>{<br>    private readonly IClassService _classService;<br><br>    public ClassesController(IClassService classService)<br>    {<br>        _classService = classService;<br>    }<br><br>    [HttpPost(&quot;create-class&quot;)]<br>    public IActionResult CreateClass(StudentClass studentClass)<br>    {<br>        _classService.CreateStudentClass(studentClass);<br>        return Ok(&quot;Class created successfully.&quot;);<br>    }<br>}<br><br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class ExamsController : ControllerBase<br>{<br>    private readonly IExamService _examService;<br><br>    public ExamsController(IExamService examService)<br>    {<br>        _examService = examService;<br>    }<br><br>    [HttpPost(&quot;create-exam&quot;)]<br>    public IActionResult CreateExam(Exam exam)<br>    {<br>        _examService.CreateExam(exam);<br>        return Ok(&quot;Exam created successfully.&quot;);<br>    }<br><br>    [HttpPost(&quot;add-exam-result&quot;)]<br>    public IActionResult AddExamResult(ExamResult examResult)<br>    {<br>        _examService.AddExamResult(examResult);<br>        return Ok(&quot;Exam result added successfully.&quot;);<br>    }<br>}</pre><h3>Writing Unit Tests</h3><h4>Test Project Setup</h4><p><strong>Create a new xUnit Test Project:</strong></p><ul><li>Add a new project to the solution.</li><li>Choose the xUnit Test Project template.</li></ul><p><strong>Add references to the main project and necessary NuGet packages:</strong></p><ul><li>Open the Package Manager Console and run the following commands:</li></ul><pre>Install-Package AutoBogus<br>Install-Package Shouldly<br>Install-Package Moq</pre><h4>Unit Tests</h4><p>Using AutoBogus to generate test data and Shouldly for assertions:</p><pre>public class StudentServiceTests<br>{<br>    private readonly Mock&lt;IRepository&lt;Student&gt;&gt; _studentRepositoryMock;<br>    private readonly IStudentService _studentService;<br><br>    public StudentServiceTests()<br>    {<br>        _studentRepositoryMock = new Mock&lt;IRepository&lt;Student&gt;&gt;();<br>        _studentService = new StudentService(_studentRepositoryMock.Object);<br>    }<br><br>    [Fact]<br>    public void CreateStudent_ShouldAddStudent()<br>    {<br>        // Arrange<br>        var student = AutoFaker.Generate&lt;Student&gt;();<br><br>        // Act<br>        _studentService.CreateStudent(student);<br><br>        // Assert<br>        _studentRepositoryMock.Verify(repo =&gt; repo.Add(It.IsAny&lt;Student&gt;()), Times.Once);<br>    }<br><br>    [Fact]<br>    public void GetStudentById_ShouldReturnStudent()<br>    {<br>        // Arrange<br>        var student = AutoFaker.Generate&lt;Student&gt;();<br>        _studentRepositoryMock.Setup(repo =&gt; repo.GetById(student.Id)).Returns(student);<br><br>        // Act<br>        var result = _studentService.GetStudentById(student.Id);<br><br>        // Assert<br>        result.ShouldNotBeNull();<br>        result.ShouldBe(student);<br>    }<br>}<br><br>public class ClassServiceTests<br>{<br>    private readonly Mock&lt;IRepository&lt;StudentClass&gt;&gt; _classRepositoryMock;<br>    private readonly IClassService _classService;<br><br>    public ClassServiceTests()<br>    {<br>        _classRepositoryMock = new Mock&lt;IRepository&lt;StudentClass&gt;&gt;();<br>        _classService = new ClassService(_classRepositoryMock.Object);<br>    }<br><br>    [Fact]<br>    public void CreateClass_ShouldAddClass()<br>    {<br>        // Arrange<br>        var studentClass = AutoFaker.Generate&lt;StudentClass&gt;();<br><br>        // Act<br>        _classService.CreateStudentClass(studentClass);<br><br>        // Assert<br>        _classRepositoryMock.Verify(repo =&gt; repo.Add(It.IsAny&lt;StudentClass&gt;()), Times.Once);<br>    }<br>}<br><br>public class ExamServiceTests<br>{<br>    private readonly Mock&lt;IRepository&lt;Exam&gt;&gt; _examRepositoryMock;<br>    private readonly Mock&lt;IRepository&lt;ExamResult&gt;&gt; _examResultRepositoryMock;<br>    private readonly IExamService _examService;<br><br>    public ExamServiceTests()<br>    {<br>        _examRepositoryMock = new Mock&lt;IRepository&lt;Exam&gt;&gt;();<br>        _examResultRepositoryMock = new Mock&lt;IRepository&lt;ExamResult&gt;&gt;();<br>        _examService = new ExamService(_examRepositoryMock.Object, _examResultRepositoryMock.Object);<br>    }<br><br>    [Fact]<br>    public void CreateExam_ShouldAddExam()<br>    {<br>        // Arrange<br>        var exam = AutoFaker.Generate&lt;Exam&gt;();<br><br>        // Act<br>        _examService.CreateExam(exam);<br><br>        // Assert<br>        _examRepositoryMock.Verify(repo =&gt; repo.Add(It.IsAny&lt;Exam&gt;()), Times.Once);<br>    }<br><br>    [Fact]<br>    public void AddExamResult_ShouldAddResult()<br>    {<br>        // Arrange<br>        var examResult = AutoFaker.Generate&lt;ExamResult&gt;();<br><br>        // Act<br>        _examService.AddExamResult(examResult);<br><br>        // Assert<br>        _examResultRepositoryMock.Verify(repo =&gt; repo.Add(It.IsAny&lt;ExamResult&gt;()), Times.Once);<br>    }<br>}</pre><h3>Conclusion</h3><p>By following SOLID principles, KISS, DRY, and YAGNI, we have built a maintainable and testable Student Track System in ASP.NET Core. We used AutoBogus to generate realistic test data, Shouldly for readable assertions, and Moq for creating mock objects in our unit tests. This setup not only ensures code reliability but also improves the overall development experience.</p><p>You can find the full project on GitHub <a href="https://github.com/epolat/StudentTrackingSystem">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99247b033385" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>