<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Lobito</title>
    <description>The latest articles on Forem by Lobito (@iamlobito).</description>
    <link>https://forem.com/iamlobito</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1328600%2Fd0038d96-2673-40f1-9aad-8e266361f81e.jpeg</url>
      <title>Forem: Lobito</title>
      <link>https://forem.com/iamlobito</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/iamlobito"/>
    <language>en</language>
    <item>
      <title>Understanding the Difference Between Proxy and Reverse Proxy</title>
      <dc:creator>Lobito</dc:creator>
      <pubDate>Fri, 22 Mar 2024 10:52:19 +0000</pubDate>
      <link>https://forem.com/iamlobito/understanding-the-difference-between-proxy-and-reverse-proxy-2pd5</link>
      <guid>https://forem.com/iamlobito/understanding-the-difference-between-proxy-and-reverse-proxy-2pd5</guid>
      <description>&lt;p&gt;Hey guys!&lt;/p&gt;

&lt;p&gt;If you are working in the web architecture, &lt;em&gt;proxies and reverse proxies&lt;/em&gt; play vital roles in facilitating communication between clients and servers. Despite sharing similar concepts, they serve distinct purposes and have different functionalities. &lt;br&gt;
There is some confusion around this two concepts. &lt;br&gt;
Let's put in the table the definitions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Proxy:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A proxy server acts as an intermediary between a client and a server. When a client sends a request to access a resource, it doesn't directly communicate with the target server; instead, it communicates with the proxy server. The proxy server then forwards the request to the target server on behalf of the client. Upon receiving the response from the server, the proxy server sends it back to the client.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Characteristics of a Proxy:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Client-Side Proxy:&lt;/strong&gt; Proxies primarily operate on the client side, intercepting requests before they reach the destination server.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Anonymity and Security:&lt;/strong&gt; Proxies can enhance security and privacy by masking the client's IP address and providing anonymity.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Caching:&lt;/strong&gt; Proxies can cache frequently accessed resources, improving performance by serving cached content to clients without needing to fetch it from the server every time.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Content Filtering:&lt;/strong&gt; Proxies can filter content based on predefined rules, allowing organizations to control access to specific websites or content categories.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Reverse Proxy:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A reverse proxy, on the other hand, sits between the internet and web servers, forwarding client requests to the appropriate backend servers. Unlike a regular proxy, which forwards requests from clients to servers, a reverse proxy receives requests from clients and directs them to the appropriate backend server based on factors like load balancing, content caching, or other criteria.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Characteristics of a Reverse Proxy:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Server-Side Proxy:&lt;/strong&gt; Reverse proxies operate on the server side, intercepting requests before they reach the destination servers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Load Balancing:&lt;/strong&gt; Reverse proxies distribute client requests across multiple servers, balancing the load and ensuring efficient resource utilization.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;SSL Termination:&lt;/strong&gt; Reverse proxies can handle SSL/TLS encryption and decryption, relieving backend servers of this resource-intensive task.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Content Caching:&lt;/strong&gt; Similar to regular proxies, reverse proxies can cache content to improve performance and reduce the load on backend servers.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Key Differences:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Direction of Traffic:&lt;/strong&gt; Proxies intercept client requests, while reverse proxies intercept requests before they reach backend servers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Location:&lt;/strong&gt; Proxies are typically deployed on the client side, while reverse proxies are deployed on the server side.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Functionality:&lt;/strong&gt; Proxies focus on client-side tasks like anonymity, caching, and content filtering, whereas reverse proxies handle server-side tasks like load balancing, SSL termination, and content caching.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In conclusion, while both proxies and reverse proxies act as intermediaries in network communication, they serve different purposes and operate at different points in the client-server interaction. Understanding these distinctions is crucial for designing robust and efficient network architectures.&lt;/p&gt;

&lt;p&gt;In a scenario of the web development you will work a lot with reverse proxy or API Gateway. A common package in .net is Ocelot library that make it possible create in a easy way API Gateways for your projects. &lt;br&gt;
Stay tune! In the next article I will write about API Gateways and Ocelot.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>networking</category>
      <category>dotnet</category>
      <category>dotnetcore</category>
    </item>
    <item>
      <title>Create a ASP.NET Web API with MongoDB</title>
      <dc:creator>Lobito</dc:creator>
      <pubDate>Thu, 14 Mar 2024 15:19:56 +0000</pubDate>
      <link>https://forem.com/iamlobito/create-a-aspnet-web-api-with-mongodb-46md</link>
      <guid>https://forem.com/iamlobito/create-a-aspnet-web-api-with-mongodb-46md</guid>
      <description>&lt;p&gt;Hello everybody,&lt;/p&gt;

