<?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 Vahid Cheshmy on Medium]]></title>
        <description><![CDATA[Stories by Vahid Cheshmy on Medium]]></description>
        <link>https://medium.com/@v.cheshmy?source=rss-f78216426281------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dyOvuq3mXkH62XYrTx2y1g.jpeg</url>
            <title>Stories by Vahid Cheshmy on Medium</title>
            <link>https://medium.com/@v.cheshmy?source=rss-f78216426281------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:58:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@v.cheshmy/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[Anemic domain model vs Rich domain model]]></title>
            <link>https://medium.com/@v.cheshmy/anemic-domain-model-vs-rich-domain-model-fbbcd9113412?source=rss-f78216426281------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbbcd9113412</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[sql-server]]></category>
            <dc:creator><![CDATA[Vahid Cheshmy]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 10:52:51 GMT</pubDate>
            <atom:updated>2025-03-08T11:01:08.528Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding the Concepts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFmM_pRdBPhblqzcQzlfSQ.png" /></figure><h4>1: Anemic Domain Model</h4><p><strong>Definition</strong>: An anemic domain model is one in which the domain objects (entities) are primarily data holders with little or no business logic. The logic is instead placed in separate service classes or managers, resulting in a procedural style of programming.</p><p><strong>Characteristics</strong>:</p><ul><li>Entities are simple classes with getters and setters (POJOs in Java or POCO in C#, for example).</li><li>Business logic resides outside the domain objects, typically in service layers.</li><li>Often criticized for <strong>violating object-oriented</strong> principles because it separates data from behavior.</li></ul><p><strong>When it’s used</strong>:</p><p>Common in frameworks like early-stage projects where simplicity is prioritized over strict OOP adherence.</p><pre>// Domain Object (Anemic)<br>public class Book<br>{<br>      <br>    public Guid Id{ get; set; }  <br>    public string Title { get; set; }<br>    public int Stock { get; set; }   <br><br>    public Book(Guid id, string title, int stock)<br>    {<br>        Id= id;<br>        Title = title;<br>        Stock = stock;<br>    }<br>}<br><br>// Service Layer with Business Logic<br>public class BookService<br>{<br>    public void AddStock(Book book, int quantity)<br>    {<br>        if (quantity &lt;= 0)<br>            throw new ArgumentException(&quot;Quantity must be positive.&quot;);<br>        book.Stock += quantity;<br>    }<br><br>    public void RemoveStock(Book book, int quantity)<br>    {<br>        if (quantity &lt;= 0)<br>            throw new ArgumentException(&quot;Quantity must be positive.&quot;);<br>        if (book.Stock &lt; quantity)<br>            throw new InvalidOperationException(&quot;Insufficient stock.&quot;);<br>        book.Stock -= quantity;<br>    }<br>}<br><br>// Usage<br>class Program<br>{<br>    static void Main()<br>    {<br>        var bookId = Guid.NewGuid();<br>        var book = new Book(bookId, &quot;Harry Potter&quot;, 10);<br>        var service = new BookService();<br><br>        service.AddStock(book, 5);<br>        Console.WriteLine(book.Stock); <br>        service.RemoveStock(book, 3);<br>        Console.WriteLine(book.Stock);<br>    }<br>}</pre><p><strong>Notes</strong>:</p><ul><li>Book is a simple POCO with no behavior—just properties.</li><li>BookService handles stock management logic, like adding or removing copies.</li></ul><h4>2: Rich Domain Model</h4><p><strong>Definition:</strong></p><ul><li>A rich domain model embeds business logic directly within the domain objects. Entities are not just data containers but also contain methods that define their behavior.</li></ul><p><strong>Characteristics</strong>:</p><ul><li>Encapsulation of data and behavior in the same class.</li><li>Follows object-oriented principles like single responsibility and encapsulation.</li><li>Often aligns with domain-driven design (DDD) practices.</li></ul><p><strong>When it’s used</strong>:</p><p>Preferred in complex applications where the domain logic is central to the system and needs to be reusable and maintainable.</p><pre>public class Book:Entity<br>{<br>    public string Title { get; private set; }<br>    public int Stock { get; private set; }<br><br><br>    protected Book(Guid id, string title, int stock)<br>    {<br>        Id = id;<br>        Title = title;<br>        Stock= stock;<br>    }<br><br>    public static Book Create(Guid id, string title, int stock)<br>    {<br>        if (id == Guid.Empty)<br>            throw new ArgumentException(&quot;Id cannot be empty.&quot;);<br>        if (string.IsNullOrWhiteSpace(title))<br>            throw new ArgumentException(&quot;Title cannot be empty.&quot;);<br>        if (stock &lt; 0)<br>            throw new ArgumentException(&quot;Stock cannot be negative.&quot;);<br><br>        return new Book(id, title, stock);<br>    }<br><br>    public void AddStock(int quantity)<br>    {<br>        if (quantity &lt;= 0)<br>            throw new ArgumentException(&quot;Quantity must be positive.&quot;);<br>        _stock += quantity;<br>    }<br><br>    public void RemoveStock(int quantity)<br>    {<br>        if (quantity &lt;= 0)<br>            throw new ArgumentException(&quot;Quantity must be positive.&quot;);<br>        if (_stock &lt; quantity)<br>            throw new InvalidOperationException(&quot;Insufficient stock.&quot;);<br>        _stock -= quantity;<br>    }<br>}<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        var bookId = Guid.NewGuid();<br>        var book = Book.Create(bookId, &quot;Harry Potter&quot;, 10);<br><br>        book.AddStock(5);<br>        Console.WriteLine(book.Stock); <br>        book.RemoveStock(3);<br>        Console.WriteLine(book.Stock); <br>    }<br>}</pre><blockquote>By using an object-relational mapping (ORM) tool like Entity Framework (EF) Core, it will automatically generate and assign a GUID for entities that have a primary key of typeGuid. This means you don&#39;t need to manually create or assign a GUID before saving the entity to the database, as EF Core will handle it internally using its default value generation strategy.</blockquote><h3>Does the anemic domain model violate the SOLID principles?</h3><p>The anemic domain model <strong>partially violates SOLID principles</strong>, particularly <strong>SRP</strong>, <strong>OCP</strong>, and <strong>DIP</strong>, though it doesn’t strongly conflict with <strong>LSP</strong> or <strong>ISP</strong>. The core issue is its separation of data and behavior.</p><ul><li><strong>SRP Violation</strong>: By relegating behavior to services, it splits domain responsibility unnaturally, undermining the cohesion expected in OOP.</li><li><strong>OCP Violation</strong>: Extending functionality requires modifying service classes rather than leveraging the entity’s own extensibility.</li><li><strong>DIP Violation</strong>: Tight coupling to concrete data classes limits flexibility.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbbcd9113412" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Architecture tests in .NET]]></title>
            <link>https://medium.com/@v.cheshmy/architecture-tests-in-net-d95192faf2dd?source=rss-f78216426281------2</link>
            <guid isPermaLink="false">https://medium.com/p/d95192faf2dd</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Vahid Cheshmy]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 17:01:48 GMT</pubDate>
            <atom:updated>2024-04-18T17:01:48.831Z</atom:updated>
            <content:encoded><![CDATA[<h3>Architecture tests in.NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N6DSFvA7u9Zsq9Ql" /></figure><h3>What is an architecture test?</h3><p>An architecture test is an automated test that enables your application to verify the structure and design of your code.</p><p>Imagine a new developer who has recently joined your team and will extend the current application. How can you enforce your software architecture, rules, etc.?</p><p>While there are some clean code standards that can be very helpful to apply in your application, you still need to review them after any commits or pull requests.</p><h3>Writing Architecture tests</h3><p>In this article, I’m going to follow the onion architecture as my software design pattern.</p><p>Here is what the solution looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*7H1gCKQrhGyUSCqf" /><figcaption>Solution</figcaption></figure><p>Let’s create a new class library application and name it “Devlife.ArchitectureTests”.</p><p>To set up the architecture tests, we need to install “NetArchTest.Rules” as a NuGet package.</p><pre>dotnet add package NetArchTest.Rules --version 1.3.2</pre><p>This library is a fluent API library that can enforce the architectural rules in our unit tests.</p><p>Let’s create a BaseTest class and add our assemblies to this file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fGk9bCnsp7aKzScB" /></figure><p>This test will cover four different layers in the current solution:</p><ul><li>Domain layer</li><li>Application layer</li><li>Infrastructure layer</li><li>Presentation layer</li></ul><h3>Domain Tests</h3><p>We need to add a new folder named “Domain” and create a “DomainTests.cs” class. This folder will include all our architecture tests related to the Domain layer, such as entities, value objects, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*AFeMaBVU3Rs98vqN" /></figure><p>Let’s add our tests to the domain test class.</p><p>In this example, we can cover:</p><ul><li>All entities should enforce having a private parameterless constructor.</li><li>All properties in entities should have a private/protected setter.</li></ul><pre>public sealed class DomainTests:BaseTest<br>{<br>    [Fact]<br>    public void Entities_Should_HavePrivateParameterlessConstructor()<br>    {<br>        var entityTypes = Types.InAssembly(DomainAssembly)<br>            .That()<br>            .Inherit(typeof(EntityBase))<br>            .GetTypes();<br>        var failingTypes = new List&lt;Type&gt;();<br>        foreach (var entityType in entityTypes)<br>        {<br>            var constructors = entityType.GetConstructors(<br>                BindingFlags.NonPublic |<br>                            BindingFlags.Instance);<br>            if (!constructors.Any(c =&gt; c.IsPrivate &amp;&amp; c.GetParameters().Length == 0))<br>            {<br>                failingTypes.Add(entityType);<br>            }<br><br>            failingTypes.Should().BeEmpty();<br>        }<br>    }<br><br>    [Fact]<br>    public void Entities_Should_Have_PrivateSetter()<br>    {<br>        var entityTypes = Types.InAssembly(DomainAssembly)<br>            .That()<br>            .AreClasses()<br>            .And()<br>            .Inherit(typeof(EntityBase))<br>            .GetTypes();<br><br>        foreach (var entityType in entityTypes)<br>        {<br>            var properties = entityType.GetProperties();<br>            foreach (var property in properties)<br>            {<br>                if (property.CanWrite)<br>                {<br>                    property.SetMethod.Should().NotBeNull()<br>                        .And.Match(setMethod =&gt; setMethod.IsPrivate || setMethod.IsFamily || setMethod.IsFamilyOrAssembly,<br>                            $&quot;{property.Name} should have a private or protected setter.&quot;, property.DeclaringType?.FullName);<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Let’s add a public setter to the Name property in the product entity and then run the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*dRW5El3Czzp9Y5XD" /><figcaption>Product.cs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Qbl1mQMP2w0VuvF" /></figure><p>This figure shows that the name property in a product class should have a private setter, which in this case violates our architecture design pattern.</p><p>This unit test will also ensure that all entities have a private constructor.</p><h3>Application Tests</h3><p>The second part we need to test in our application is the application layer.</p><p>In this layer, I use the MediatR pattern and need to enforce the developer to follow some rules:</p><ul><li>All Command handlers should have a name ending with “CommandHandler”</li><li>All query handlers should have a name ending with “QueryHandler”</li><li>All command and query handlers should not be public</li></ul><p>Let’s add a new folder to the current project and name it “Application”</p><p>This folder contains an “ApplicationTests” class.</p><pre>public sealed class ApplicationTests:BaseTest<br>{<br>[Fact]<br>    public void CommandHandler_ShouldHave_NameEndingWith_CommandHandler()<br>    {<br>        var result = Types.InAssembly(ApplicationAssembly)<br>            .That()<br>            .ImplementInterface(typeof(ICommandHandler&lt;&gt;))<br>            .Or()<br>            .ImplementInterface(typeof(ICommandHandler&lt;,&gt;))<br>            .Should()<br>            .HaveNameEndingWith(&quot;CommandHandler&quot;)<br>            .GetResult();<br>        result.IsSuccessful.Should().BeTrue();<br>    }<br>    <br>    [Fact]<br>    public void CommandHandler_Should_NotBePublic()<br>    {<br>        var result = Types.InAssembly(ApplicationAssembly)<br>            .That()<br>            .ImplementInterface(typeof(ICommandHandler&lt;&gt;))<br>            .Or()<br>            .ImplementInterface(typeof(ICommandHandler&lt;,&gt;))<br>            .Should()<br>            .NotBePublic()<br>            .GetResult();<br>        result.IsSuccessful.Should().BeTrue();<br>    }<br>    [Fact]<br>    public void QueryHandler_Should_NotBePublic()<br>    {<br>        var result = Types.InAssembly(ApplicationAssembly)<br>            .That()<br>            .ImplementInterface(typeof(IQueryHandler&lt;&gt;))<br>            .Or()<br>            .ImplementInterface(typeof(IQueryHandler&lt;,&gt;))<br>            .Should()<br>            .NotBePublic()<br>            .GetResult();<br>        result.IsSuccessful.Should().BeTrue();<br>    }<br>    <br>    [Fact]<br>    public void QueryHandler_ShouldHave_NameEndingWith_QueryHandler()<br>    {<br>        var result = Types.InAssembly(ApplicationAssembly)<br>            .That()<br>            .ImplementInterface(typeof(IQueryHandler&lt;&gt;))<br>            .Or()<br>            .ImplementInterface(typeof(IQueryHandler&lt;,&gt;))<br>            .Should()<br>            .HaveNameEndingWith(&quot;QueryHandler&quot;)<br>            .GetResult();<br>        result.IsSuccessful.Should().BeTrue();<br>    }<br>}</pre><p>Let’s run the tests and analyze the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A4hW6dWer0ww8HFp" /></figure><h3>Dependencies tests</h3><p>Last but not least, this test will enforce the solution to follow onion architecture layer design.</p><p>Let’s add another folder and name it “Layer”. This folder will also have a “LayersTest” class.</p><p>We will enforce the design to follow:</p><ul><li>domain layer should not depend on Application layer</li><li>domain layer should not depend on Infrastructure layer</li><li>application layer should not depend on infrastructure layer</li><li>infrastructure layer should not depend on presentation layer</li></ul><pre>public sealed class LayerTests:BaseTest<br>{<br>    [Fact]<br>    public void DomainLayer_Should_NotHaveDependencyOnApplication()<br>    {<br>        var result = Types.InAssembly(DomainAssembly)<br>            .Should()<br>            .NotHaveDependencyOn(ApplicationAssembly.GetName().Name)<br>            .GetResult();<br>        result.IsSuccessful.Should().BeTrue();<br>    }<br>    <br>    [Fact]<br>    public void DomainLayer_ShouldNotHaveDependencyOn_InfrastructureLayer()<br>    {<br>        var result = Types.InAssembly(DomainAssembly)<br>            .Should()<br>            .NotHaveDependencyOn(InfrastructureAssembly.GetName().Name)<br>            .GetResult();<br>        result.IsSuccessful.Should().BeTrue();<br>    }<br>    <br>    [Fact]<br>    public void ApplicationLayer_ShouldNotHaveDependencyOn_InfrastructureLayer()<br>    {<br>        var result = Types.InAssembly(ApplicationAssembly)<br>            .Should()<br>            .NotHaveDependencyOn(InfrastructureAssembly.GetName().Name)<br>            .GetResult();<br>        result.IsSuccessful.Should().BeTrue();<br>    }<br>    <br>    [Fact]<br>    public void InfrastructureLayer_ShouldNotHaveDependencyOn_PresentationLayer()<br>    {<br>        var result = Types.InAssembly(InfrastructureAssembly)<br>            .Should()<br>            .NotHaveDependencyOn(PresentationAssembly.GetName().Name)<br>            .GetResult();<br>        result.IsSuccessful.Should().BeTrue();<br>    }<br>}</pre><p>Finally, the test project will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*j71JirJU04T7HwRM" /></figure><h3>Summary</h3><p>In this article, we discussed the importance of architecture tests in ensuring the structure and design of our codebase. We followed the onion architecture design pattern and created tests for different layers of our application.</p><ol><li>Domain Tests: We ensured that all entities have a private parameterless constructor and that all properties in entities have private/protected setters.</li><li>Application Tests: We enforced naming conventions and access modifiers for command and query handlers in the application layer.</li><li>Dependencies Tests: We verified that the dependencies between layers follow the Onion Architecture principles, ensuring loose coupling and a clear separation of concerns.</li></ol><p>By running these tests, we can maintain a consistent architecture throughout our application and catch any violations early in the development process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d95192faf2dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vertical slice architecture using .Net 8]]></title>
            <link>https://medium.com/@v.cheshmy/introduction-ae32b9f32ac5?source=rss-f78216426281------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae32b9f32ac5</guid>
            <dc:creator><![CDATA[Vahid Cheshmy]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 14:24:16 GMT</pubDate>
            <atom:updated>2023-09-15T14:25:51.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*2yDqm4PG23m-Kl_oI68lbA.png" /><figcaption>Vertical slice architecture in .NET 8</figcaption></figure><h3>Introduction</h3><p>Most of us are familiar with clean architecture, nowadays, this approach called traditional layered architecture.</p><p>A traditional layered or onion architecture organizes code based on technical concerns in different layers. In this approach, each layer has individual responsibility in the system.</p><p>The layers then depend on each other, and they can collaborate with each other.</p><p>In web applications, the following layers might apply:</p><ul><li>Presentation</li><li>Application</li><li>Domain</li><li>Infrastructure</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*Ktv0ND3CZjenQbcp" /></figure><p>Onion architecture approach</p><h3>Traditional layered architecture problems</h3><ul><li>Highly coupled to the layers, it depends on, and the maintainability will be difficult</li><li>Parallel changing between developers might be difficult, that means by changing different parts, application might be broken.</li></ul><h3>Vertical Slice Architecture</h3><p>A vertical slice architecture is an architectural pattern that organize code by features instead of technical patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/0*IpeBh_stL8rLVxX1" /></figure><p>Vertical slice architecture</p><p>As you can see in the picture, the idea of vertical slice architecture is about grouping the code based on business functionalities, and it will put all relevant codes together.</p><p>In layered architecture the goal is to think about horizontal layers but in now we need to think about vertical layers, in this case we need to put every thing as a feature, that means we don’t need shared layers like repositories, services, infrastructure, and even controllers, we just need to focus on features.</p><h3>Example API in .NET 8</h3><p>Now let’s take a look how we can follow this approach, I will create a simple minimal API in .NET 8.</p><p>Here our solution will look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/0*N6i2oHbUrG_Pen4k" /></figure><p>Vertical slice architecture solution</p><h3>Step 1: Necessary packages</h3><p>We need to install following packages</p><pre>dotnet add package MediatR <br>dotnet add Microsoft.EntityFrameworkCore<br>dotnet add Microsoft.EntityFrameworkCore.Design<br>dotnet add Microsoft.EntityFrameworkCore.SqlServer</pre><h3>Step 2: Add entity</h3><p>Let’s start by creating the entity.</p><pre>public sealed class Book<br>{<br>    public long  Id { get; set; }<br>    public string Name { get; set; } = string.Empty;<br>    public string Description { get; set; } = string.Empty;<br>}</pre><p>The entity will follow an anemic domain that has three properties.</p><h3>Step 3: Configure DbContext</h3><p>We need to add the dbContext in database folder</p><pre>public class ApplicationDbContext:DbContext<br>{<br>    public ApplicationDbContext(DbContextOptions&lt;ApplicationDbContext&gt; options):base(options)<br>    {<br>        <br>    }<br>  public DbSet&lt;Book&gt; Books { get; set; }<br>}</pre><h3>Step 4: Configure services and middlewares</h3><p>It’s time to configure services and also add the middleware in our API</p><p>appsettings.Development.json</p><pre>{<br>  &quot;Logging&quot;: {<br>    &quot;LogLevel&quot;: {<br>      &quot;Default&quot;: &quot;Information&quot;,<br>      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;<br>    }<br>  },<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;Database&quot;: &quot;Server=localhost;Database=VSA;Integrated Security=true;MultipleActiveResultSets=true;TrustServerCertificate=Yes;&quot;<br>  }<br>}</pre><p>Program.cs</p><pre>var builder = WebApplication.CreateBuilder(args);<br>builder.Services.AddDbContext&lt;ApplicationDbContext&gt;(opt =&gt;<br>{        opt.UseSqlServer(builder.Configuration.GetConnectionString(&quot;Database&quot;));<br>});<br>builder.Services.AddMediatR(cfg =&gt; cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));<br>var app = builder.Build();<br>app.Run();</pre><p>So, we just registered the dbContext to use SQL server and also registered MediatR service.</p><h3>Step 5: Create book feature</h3><p>The next step is to apply the feature in our architecture, in this case we need to separate each feature, in this example I will create a book feature that will create and get all books.</p><p>Let’s start with creating the book feature, since I will use MediatR pattern I will adapt CQRS pattern that will segregate query and commands.</p><pre>public static class CreateBook<br>{<br>    public sealed class CreateBookCommand:IRequest&lt;long&gt;<br>    {<br>        public string Name { get; set; } = string.Empty;<br>        public string Description { get; set; } = string.Empty;<br>    }<br>    internal sealed class Handler : IRequestHandler&lt;CreateBookCommand, long&gt;<br>    {<br>        private readonly ApplicationDbContext _dbContext;<br>        public Handler(ApplicationDbContext dbContext)<br>        {<br>            _dbContext = dbContext;<br>        }<br>        public async Task&lt;long&gt; Handle(CreateBookCommand request, CancellationToken cancellationToken)<br>        {<br>            var book = new Book<br>            {<br>                Name = request.Name,<br>                Description = request.Description<br>            };<br>            await _dbContext.AddAsync(book, cancellationToken);<br>            await _dbContext.SaveChangesAsync(cancellationToken);<br>            return book.Id;<br>        }<br>    }<br>    public static void AddEndpoint(this IEndpointRouteBuilder app)<br>    {<br>            app.MapPost(&quot;api/books&quot;, async (CreateBookRequest request, ISender sender) =&gt;<br>            {<br>                var bookId = await sender.Send(request);<br>                return Results.Ok(bookId);<br>            });<br>    }<br>}</pre><p>Contracts</p><pre>public class CreateBookRequest<br>{<br>    public string Name { get; set; } = string.Empty;<br>    public string Description { get; set; } = string.Empty;<br>}</pre><p>As you can see, we added all feature inside the static class, it will create an input that will use IRequest to create a command, then will add the IRequest to its handler and create the book and finally will add the endpoint to call by the client.</p><p>In order to apply the endpoint we need to this middleware in pipeline, simply we can add it in program.cs class.</p><pre>var app = builder.Build();<br>CreateBook.AddEndpoint(app);<br>...</pre><h3>Step 6: Get All books feature</h3><p>Let’s create a query in order to select all books and return them to the client.</p><pre>public static class GetAllBooks<br>{<br>    public sealed class Query : IRequest&lt;List&lt;Book&gt;&gt;<br>    {<br>    }<br>    internal sealed class QueryHandler : IRequestHandler&lt;Query, List&lt;Book&gt;&gt;<br>    {<br>        private readonly ApplicationDbContext _dbContext;<br>        public QueryHandler(ApplicationDbContext dbContext)<br>        {<br>            _dbContext = dbContext;<br>        }<br>        public async Task&lt;List&lt;Book&gt;&gt; Handle(Query request, CancellationToken cancellationToken)<br>            =&gt; await _dbContext.Books.ToListAsync(cancellationToken: cancellationToken);<br>    }<br>    public static void AddEndpoint(this IEndpointRouteBuilder app)<br>    {<br>        app.MapGet(&quot;api/books&quot;, async (ISender sender) =&gt;<br>        {<br>            var books=await sender.Send(new GetAllBooks.Query());<br>            return Results.Ok(books);<br>        });<br>    }<br>}</pre><p>Also, we need to add the endpoint in pipeline:</p><pre>var app = builder.Build();<br>CreateBook.AddEndpoint(app);<br>GetAllBooks.AddEndpoint(app);<br>...</pre><h3>Problem:</h3><p>As you might see, for each feature we need to add the endpoint middleware, here is another package that we can install and use it to get rid of adding a new middleware.</p><pre>dotnet add package Carter</pre><p>in order to use the carter, we need to modify the features</p><p>CreateBook.cs</p><pre>public static class CreateBook<br>{<br>    public sealed class CreateBookCommand:IRequest&lt;long&gt;<br>    {<br>        public string Name { get; set; } = string.Empty;<br>        public string Description { get; set; } = string.Empty;<br>    }<br>    internal sealed class Handler : IRequestHandler&lt;CreateBookCommand, long&gt;<br>    {<br>        private readonly ApplicationDbContext _dbContext;<br>        public Handler(ApplicationDbContext dbContext)<br>        {<br>            _dbContext = dbContext;<br>        }<br>        public async Task&lt;long&gt; Handle(CreateBookCommand request, CancellationToken cancellationToken)<br>        {<br>            var book = new Book<br>            {<br>                Name = request.Name,<br>                Description = request.Description<br>            };<br>            await _dbContext.AddAsync(book, cancellationToken);<br>            await _dbContext.SaveChangesAsync(cancellationToken);<br>            return book.Id;<br>        }<br>    }<br>}<br>public class CreateBookEndpoint : ICarterModule<br>{<br>    public void AddRoutes(IEndpointRouteBuilder app)<br>    {<br>        app.MapPost(&quot;api/books&quot;, async (CreateBookRequest request, ISender sender) =&gt;<br>        {<br>            var bookId = await sender.Send(request);<br>            return Results.Ok(bookId);<br>        });<br>    }<br>}</pre><p>GetAllBooks.cs</p><pre>public static class GetAllBooks<br>{<br>    public sealed class Query : IRequest&lt;List&lt;Book&gt;&gt;<br>    {<br>    }<br>    internal sealed class QueryHandler : IRequestHandler&lt;Query, List&lt;Book&gt;&gt;<br>    {<br>        private readonly ApplicationDbContext _dbContext;<br>        public QueryHandler(ApplicationDbContext dbContext)<br>        {<br>            _dbContext = dbContext;<br>        }<br>        public async Task&lt;List&lt;Book&gt;&gt; Handle(Query request, CancellationToken cancellationToken)<br>            =&gt; await _dbContext.Books.ToListAsync(cancellationToken: cancellationToken);<br>    }<br>}<br>public class GetAllBooksEndpoint : ICarterModule<br>{<br>    public void AddRoutes(IEndpointRouteBuilder app)<br>    {<br>        app.MapGet(&quot;api/books&quot;, async (ISender sender) =&gt;<br>        {<br>            var books=await sender.Send(new GetAllBooks.Query());<br>            return Results.Ok(books);<br>        });<br>    }<br>}</pre><p>and the last step is to register the carter in middleware</p><pre>var app = builder.Build();<br>app.MapCarter();</pre><p>We just need to add the MapCarter middleware in pipeline and that’s it, no need to add new feature in pipeline.</p><blockquote><em>What are your thoughts on this new feature? Do you see it as a valuable addition to your projects, or do you plan to stick with the more traditional layered/onion architecture? Your insights are highly valuable, and I’d love to hear your perspective.</em></blockquote><p>HAPPY CODING!!! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae32b9f32ac5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Onion Architecture -Separate Web/Endpoint and presentation layer]]></title>
            <link>https://medium.com/@v.cheshmy/onion-architecture-separate-web-endpoint-and-presentation-layer-36d4841221cc?source=rss-f78216426281------2</link>
            <guid isPermaLink="false">https://medium.com/p/36d4841221cc</guid>
            <category><![CDATA[onionarchitecture]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[mvc-frameworks]]></category>
            <dc:creator><![CDATA[Vahid Cheshmy]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 17:22:01 GMT</pubDate>
            <atom:updated>2023-03-30T17:22:01.614Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I’m focusing on clean architecture more in projects and I would say I’m a real fan of this architecture.</p><p>So let’s take a glance at this architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ssb5hSPN34AGK-10pelo5w.png" /><figcaption>Onion architecture</figcaption></figure><p>In onion architecture we may have the following projects:</p><ul><li>Presentation</li><li>Application</li><li>Domain</li><li>Infrastructure</li><li>Cross-cutting edge</li></ul><p>You may ask why the Presentation layer and Web/Api are separated.</p><p>So the short answer is to avoid accessing the database directly into the controller, but let’s take a look at it deeper.</p><p>Let’s imagine we would have a home controller like this:</p><pre>public class HomeController : ControllerBase<br>{<br><br>    private readonly DbContext _dbContext;<br>    public HomeController (DbContext dbContext)<br>    {<br>      _dbContext=dbContext;<br>    }<br><br>    // Remaining code removed for brevity<br>}</pre><p>Normally the controllers and web will be implemented in the presentation layer, but let’s consider a new developer trying to create an instance of DBcontext, it will function and while the DBcontext is registered in services, then it will violate the CQRS design and principles.</p><p>In order to avoid this, we can separate the Web API and presentation layer.</p><p>So, I’ve moved the controllers into the class library and we can control what we are referencing in our solution.</p><p>In order to achieve this approach we need to configure <strong>program.cs</strong> in our Web/Endpoint to register the presentation layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jpF8kvuflhuo8oKLg3eUg.png" /><figcaption>Web/API and Presentation layer</figcaption></figure><p>So here our onion architecture will look like this, the presentation layer and Api have been separated.</p><p>Let’s take a look at the codes inside each, first of all, let’s take a look at IAssmblyReference.cs interface:</p><pre>namespace OnionArchitecture.Presentation;<br>/// &lt;summary&gt;<br>/// This empty interface will be registered by Api<br>/// &lt;/summary&gt;<br>public interface IAssemblyReference<br>{<br><br>}</pre><p>It’s just an empty interface that will be referenced by program.cs in order to register our presentation layer into Api.</p><p>Now it’s time to register IAssemblyReference into our API.</p><pre>using OnionArchitecture.Presentation;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>// Add services to the container.<br><br>builder.Services.AddControllers()<br>    .AddApplicationPart(typeof(IAssemblyReference).Assembly);<br>// Remaining code removed for brevity</pre><p>By adding <strong><em>AddApplicationPart</em></strong> we will register all controllers and etc from the Presentation layer into our API.</p><p><strong>Conclusion:</strong></p><p>With this approach, we can achieve the CQRS implementation and avoid accessing the database directly in the controller.</p><p>we only created a new class library that will include controllers and then we would register it into the Web/API layer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36d4841221cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CLR, BCL, CIL and assemblies in .Net framework]]></title>
            <link>https://medium.com/@v.cheshmy/clr-bcl-cil-and-assemblies-in-net-framework-3de8bf09e781?source=rss-f78216426281------2</link>
            <guid isPermaLink="false">https://medium.com/p/3de8bf09e781</guid>
            <category><![CDATA[mvc-frameworks]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[c-language]]></category>
            <category><![CDATA[c-programming]]></category>
            <dc:creator><![CDATA[Vahid Cheshmy]]></dc:creator>
            <pubDate>Tue, 08 Jan 2019 07:53:54 GMT</pubDate>
            <atom:updated>2023-04-21T06:08:33.934Z</atom:updated>
            <content:encoded><![CDATA[<h3>CLR, BCL, CIL, and assemblies in .Net</h3><p>This article is about Base Class Library (BCL), Common Language Runtime (CLR), Common Intermediate Language (CIL), and .NET assemblies.</p><p>Beforehand let’s take a look at Framework Class Library (FCL) in which you can see so many other classes, functionalities, and other services and this article covers Base Class Library and Common Language Runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JnVsyJLhde6gO5gfhFHYFA.png" /><figcaption>Framework Class Library(FCL)</figcaption></figure><h3>Introducing the Building Blocks of the .NET Platform (the CLR, CTS, and CLS)</h3><p>Now, you’ve understood some benefits provided by .NET, I’m going to describe three key topics that will help you to understand key benefits better,</p><p>CLR (Common Language Runtime)</p><p>From a Programmer&#39;s point of view, .NET could be a runtime environment and a comprehensive base class library.</p><p>The runtime is referred to as Common Language Runtime (CLR). the main goal of CLR is to load, Locate and manage .NET objects on the programmer’s behalf. It means that CLR always handles these operations and a programmer doesn’t interfere with these processes. Also, CLR takes care of memory management, application hosting, some security checks, and coordinating threads.</p><p>CTS (Common Type System)</p><p>The CTS describes all data types and all related constructs supported by the runtime, details how they would be represented in the .NET metadata format, and also specifies how entities can interact with each other. In other words, we have several languages and each language has its own data type definition and cannot be understandable by other languages but CLR can understand all the data types.</p><p>For example, C# has an int Data Type and VB.NET has Integer Data Type. so after compilation, it uses the same structure as Int32 in CTS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*e_bAjd6SA2nrpBkEHMWwzQ.png" /><figcaption>Common Language Runtime (CLR)</figcaption></figure><p>CLS (Common Language Specification)</p><p>CLS is a subset of CTS, It defines a set of rules and restrictions that every language must follow which runs under.NET the framework.</p><p>For example imagine you develop an application by C# and VB.NET, in C# every statement must have to end with a semicolon otherwise in VB.NET shouldn’t be written like that.</p><p>So these syntax rules are different from language to language but CLR can understand all language&#39;s syntax because in .NET each language is converted into MSIL code after compilation and MSIL code is the language specification of CLR.</p><p>Base Class Library (BCL)</p><p>Stands for Base class library also known as a Class Library (CL). BCL is a subset of the Framework class library (FCL). The class library is a collection of reusable types that are closely integrated with CLR. The base Class library provides classes and types that are helpful in performing day-to-day operations e.g. dealing with string and primitive types, database connection, and IO operations.</p><p>BCL defines types that can be used to build any type of software application.</p><p>You can use ASP.NET to build websites and REST services, WCF to build distributed systems, WPF to build desktop GUI applications, and so on. As well, the base class libraries provide types to interact with the directory and file system on a given computer, communicate with relational databases (via ADO.NET), and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*1YTCJPIlBPQrXGlOXLqHqg.png" /><figcaption>Base Class Library (BCL)</figcaption></figure><p>Managed and Unmanaged Code</p><p>Now that you’ve found out the definition of BCL and CLR I’m going to talk about Managed and unmanaged codes.</p><p>C# language can be used only to build software that is hosted under .NET runtime. The term used to describe the code targeting the .NET runtime is managed code. There is a binary unit that contains the managed code which is called assembly. In contrast, code that cannot be directly hosted by the.ET runtime is called unmanaged code.</p><p>As I mentioned in a previous article the .NET platform can run on a variety of operating systems.it is possible to build a C# application on a Windows operating system using Visual Studio and run the program on a macOS machine using the .NET Core runtime. Also, you can build a C# application on the Linux operating system using Xamarin Studio and run the program on Windows, macOS, and so on. With the latest release of Visual Studio, I mean Visual Studio 2017, you can also build .NET Core applications on a Mac to be run on Windows, macOS, or Linux.it’s possible to build, deploy, and run .NET programs on different operating systems.</p><h3>An overview of .NET assemblies</h3><p>Regardless of which .NET languages you chose to develop, after compiling your application there would be two types of assemblies, Executing files *.exe and Dynamic Link Library *.dll.</p><p>But when we compile our .NET program it’s not converted into the executable binary code but to an intermediate code, called MSIL or IL, which is understandable by CLR. MSIL is an OS and H/W independent code. When the program needs to be executed, this MSIL or intermediate code is converted to binary executable code, called native code.</p><p>All the .NET assemblies contain the definition of types, versioning information for the type meta-data, and manifest and in this article, I’m going to talk about it more.</p><p>If you have a class named Customer, the type metadata describes details such as Customer’s base class, specifies which interfaces are implemented by the Customer class, and also gives some information about each member in the Customer class..NET metadata is always present within an assembly and it’s .NET duty to automatically generate it.</p><p>CIL and type metadata, assemblies themselves are also described using metadata, which is called <em>manifest.</em> The manifest contains information about the current version of the assembly and a list of all externally referenced assemblies that are required for proper execution. So in the following article, I’m going to use a tool to examine an assembly’s type, metadata, and manifest.</p><h3>The Role of CIL in .NET</h3><p>To understand the rule of CIL take a look at the following C# code which models a calculator.</p><pre>using System;  <br>  <br>namespace Calculator  <br>{  <br>      <br>    class Program  <br>    {  <br>        static void Main(string[] args)  <br>        {  <br>            Calc cl=new Calc();  <br>            Console.WriteLine(&quot;13+31={0}&quot;,cl.AddNumbers(13,31));  <br>            Console.ReadLine();  <br>        }  <br>    }  <br>    <em>//Calculator class which has a method Addnumbers  </em><br>    class Calc  <br>    {  <br>        public int AddNumbers(int x, int y)  <br>        {  <br>            return x + y;  <br>        }  <br>    }  <br>}</pre><p>As you can see we have two classes,</p><ul><li>Program: which is the app’s entry point</li><li>Calc: which has a method named Addnumbers and add two numbers and returns the result of adding numbers.</li></ul><p>After compiling the application using the C# compiler (Calculator.exe), you end up with a *.exe file that contains a manifest, metadata, and CIL instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*3yMTZZXfw0ZCjCXaZAYwag.jpeg" /></figure><p>Now let’s use ildasm.exe to examine our Calculator.exe file.</p><p>You can find ildasm.exe file in C:\Program Files (x86)\Microsoft SDKs\Windows\[your windows version]\Bin</p><p>If you want to use this tool in Visual Studio just follow these steps and add it to Visual Studio tools,</p><ul><li>First find ildasm.exe location (usually it’s located in C:\Program Files (x86)\Microsoft SDKs\Windows\[Windows Verwsion]\Bin\ildasm.exe</li><li>Open up Visual Studio</li><li>From the Tools menu open External Tools and then you should see the External Tools dialog,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*TtyKe3qz1Jj5zpNPDKxCVA.jpeg" /><figcaption>ILDASM.exe</figcaption></figure><ul><li>Click on add button, choose a Title of your tool (my title is ILDASM) , in Command text box enter the path of ildasm.exe and in the Argument textbox just click on the right-arrow button and choose $(TargetPath)</li><li>Check Close and Exit.</li><li>That’s it, it’s done.</li></ul><p>What ildasm.exe offers?</p><p>ildasm will show you three basic things,</p><ul><li>A list of all classes and methods in your assembly</li><li>The contents of the assembly’s manifest</li><li>IL code for any method implemented in the assembly.</li></ul><p>To open related assembly just go to the tools menu and here we go, ILDASM appears in this menu, just open it.</p><p>So, if you want to find some information about your application, open ildasm in your Tools menu, and you’ll see the ildasm.exe dialog.</p><p>As you see there is some information about the assembly’s type, manifest, and metadata.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*PuZkW-y7YtqvZy4k0r_fLw.jpeg" /><figcaption>Assembly</figcaption></figure><p>If I expand Calculator.Calc there would be AddNumbers methods. by double-clicking on the method I can see the information about this method in new dialog windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Z5uSeQ0xUwlL7in98bMXxA.jpeg" /></figure><p>Pay attention to the int32 data type, as you remember in early of this article I talked about CTS (Common Type System) in which all of the data types after compilation would be understandable for CTS. Whatever int in C# or Integer in VB will be compiled as int32 in CTS.</p><p>So as you can see the AddNumbers method is represented using CIL as above picture.</p><p>Benefit of CIL</p><p>Now you’ve found out what CIL exactly does, why is it necessary to compile your code into CIL?do you remember as I said you can use a variety of languages in .NET, here’s a benefit of using CIL, no matter which language you use in your project maybe one or maybe two and so forth, at the end all of them will compile into CIL and all of the languages will interact within a well-defined binary arena.</p><h3>The Role of .NET Type Metadata</h3><p>.NET assembly contains complete and accurate metadata, such as class, structure, and also members of each type such as properties, methods and etc. So, how this information extract? By programmer or compiler? Hopefully all of these tasks are done by the compiler, not the programmer.</p><p>To show you the format of the metadata, let’s take a look at our project metadata generated by the AddNumbers method.to do that, simply open ideas in your Tools menu, and after the dialog popped up, just hit ctl+m to illustrate the type of Metadata of your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQnRsLzTBezJc_sNF9EAMg.jpeg" /></figure><p>If you hit ctl+m and then the dialog box disappears make sure to open the proper version of ildasm.If your project is generated by .Net framework version 4.6.1 and you open ildasm with .NET framework version 4.5.1 your dialog box will disappear after using ctl+m.</p><p>as you see in the above picture, we have a TypeDef #2 which provides some information about the project, for example, TypeDefName refers to the Calc class in the Calculator project and also there are two methods in the Calc class,</p><ul><li>AddNumbers</li><li>which takes two parameters x and y</li><li>.ctor which is the default constructor of the Calc class and is generated automatically by the .NET.</li></ul><p>The Role of the Assembly Manifest</p><p>.Net assembly which contains metadata that describes the assembly itself, as I mentioned earlier it’s called Manifest.</p><p>Manifest documents all external assemblies&#39; information such as the assembly’s version number, copyright information, and so on. so accordingly it is the compiler&#39;s duty to generate the assembly’s manifest rather than the programmer&#39;s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*GAsD3MiMTEOqozAAs0tFxg.jpeg" /><figcaption>Manifest</figcaption></figure><p>resource: pro C# 7 by <a href="https://www.google.com/search?q=Andrew+Troelsen&amp;stick=H4sIAAAAAAAAAOPgE-LVT9c3NEyJT46vqCxMV-LSz9U3MC0vsijI0ZLJTrbST8rPz9YvL8osKUnNiy_PL8q2SiwtycgvAgCszC5ROwAAAA&amp;sa=X&amp;ved=2ahUKEwjiva-Y-9rfAhVjg-AKHWmOAAoQmxMoATAUegQICRAK">Andrew Troelsen</a>,<a href="https://www.google.com/search?q=Philip+Japikse&amp;stick=H4sIAAAAAAAAAOPgE-LVT9c3NEyJT46vqCxMV4Jwk8wM0kyzKzO0ZLKTrfST8vOz9cuLMktKUvPiy_OLsq0SS0sy8osA4B15oz4AAAA&amp;sa=X&amp;ved=2ahUKEwjiva-Y-9rfAhVjg-AKHWmOAAoQmxMoAjAUegQICRAL">Philip Japikse</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3de8bf09e781" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>