&lt;p&gt;Continuing my learning path to become a better and more complete developer I challenge myself to learn a little bit about MongoDB that will be consumed by my ASP.NET Core Web Api.&lt;/p&gt;

&lt;p&gt;First things first, for those who don´t know what a hell is a MongoDB I will give a short explanation for what I learn in this challenge. &lt;/p&gt;

&lt;p&gt;MongoDB is a NOSQL database and NOSQL means "Not Only SQL". This is because MongoDB is not only a relational database. NOSQL can store unstructured data.&lt;/p&gt;

&lt;p&gt;Acording to the definition given by ChatGPT: _"A NoSQL database is a type of database that provides a mechanism for storage and retrieval of data that is modeled in ways other than the tabular relations used in relational databases. It's often used for large-scale distributed data storage and real-time web applications, offering flexibility, scalability, and performance advantages over traditional relational databases." _&lt;/p&gt;

&lt;p&gt;So, in practice, MongoDB as NOSQL database is organized like this:&lt;br&gt;
Database -&amp;gt; Collection -&amp;gt; Documents.&lt;/p&gt;

&lt;p&gt;The data is stored in a BSON format (Binary Json). Each pieace of this json is a &lt;strong&gt;Document&lt;/strong&gt;. So in this example we have three documents. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1p525buik1oymyirycki.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1p525buik1oymyirycki.png" alt="Image description" width="500" height="354"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And this documents are stored in collections (you can compare a collection like as a table in SQL Relational databases)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9ttsx4x4vu5vm9e10lfk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9ttsx4x4vu5vm9e10lfk.png" alt="Image description" width="800" height="341"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And all this collections are stored in a database!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxo26wgp3z111hghjq2lx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxo26wgp3z111hghjq2lx.png" alt="Image description" width="800" height="371"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To start using MongoDB the first thing that you need is the MongoDB "engine". For that I recommend using a image container and run that image in the docker container.&lt;br&gt;
You can find all the images available and also MongoDB here:&lt;br&gt;
&lt;a href="https://hub.docker.com/r/bitnami/mongodb"&gt;MongoDB container image&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;After pull the image and run it, you need a way to interact with the database. You can choose using for example &lt;a href="https://www.mongodb.com/try/download/shell"&gt;MongoDB Shell&lt;/a&gt; or some GUI tool like &lt;a href="https://www.mongodb.com/products/tools/compass"&gt;MongoDB Compass&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fglrxojcl6jgnpeivnx8i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fglrxojcl6jgnpeivnx8i.png" alt="Image description" width="800" height="173"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here you can find a good &lt;a href="https://www.mongodb.com/developer/products/mongodb/cheat-sheet/"&gt;MongoDB Cheat Sheet&lt;/a&gt; where you can explore how manipulate the data in MongoDB.&lt;/p&gt;

&lt;p&gt;Ok, this was just a brief about MongoDB, now let´s talk about how use MongoDB in a ASP.NET Core Web API.&lt;/p&gt;

&lt;p&gt;The first this that you must do is create obviously a new asp.net core web api from your visual studio or vscode.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5gddsl3z3vhqsovsgcah.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5gddsl3z3vhqsovsgcah.png" alt="Image description" width="800" height="533"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I will not demonstrate step-by-step everything because it will be boring and also you can download the source code from my &lt;a href="https://github.com/iamlobito/CRUD-for-MongoDB"&gt;GitHub&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;After the project is created you need install the nuget package for the MongoDB Driver.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F97l21lz6i7cjha5y27eq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F97l21lz6i7cjha5y27eq.png" alt="Image description" width="800" height="349"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I organize my project in that way and I only show here the fundamentals. You can organize in other architecture.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa740ov62apl0gugyrjgj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa740ov62apl0gugyrjgj.png" alt="Image description" width="374" height="364"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I have in the Model folder a SuperHero class that represent the document in MongoDB.&lt;/p&gt;

&lt;p&gt;Important things here is the data attributes to identify the field Id and map the c# names with MongoDB names.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1jo5l8j24n91zjirmr08.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1jo5l8j24n91zjirmr08.png" alt="Image description" width="505" height="363"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Another thing that you need is to establish connection to the MongoDb. In this example I create a factory class to do that.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjy0o7hqsy3r7wxfzv85k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjy0o7hqsy3r7wxfzv85k.png" alt="Image description" width="800" height="386"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The configurations of MongoDB connection string is in the appsettings.json.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4hypcb80abjs34u3j4vb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4hypcb80abjs34u3j4vb.png" alt="Image description" width="438" height="257"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, all the magic is in the Repository class. I create a SuperHeroRepository that abstract the data manipulation. In this example the repository do the CRUD operations for MongoDB.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class SuperHeroRepository : ISuperHeroRepository
    {
        private readonly IMongoDbConnectionFactory _connectionFactory;
        private readonly IMongoCollection&amp;lt;SuperHero&amp;gt; _collection;

        public SuperHeroRepository(IMongoDbConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;

            var database = _connectionFactory.GetDatabase();
            _collection = database.GetCollection&amp;lt;SuperHero&amp;gt;("superhero");

        }

        public async Task&amp;lt;bool&amp;gt; Create(SuperHero hero)
        {
            try
            {
                await _collection.InsertOneAsync(hero);
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public async Task&amp;lt;bool&amp;gt; Delete(string id)
        {
            var filterDefinition = Builders&amp;lt;SuperHero&amp;gt;.Filter.Eq(a =&amp;gt; a.Id, id);
            var result = await _collection.DeleteOneAsync(filterDefinition);
            return result.DeletedCount &amp;gt; 0;
        }

        public async Task&amp;lt;List&amp;lt;SuperHero&amp;gt;&amp;gt; GetAll()
        {
            return await _collection.Find(Builders&amp;lt;SuperHero&amp;gt;.Filter.Empty).ToListAsync();
        }

        public async Task&amp;lt;SuperHero&amp;gt; GetById(string id)
        {
            var filterDefinition = Builders&amp;lt;SuperHero&amp;gt;.Filter.Eq(a =&amp;gt; a.Id, id);
            return await _collection.Find(filterDefinition).FirstAsync();
        }

        public async Task&amp;lt;bool&amp;gt; Update(SuperHero hero)
        {
            var filterDefinition = Builders&amp;lt;SuperHero&amp;gt;.Filter.Eq(a=&amp;gt;a.Id, hero.Id);
            var result = await _collection.ReplaceOneAsync(filterDefinition, hero);
            return result.ModifiedCount &amp;gt; 0;
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you need to create your controller that will receive by dependency injection the ISuperHeroRepository. In the Http methods you will call the respective CRUD action.&lt;/p&gt;

&lt;p&gt;Lets see the GetAll example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F69eldlbczx2p2o1kyhpq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F69eldlbczx2p2o1kyhpq.png" alt="Image description" width="686" height="99"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Another interesting thing is the way how we filter some query with MongoDB Drive.&lt;/p&gt;

&lt;p&gt;In this example, I'm filtering the collection only by the super hero id.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuwvj7f35gnu6s5smd2vd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuwvj7f35gnu6s5smd2vd.png" alt="Image description" width="582" height="115"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And that's it guys, just sharing my learning with someone.&lt;/p&gt;

&lt;p&gt;The source code in the my &lt;a href="https://github.com/iamlobito/CRUD-for-MongoDB"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Feel free to clone and happy coding!&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>mongodb</category>
      <category>aspdotnet</category>
      <category>api</category>
    </item>
    <item>
      <title>Repository Pattern in c#</title>
      <dc:creator>Lobito</dc:creator>
      <pubDate>Fri, 08 Mar 2024 10:35:56 +0000</pubDate>
      <link>https://forem.com/iamlobito/repository-pattern-in-c-202k</link>
      <guid>https://forem.com/iamlobito/repository-pattern-in-c-202k</guid>
      <description>&lt;p&gt;Any good software must be guided by design patterns. Design patterns are nothing more, nothing less than a set of best practices and mechanisms to make the code more robust, organized, and easy to maintain.&lt;/p&gt;

&lt;p&gt;There are different design patterns for different situations and today, we will focus on one of the most commonly used patterns: the Repository Pattern.&lt;/p&gt;

&lt;p&gt;The Repository Pattern is a design pattern commonly used in software development, particularly in applications that interact with databases or other data sources. It provides an abstraction layer between the application's business logic and the data access logic.&lt;/p&gt;

&lt;p&gt;In essence, the Repository Pattern involves creating an interface or class (the repository) that defines methods for accessing data, such as querying, adding, updating, and deleting records. This repository acts as a mediator between the application's code and the data storage mechanism, abstracting away the details of how data is retrieved and manipulated.&lt;/p&gt;

&lt;p&gt;With a repository pattern and the abstraction it provides, it's very simple, for example, to switch databases in an application. Let's imagine that we want to switch from a SQL Server database to MongoDB. All that will be needed is to implement a new repository implementation to apply the logic to MongoDB.&lt;/p&gt;

&lt;p&gt;I'll present here a simple example of implementing a repository for a customer API. This API will have the following methods: GetAll, GetById, and Add.&lt;/p&gt;

&lt;p&gt;The first thing to do is to create an interface that will define the repository contract. In this case, the interface will require the implementation of the &lt;code&gt;GetAll&lt;/code&gt;, &lt;code&gt;GetById&lt;/code&gt;, and &lt;code&gt;Add&lt;/code&gt; methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface ICustomerRepository
    {
        Task&amp;lt;Customer&amp;gt; GetById(int id);
        Task&amp;lt;List&amp;lt;Customer&amp;gt;&amp;gt; GetAll();
        Task&amp;lt;Customer&amp;gt; Add(Customer customer);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And our Customer model is a simple class with the following fields:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; [Table("customer")]
    public class Customer
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column("customer_id")]
        public int CustomerId { get; set; }
        [Column("customer_name")]
        public string CustomerName { get; set; }
        [Column("mobile_no")]
        public string MobileNumber { get; set; }
        [Column("email")]
        public string Email { get; set; }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the interface created, the next step is to implement these methods in a class called &lt;code&gt;CustomerRepository&lt;/code&gt;, which will implement the previously created interface &lt;code&gt;ICustomerRepository&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CustomerRepository : ICustomerRepository
    {
        private readonly CustomerDbContext _customerDbContext;

        public CustomerRepository(CustomerDbContext customerDbContext)
        {
            _customerDbContext = customerDbContext;
        }

        public async Task&amp;lt;Customer&amp;gt; Add(Customer customer)
        {

            var result = _customerDbContext.Customers.Add(customer);
            await _customerDbContext.SaveChangesAsync();
            return result.Entity;    
        }

        public async Task&amp;lt;Customer&amp;gt; GetById(int id)
        {
            return await _customerDbContext.Customers.FirstOrDefaultAsync(a =&amp;gt; a.CustomerId == id);
        }

        public async Task&amp;lt;List&amp;lt;Customer&amp;gt;&amp;gt; GetAll()
        {
            return await _customerDbContext.Customers.ToListAsync();
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this application, I'm using a local SQL Server database to store information, but let's keep the example simple and leave the database for another example.&lt;/p&gt;

&lt;p&gt;Now, what we need to do is create the controller for our API, which will call our repository. This controller will receive the repository via dependency injection, allowing it to access all the methods implemented earlier.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Route("api/[controller]")]
    [ApiController]
    public class CustomerController : ControllerBase
    {
        private readonly ICustomerRepository _customerRepository;
        public CustomerController(ICustomerRepository customerRepository)
        {
            _customerRepository = customerRepository;
        }

        [HttpGet]
        [Route("getAll")]
        public ActionResult&amp;lt;IEnumerable&amp;lt;Customer&amp;gt;&amp;gt; GetCustomers()
        {
            return _customerRepository.GetAll().Result;
        }

        [HttpGet]
        [Route("{id}")]
        public ActionResult&amp;lt;Customer&amp;gt; GetCustomers(int id)
        {
            return _customerRepository.GetById(id).Result;
        }

        [HttpPost]
        [Route("add")]
        public ActionResult&amp;lt;Customer&amp;gt; Create([FromBody]Customer customer)
        {
            var newCustomer =   _customerRepository.Add(customer).Result;
            return Ok(newCustomer);
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see in the controller, we receive the repository via dependency injection and assign it in the constructor. Then, in each of the REST methods, we access the repository through the "_customerRepository".&lt;/p&gt;

&lt;p&gt;The last thing to do is register our repository implementation in the C# dependency container. To do this, in the &lt;code&gt;Program.cs&lt;/code&gt;, we'll register our implementation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.Services.AddScoped&amp;lt;ICustomerRepository, CustomerRepository&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can find this example in my github repository:&lt;br&gt;
&lt;a href="https://github.com/iamlobito/MicroServicesSolution"&gt;Github&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>SOLID Principles</title>
      <dc:creator>Lobito</dc:creator>
      <pubDate>Tue, 05 Mar 2024 21:54:21 +0000</pubDate>
      <link>https://forem.com/iamlobito/solid-principles-8eg</link>
      <guid>https://forem.com/iamlobito/solid-principles-8eg</guid>
      <description>&lt;p&gt;As a software developer for a decade, I've come to realize that myself and a significant percentage of programmers are not prioritizing good practices, or at least, these concerns are not among our top priorities.&lt;br&gt;
However, I decide revert this and learn to become a better professional. &lt;/p&gt;

&lt;p&gt;I’m writing these articles as my personal notes and hope motivate you to be a better programmer as well.&lt;/p&gt;

&lt;p&gt;So let’s start for the beginning: SOLID principles!&lt;/p&gt;

&lt;p&gt;The SOLID principles are a set of five design principles intended to make software designs more understandable, flexible, and maintainable. They are:&lt;/p&gt;

&lt;p&gt;1 - &lt;strong&gt;Single Responsibility Principle (SRP)&lt;/strong&gt;: A class should have only one reason to change, meaning it should have only one responsibility or job.&lt;br&gt;
We all did the mistake to have a huge class that do more than one thing and different things with different contexts.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
public class UserManagementSystem
{
    public void AddUser(User user)
    {
        // Add user to the database
    }

    public void DeleteUser(User user)
    {
        // Delete user from the database
    }

    public void SendEmailToUser(User user, string message)
    {
        // Send email to the user
    }

    public void GenerateReportForUser(User user)
    {
        // Generate report for the user
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the UserManagementSystem class is responsible for multiple tasks: adding/deleting users, sending emails, and generating reports. This violates the SRP because the class has multiple reasons to change: if the database structure changes, if the email service changes, or if the report generation logic changes. It would be better to separate these responsibilities into distinct classes.&lt;/p&gt;

&lt;p&gt;2 -  &lt;strong&gt;Open/Closed Principle (OCP)&lt;/strong&gt;: Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. This means that you should be able to add new functionality without altering existing code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
public class Shape
{
    public string Type { get; set; }

    public double Area()
    {
        if (Type == "Rectangle")
        {
            Rectangle rectangle = new Rectangle();
            return rectangle.Length * rectangle.Width;
        }
        else if (Type == "Circle")
        {
            Circle circle = new Circle();
            return Math.PI * Math.Pow(circle.Radius, 2);
        }
        // More shapes and calculations can be added here, but violates OCP
        else
        {
            throw new InvalidOperationException("Unsupported shape type");
        }
    }
}

public class Rectangle
{
    public double Length { get; set; }
    public double Width { get; set; }
}

public class Circle
{
    public double Radius { get; set; }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the Shape class contains a method to calculate the area based on different shapes such as rectangles and circles. However, if a new shape is introduced, such as a triangle, the Area() method in the Shape class would need to be modified to accommodate the new shape. This violates the OCP because the class is not closed for modification; instead, it requires modification whenever a new shape is added.&lt;/p&gt;

&lt;p&gt;3 - &lt;strong&gt;Liskov Substitution Principle (LSP)&lt;/strong&gt;: Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. In other words, derived classes should be substitutable for their base classes without altering the desirable properties of the program.&lt;/p&gt;

&lt;p&gt;4 - &lt;strong&gt;Interface Segregation Principle (ISP)&lt;/strong&gt;: A client should not be forced to depend on interfaces it does not use. Instead of one large interface, it is better to have smaller, specific interfaces.&lt;/p&gt;

&lt;p&gt;5 - &lt;strong&gt;Dependency Inversion Principle (DIP)&lt;/strong&gt;: High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions. This principle promotes loose coupling between software modules.&lt;/p&gt;

</description>
      <category>solid</category>
      <category>softwareengineering</category>
      <category>architecture</category>
    </item>
  </channel>
</rss>
