<?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 Dilakshan Antony Thevathas on Medium]]></title>
        <description><![CDATA[Stories by Dilakshan Antony Thevathas on Medium]]></description>
        <link>https://medium.com/@atdilakshan?source=rss-4a33dfff0491------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lxHE04uQEzwK8K8SdlBM4Q.jpeg</url>
            <title>Stories by Dilakshan Antony Thevathas on Medium</title>
            <link>https://medium.com/@atdilakshan?source=rss-4a33dfff0491------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:56:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@atdilakshan/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[Why double to decimal Conversion Changed in .NET 11 | by AT Dilakshan]]></title>
            <link>https://atdilakshan.medium.com/why-double-to-decimal-conversion-changed-in-net-11-by-at-dilakshan-358eb7a18dd4?source=rss-4a33dfff0491------2</link>
            <guid isPermaLink="false">https://medium.com/p/358eb7a18dd4</guid>
            <category><![CDATA[dotnet-11-features]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-11]]></category>
            <category><![CDATA[dot-net-core]]></category>
            <category><![CDATA[dotnet-breaking-changes]]></category>
            <dc:creator><![CDATA[Dilakshan Antony Thevathas]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 14:05:38 GMT</pubDate>
            <atom:updated>2026-11-13T14:22:58.245Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why double to decimal Conversion Changed in .NET 11</h3><p>A .NET 11 upgrade can change the result of converting a double or float to a decimal. The same code may produce a different decimal value than it did on .NET 10 or earlier.</p><p>This article explains the old behavior, shows one example with the same code on both runtimes, and provides a migration checklist.</p><figure><img alt="Why double to decimal Conversion Changed in .NET 11 | AT Dilakshan" src="https://cdn-images-1.medium.com/max/1024/1*RBbOMMU2fjXwOtCDWDAOng.jpeg" /><figcaption>Why double to decimal Conversion Changed in .NET 11 | AT Dilakshan</figcaption></figure><p><strong>Experiment repository:</strong> <a href="https://github.com/atdilakshan/dotnet-10-11-double-decimal-conversion-research">Double-to-Decimal Conversion Research</a></p><h3>A quick reminder: double and decimal</h3><p>Both types store numbers, but they use different systems:</p><ul><li>double Stores numbers in binary. It can represent a very wide range, but many decimal fractions are stored as nearby values rather than exactly.</li><li>decimal Stores numbers using a base-10 scaled representation. It is useful for values such as prices, where decimal fractions are common.</li></ul><p>For example, 0.1 cannot be represented exactly as a binary fraction, so a double stores a nearby value. This is normal floating-point behavior.</p><h3>What happened in .NET 10 and earlier?</h3><p>Before .NET 11, converting a double to decimal kept about 15 significant decimal digits. Converting a float kept about 7. This often made the converted result look like the short decimal number a developer had written, even though the floating-point value stored by the program was only an approximation.</p><p>That behavior could hide the difference between a binary floating-point value and a decimal value. The conversion could also lose significant digits or round through an intermediate value.</p><h3>What changed in .NET 11?</h3><p>Starting in .NET 11 Preview 7, conversions between decimal and binary floating-point types were changed to round the exact source value once to the nearest value the destination type can represent.</p><p>In simple terms, .NET 11 pays closer attention to the actual number stored in the double or float. When that stored value is converted to decimal, additional digits may appear. The change is intended to produce correctly rounded results. <a href="https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/11/decimal-biginteger-floating-point-conversions">Microsoft documents the change and its compatibility impact</a>.</p><h4>The same code before and after the upgrade</h4><p>Imagine an application receives a measurement as a double and checks whether it matches a decimal threshold. Here is the same code on both runtimes:</p><pre>double reading = 0.1;<br>decimal threshold = 0.1m;<br>decimal convertedReading = (decimal)reading;<br><br>Console.WriteLine(convertedReading);<br>Console.WriteLine(convertedReading == threshold);</pre><p>The conversion result differs:</p><figure><img alt="Why double to decimal Conversion Changed in .NET 11 | The conversion result differs | AT Dilakshan" src="https://cdn-images-1.medium.com/max/1024/1*-GOFCJaGU2N1dgliyAxOSw.jpeg" /><figcaption>The conversion result differs | AT Dilakshan</figcaption></figure><p>The double reading does not change when the application is upgraded. The conversion to decimal now more faithfully represents the value that was already stored in that double.</p><p>In a real application, this could affect a threshold check, a test expectation, or a value written to a file or database. This example illustrates a possible effect; an application is affected only if it performs this kind of conversion and relies on the converted value.</p><h4>Why does the new result have more digits?</h4><p>A double stores numbers using a limited number of binary digits. When that stored value is converted to decimal, .NET 11 finds the nearest decimal value that decimal can represent. More digits may be needed to describe that value closely.</p><p>The conversion does not look back at the source code and recover the text 0.1. It works with the number already in memory.</p><p>These declarations therefore have different meanings:</p><pre>double approximate = 0.1;<br>decimal decimalNumber = 0.1m;</pre><p>The m suffix makes the second literal a decimal from the beginning.</p><h3>After migrating to .NET 11: a checklist</h3><p>Use this checklist to find and review code that could rely on the old behavior:</p><ul><li>[ ] <strong>Search for conversions.</strong> Look for casts such as (decimal)value, conversions from float or double, and helper methods that perform them.</li><li>[ ] <strong>Trace how each result is used.</strong> Check comparisons, calculations, rounding, database writes, serialized data, and values sent to other systems.</li><li>[ ] <strong>Run representative inputs on both runtimes.</strong> Use the same source and include normal values and relevant boundaries.</li><li>[ ] <strong>Review equality checks.</strong> Confirm that exact equality is intended, or decide whether the requirement calls for an explicit rounding rule or tolerance.</li><li>[ ] <strong>Check rounding rules.</strong> Define the scale and midpoint behavior from the application’s requirements.</li><li>[ ] <strong>Review tests and saved outputs.</strong> Change expected values only after deciding which behavior is correct for the application.</li><li>[ ] <strong>Choose the type at the data boundary.</strong> If a value is decimal by nature, such as a price, parse and store it as decimal instead of routing it through double.</li><li>[ ] <strong>Preserve legacy results only when required.</strong> Microsoft’s guidance says rounding a converted double to 15 significant decimal digits, or a float to 7 significant decimal digits, can generally reproduce previous results. This intentionally discards precision, so verify it with representative tests.</li></ul><p>There is no switch that restores the old conversion algorithm globally. Apply a compatibility adjustment only where the old result is an explicit requirement.</p><h3>Which type should I use?</h3><p>Use decimal when the value is defined in decimal terms and decimal rounding matters, such as prices or tax amounts:</p><pre>decimal unitPrice = 12.50m;<br>decimal taxRate = 0.08m;<br>decimal tax = unitPrice * taxRate;</pre><p>Use double when approximate real-number calculations and a wide range are appropriate, such as many scientific, engineering, graphics, or measurement tasks. The .NET 11 change does not make double unsuitable; it changes what happens when a floating-point value is converted to decimal.</p><p>If conversion is necessary and the result must be rounded, make that choice explicit:</p><pre>decimal roundedAmount = decimal.Round(<br>    convertedAmount,<br>    2,<br>    MidpointRounding.ToEven);</pre><p>Two decimal places and midpoint-to-even are examples, not universal rules. Use the scale and rule required by the application. Rounding for display may differ from rounding the value used in calculations.</p><h3>Key takeaway</h3><p>Before .NET 11, conversions from floating-point values to decimal kept a limited number of significant digits. In .NET 11, conversion reflects the exact floating-point value already stored and rounds it once to the nearest representable destination value.</p><p>If the data is decimal, use decimal from the start. If an application depends on conversion results, test during migration and define rounding or compatibility behavior explicitly.</p><h3>Further reading</h3><ul><li><a href="https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/11/decimal-biginteger-floating-point-conversions">Breaking change: Decimal and BigInteger floating-point conversions are correctly rounded</a></li><li><a href="https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-11/libraries">What’s new in .NET 11 libraries</a></li></ul><h4>Happy Coding ✨ Fellows 🙂</h4><blockquote><strong><em>If you enjoy my content, please consider buying me a coffee to support my work: </em></strong><a href="https://www.buymeacoffee.com/atdilakshan"><strong><em>Buy me a coffee</em></strong></a></blockquote><blockquote>Follow me on <a href="https://www.linkedin.com/in/atdilakshan/">LinkedIn</a><br>Follow me on <a href="https://github.com/atdilakshan">GitHub</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=358eb7a18dd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Database Management with Stored Procedures]]></title>
            <link>https://atdilakshan.medium.com/efficient-database-management-with-stored-procedures-0d7fe2753d39?source=rss-4a33dfff0491------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d7fe2753d39</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database-management]]></category>
            <category><![CDATA[database-performance]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[stored-procedure]]></category>
            <dc:creator><![CDATA[Dilakshan Antony Thevathas]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 04:32:13 GMT</pubDate>
            <atom:updated>2024-09-03T04:32:13.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Efficient Database Management with Stored Procedures || Dilakshan AT" src="https://cdn-images-1.medium.com/max/1024/1*wklkFtDNAHJAHsTNApo8iQ.jpeg" /><figcaption>Efficient Database Management with Stored Procedures || Dilakshan AT</figcaption></figure><blockquote><em>Discover the power of stored procedures in SQL databases! Learn how they boost performance, ensure consistency, and enhance security.</em></blockquote><h3>What is the Stored Procedure?</h3><p>A stored procedure is a <strong>precompiled</strong> collection of one or more SQL statements saved under a name and processed as a unit. Stored procedures are commonly used in relational databases to <strong>encapsulate</strong> complex business logic or repetitive database operations, offering several advantages in terms of <strong>performance</strong>, <strong>security</strong>, and <strong>maintainability</strong>.</p><p>This time, there’s a common question on everyone’s mind: <strong>why can’t we create stored procedures in non-relational databases like MongoDB and Redis</strong>?</p><p>Stored procedures are less common in non-relational (NoSQL) databases, as these databases often do not use SQL and focus on different models (Ex: key-value, document, etc). However, some NoSQL databases offer similar functionality through other means:</p><p>MongoDB: It allows the use of JavaScript functions stored on the server, called “<strong>stored JavaScript</strong>.” Learn more <a href="https://www.mongodb.com/resources/products/capabilities/stored-procedures">here</a>.</p><p>Redis: Supports Lua scripting for executing server-side logic. Learn more <a href="https://redis.io/docs/latest/develop/interact/programmability/">here</a>.</p><p>In this article, we’ll learn about, <strong>Stored Procedures in relational databases (SQL)</strong>.</p><h3>Stored Procedure in SQL (Relational database)</h3><p>As we previously see, the Stored Procedure (<strong>SP</strong>) is a group of SQL statements that perform a specific task. Once a Stored Procedure is written and stored in a <strong>database management system (DBMS)</strong>, it can be executed repeatedly without needing to rewrite the SQL commands.</p><p><strong>Where is Store:</strong> The compiled version of the procedure is saved in the DBMS catalog, making it available for repeated execution without needing recompilation.</p><p><strong>How it works:</strong> When you execute a stored procedure, the DBMS runs the precompiled set of SQL commands in sequence.</p><h4>Advantages</h4><ul><li><strong>Performance / Efficiency:</strong> Since SPs are precompiled, they often run faster than if the SQL statements were written and executed individually.</li><li><strong>Consistency:</strong> Every time the procedure is executed, it performs the same sequence of operations, ensuring consistent results.</li><li><strong>Reusability:</strong> You can call the same SP from multiple programs or places in your application, which ensures consistency and reduces redundancy.</li><li><strong>Reduced Network Traffic:</strong> When an operation involves a complex series of SQL commands, executing it as a stored procedure can significantly reduce network traffic. Instead of transmitting multiple SQL statements from the application to the database server, a single call to the stored procedure is made, allowing all operations to be executed on the server side.</li><li><strong>Security:</strong> SPs can help control access to data by restricting user actions through defined procedures rather than giving direct access to tables.</li><li><strong>Maintenance:</strong> Changes to business logic can be made in the stored procedure without modifying the application code</li></ul><h4>Drawbacks of Stored Procedures</h4><ul><li><strong>Complexity:</strong> Overuse of stored procedures can lead to complex, hard-to-maintain code, especially if business logic is heavily embedded in the database layer.</li><li><strong>Performance Overhead:</strong> While stored procedures can enhance performance, they can also introduce overhead if not optimized properly, especially in large-scale systems.</li><li><strong>Limited Debugging:</strong> Debugging stored procedures can be challenging, especially compared to application code, where more sophisticated debugging tools are available.</li><li><strong>Vendor Lock-In:</strong> Stored procedures are usually written in a specific type of SQL that only works with one particular database system. This means that if you want to switch to a different database in the future, it can be challenging and time-consuming because the stored procedures may not work with the new system.</li></ul><h4>Types of Stored Procedures</h4><p>Stored procedures can be categorized into several types, depending on their <strong>functionality and scope</strong>:</p><ul><li><strong>System Stored Procedures:</strong> Provided by the DBMS, these procedures are used to perform administrative tasks such as managing databases, users, and system configurations. Learn more <a href="https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/stored-procedures-database-engine?view=sql-server-ver16#system">here</a>.</li><li><strong>User-Defined Stored Procedures:</strong> Created by the user to perform specific tasks such as data manipulation, business logic implementation, or custom calculations. Learn more <a href="https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/stored-procedures-database-engine?view=sql-server-ver16#user-defined">here</a>.</li><li><strong>Temporary Stored Procedures:</strong> These procedures are created temporarily during a session and are automatically dropped when the session ends. They are typically used for temporary operations that don’t need to be persistent. Learn more <a href="https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/stored-procedures-database-engine?view=sql-server-ver16#temporary">here</a>.</li><li><strong>Remote Stored Procedures:</strong> These are stored procedures executed on a remote database server, allowing distributed operations across multiple databases.</li></ul><h4>Best Practices for Writing Stored Procedures</h4><ul><li><strong>Error Handling:</strong> Use TRY…CATCH blocks to manage exceptions during execution.</li><li><strong>Transaction Management:</strong> Enclose related operations within transactions using BEGIN TRANSACTION, COMMIT, and ROLLBACK.</li><li><strong>Input Validation:</strong> Validate input parameters to ensure they meet expected formats, types, and ranges.</li><li><strong>Use of Parameters:</strong> Utilize parameters to pass values into and out of stored procedures.</li><li><strong>Avoid Cursors:</strong> Prefer set-based operations over cursors for processing rows.</li><li><strong>Modular Design:</strong> Break down complex logic into smaller, reusable stored procedures.</li><li><strong>Minimize Dependencies:</strong> Design procedures to be independent, avoiding hard-coded references to specific tables or columns.</li><li><strong>Security Considerations:</strong> Implement necessary security measures, such as restricting access to sensitive data and using encryption.</li><li><strong>Commenting in Procedure:</strong> Use comments to document the purpose, parameters, and complex logic of the stored procedure.</li><li><strong>Use SET NOCOUNT ON:</strong> Include SET NOCOUNT ON at the beginning of your stored procedure.</li></ul><h3>Takeaway</h3><p>Stored procedures play a crucial role in relational databases by <em>encapsulating</em> SQL statements into a reusable and efficient unit. They improve performance, ensure consistent results, and enhance security. However, they can become complex, and debugging them might be challenging. Additionally, switching databases can be tricky due to compatibility issues.</p><p>Non-relational databases like MongoDB and Redis use different approaches, such as JavaScript functions and Lua scripting, for similar purposes.</p><p>By following best practices like error handling, managing transactions, and validating inputs, you can make the most of stored procedures while avoiding common pitfalls.</p><h4>Happy Coding ✨ Fellows 🙂</h4><blockquote><strong>If you enjoy my content, please consider buying me a coffee to support my work: </strong><a href="https://www.buymeacoffee.com/atdilakshan"><strong><em>Buy me a coffee</em></strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d7fe2753d39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy an Angular App to GitHub Pages With Angular CLI]]></title>
            <link>https://atdilakshan.medium.com/deploy-an-angular-app-to-github-pages-with-angular-cli-92a2d6fe6533?source=rss-4a33dfff0491------2</link>
            <guid isPermaLink="false">https://medium.com/p/92a2d6fe6533</guid>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[github-pages]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Dilakshan Antony Thevathas]]></dc:creator>
            <pubDate>Sat, 06 May 2023 18:40:29 GMT</pubDate>
            <atom:updated>2023-05-06T18:40:29.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Deploy an Angular App to GitHub Pages With Angular CLI || AT Dilakshan" src="https://cdn-images-1.medium.com/max/1024/1*yd3L0qeB3_N4BlhCRhx3iQ.jpeg" /><figcaption>Deploy an Angular App to GitHub Pages With Angular CLI</figcaption></figure><h3>Angular</h3><p>Angular is a popular <strong>JavaScript framework</strong> for building <strong>single-page applications</strong>.</p><h3>Deploy the angular app on GitHub</h3><p>Deploying Angular applications to <strong>GitHub pages</strong> is a great way to host them for <em>free</em>.</p><p>First, you need the Angular Application.</p><p>Create the gh-pages git branch.</p><pre>git branch gh-pages</pre><p>Next, check out from the main branch to gh-pages to transfer all code.</p><pre>git checkout gh-pages</pre><p>Create the GitHub repository in your GitHub account.</p><p>Push the gh-pages to the remote repository.</p><pre>git push -u origin gh-pages</pre><p>Get the repo link.</p><p>Goto the settings for your repository.</p><p>In the pages tab, the Build and Deployment section sets the sources to Deploy from a branch.</p><p>Then change the branch to gh-pages and select the root folder.</p><h3>Install Angular-CLI-GHpages</h3><p>After that, install the Angular-CLI-GHpages.</p><p>The angular-cli-ghpages package is a tool that the Angular CLI uses for deployment purposes.</p><p>Navigate back to your local project repository. Then install and run angular-cli-ghpages with this command:</p><pre>ng add angular-cli-ghpages</pre><h3>Deploy the App</h3><p>Then deploy the app remotely.</p><p>To build the app in production, you must connect it to a remote server on GitHub.</p><p>Configure your app to a remote server by running the following command:</p><pre>ng deploy --base-href=https://GithubUserName.github.io/GithubRepoName/</pre><p>Now, you can find your Angular project on online. (<a href="https://githubusername.github.io/GithubRepoName/">https://www.userName.github.io/repoName</a>)</p><p><strong>If you enjoy my content, please consider buying me a coffee to support my work: </strong><a href="https://www.buymeacoffee.com/atdilakshan"><strong><em>https://www.buymeacoffee.com/atdilakshan</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92a2d6fe6533" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refit Library Introduction and Setup In .NET]]></title>
            <link>https://atdilakshan.medium.com/refit-library-introduction-and-setup-in-net-f1a074166966?source=rss-4a33dfff0491------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1a074166966</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[refit]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[dotnet6]]></category>
            <dc:creator><![CDATA[Dilakshan Antony Thevathas]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 04:42:07 GMT</pubDate>
            <atom:updated>2023-03-08T17:09:48.620Z</atom:updated>
            <content:encoded><![CDATA[<h3>Refit Library Introduction and Setup In .NET</h3><figure><img alt="Refit Library Introduction and Setup In .NET || AT Dilakshan || Dilakshan Antony Thevathas" src="https://cdn-images-1.medium.com/max/1024/1*0vaSmuA25qJfHoXsyEWklw.jpeg" /><figcaption>Refit Library Introduction and Setup In .NET</figcaption></figure><h3>Introduction</h3><p>In a distributed system, it is common to have different microservices that communicate with each other over a network. One way to implement this communication is through RESTful APIs, which allow services to exchange data in a standardized way. However, consuming RESTful APIs can be a cumbersome process, requiring a lot of boilerplate code for making <strong>HTTP requests</strong> and handling responses. This is where <strong>Refit</strong> comes in — a <strong>type-safe</strong> <strong>HTTP client</strong> library for .NET that simplifies the process of consuming RESTful APIs.</p><p>In this article, we will show how to use <strong>Refit</strong> in a .NET solution to consume multiple APIs and integrate the results.</p><h4>What is Refit?</h4><p><strong>Refit</strong> is a .NET package used to create <strong>type-safe</strong>, <strong>dynamic</strong>, and <strong>HTTP-based APIs</strong>. It enables programmers to create <strong>clear</strong>, <strong>simple code</strong> to use RESTful APIs.</p><p>Refit is built on top of the .NET <strong>HttpClient</strong> library, giving a simpler and more expressive interface for making <strong>HTTP requests</strong>.</p><h4>Refit vs HttpClient</h4><figure><img alt="Refit vs HttpClient || Refit Library Introduction and Setup In .NET || AT Dilakshan || Dilakshan Antony Thevathas" src="https://cdn-images-1.medium.com/max/1024/1*5L9zcLVZFQVcgI1LUXXwNQ.jpeg" /><figcaption>Refit vs HttpClient</figcaption></figure><blockquote><strong><em>Refit</em></strong></blockquote><blockquote>Provides a type-safe way to define an API using C# interfaces.</blockquote><blockquote>Generates a concrete implementation of an API interface at runtime.</blockquote><blockquote>Allows developers to define expected input and output types for each API endpoint.</blockquote><blockquote>Supports automatic serialization and deserialization of data.</blockquote><blockquote>Includes support for interceptors, allowing modification or logging of HTTP requests and responses.</blockquote><blockquote>Reduces the amount of boilerplate code required to work with an API.</blockquote><blockquote><strong><em>HttpClient</em></strong></blockquote><blockquote>Requires manually constructing HTTP requests.</blockquote><blockquote>Requires handling responses and deserializing JSON data manually.</blockquote><blockquote>Does not provide a built-in way to handle pagination, authentication, or other common features.</blockquote><blockquote>Requires manually handling serialization and deserialization of JSON data.</blockquote><blockquote>Does not provide a built-in way to intercept and modify HTTP requests and responses.</blockquote><blockquote>Can be verbose and repetitive when working with APIs.</blockquote><h4>Installation</h4><p>Using the <strong>NuGet package manager console</strong> within <strong>Visual Studio</strong> run the following command:</p><pre>NuGet\Install-Package Refit -Version 6.3.2</pre><p>Goto <strong>NuGet package manager</strong> and Install <strong><em>Refit</em></strong> Package.</p><h3>Setup</h3><h4>Example</h4><p>We need some <strong>dependencies</strong> to run this example.</p><blockquote>Refit</blockquote><blockquote>Refit.HttpClientFactory</blockquote><p>In this example, we have a .NET solution that consists of three projects: <strong>StudentsProj.API</strong>, <strong>SubjectsProj.API</strong>, and <strong>StudentSubjectProj.API </strong>exposes RESTful APIs that allow you to retrieve data about students and subjects, respectively.</p><p><strong>StudentSubjectProj.API</strong> is a project that depends on the other two projects and needs to consume their APIs to retrieve data about students and subjects and integrate them.</p><h4>Solution architecture</h4><p>The solution architecture is as follows:</p><figure><img alt="Folder Structure || Refit Library Introduction and Setup In .NET || AT Dilakshan || Dilakshan Antony Thevathas" src="https://cdn-images-1.medium.com/max/505/1*KORjyBzeBCILpIl2hzRiHw.png" /><figcaption>Folder Structure</figcaption></figure><p>The solution is structured into three projects: <strong>StudentsProj.API</strong>, <strong>SubjectsProj.API</strong>, and <strong>StudentSubjectProj.API</strong>.</p><p>The <strong>StudentsProj.API and SubjectsProj.API</strong> projects are responsible for managing <strong>students</strong> and <strong>subjects</strong> data, respectively.</p><p>The <strong>StudentSubjectProj.API</strong> project acts as an aggregator, providing a unified API to retrieve information about both students and subjects.</p><p><strong>ISubjectsApiClient.cs </strong>(StudentSubjectProj.API → Clients)</p><pre>using Refit;<br>using StudentSubjectProj.API.Models;<br><br>namespace StudentSubjectProj.API.Clients<br>{<br>    public interface ISubjectsApiClient<br>    {<br>        [Get(&quot;/subjects&quot;)] // &quot;/subjects&quot; is endpoint of get all subjects in SubjectsProj.API Project<br>        Task&lt;IEnumerable&lt;Subjects&gt;&gt; GetAllSubjects();<br>    }<br>}</pre><p><strong>IStudentsApiClient.cs</strong> (StudentSubjectProj.API → Clients)</p><pre>using Refit;<br>using StudentSubjectProj.API.Models;<br><br>namespace StudentSubjectProj.API.Clients<br>{<br>    public interface IStudentsApiClient<br>    {<br>        [Get(&quot;/students&quot;)] // &quot;/students&quot; is endpoint of get all students in StudentsProj.API Project<br>        Task&lt;IEnumerable&lt;Students&gt;&gt; GetAllStudents();<br>    }<br>}</pre><p><strong>StudentSubjectRepository.cs</strong> (StudentSubjectProj.API → Repositories)</p><pre>using StudentSubjectProj.API.Clients;<br>using StudentSubjectProj.API.Models;<br><br>namespace StudentSubjectProj.API.Repositories<br>{<br>    public class StudentSubjectRepository : IStudentSubjectRepository<br>    {<br>        private readonly IStudentsApiClient studentsApiClient;<br>        private readonly ISubjectsApiClient subjectsApiClient;<br><br>        public StudentSubjectRepository(IStudentsApiClient studentsApiClient, ISubjectsApiClient subjectsApiClient)<br>        {<br>            this.studentsApiClient = studentsApiClient;<br>            this.subjectsApiClient = subjectsApiClient;<br>        }<br>        public Task&lt;IEnumerable&lt;Students&gt;&gt; GetAllStudentsAsync()<br>        {<br>            return studentsApiClient.GetAllStudents();<br>        }<br>        public Task&lt;IEnumerable&lt;Subjects&gt;&gt; GetAllSubjectsAsync()<br>        {<br>            return subjectsApiClient.GetAllSubjects();<br>        }<br>    }<br>}</pre><p>The <strong>StudentSubjectProj.API</strong> project has a <strong>StudentSubjectRepository</strong> class that depends on the <strong>IStudentsApiClient</strong> and <strong>ISubjectsApiClient</strong> interfaces.</p><p>These interfaces are defined in the StudentSubjectProj.API.Clients namespace and specify the endpoints to retrieve data from the <strong>StudentsProj.API</strong> and <strong>SubjectsProj.API</strong> projects.</p><p>The <strong>StudentSubjectRepository</strong> class uses the <strong><em>Refit</em></strong> library to generate the implementation of these interfaces, which enables it to make HTTP requests to the endpoints specified in the interfaces.</p><p><strong>Program.cs</strong> (StudentSubjectProj.API)</p><pre>using Refit;<br>using StudentSubjectProj.API.Clients;<br><br>... // other contents<br><br>// Set base URL for Refit -- StudentsProj.API<br>string studentsBaseUrl = &quot;https://localhost:7183&quot;;<br>builder.Services.AddScoped&lt;IStudentsApiClient&gt;(x =&gt; RestService.For&lt;IStudentsApiClient&gt;(studentsBaseUrl));<br><br>// Set base URL for Refit -- SubjectsProj.API<br>string subjectsBaseUrl = &quot;https://localhost:7021&quot;;<br>builder.Services.AddScoped&lt;ISubjectsApiClient&gt;(x =&gt; RestService.For&lt;ISubjectsApiClient&gt;(subjectsBaseUrl));<br><br>... // other contents<br><br>var app = builder.Build();<br><br>... // other contents</pre><p>In the <strong>Program.cs</strong> file of the <strong>StudentSubjectProj.API</strong> project, the base URLs for the <strong>StudentsProj.API</strong> and <strong>SubjectsProj.API</strong> projects are set using the <em>AddScoped</em> method of the IServiceCollection interface.</p><p>The base URLs are then passed to the <em>RestService.For </em>method of the <strong>Refit</strong> library, which generates the implementations of the <strong>IStudentsApiClient</strong> and <strong>ISubjectsApiClient</strong> interfaces.</p><p>By using <strong>Refit</strong>, the <strong>StudentSubjectProj.API</strong> project can make HTTP requests to the <strong>StudentsProj.API</strong> and <strong>SubjectsProj.API</strong> projects without having to manually manage the HTTP request and response objects. This simplifies the code and makes it more readable.</p><p>In addition to simplifying the code, using Refit also provides other benefits.</p><p>For example, it automatically deserializes JSON responses into C# objects, which can save time and effort when working with APIs.</p><p>Refit also provides a strongly typed API, which can help catch errors at compile-time instead of at runtime.</p><p>Overall, using <strong>Refit</strong> can be a great way to simplify the code and make it more maintainable when working with APIs.</p><p><strong>If you enjoy my content, please consider buying me a coffee to support my work: </strong><a href="https://www.buymeacoffee.com/atdilakshan"><strong><em>https://www.buymeacoffee.com/atdilakshan</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1a074166966" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Introduction And Configuration]]></title>
            <link>https://atdilakshan.medium.com/docker-introduction-and-configuration-fdecc5daafc5?source=rss-4a33dfff0491------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdecc5daafc5</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Dilakshan Antony Thevathas]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 03:56:33 GMT</pubDate>
            <atom:updated>2023-01-27T03:56:33.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Docker Introduction And Configuration" src="https://cdn-images-1.medium.com/max/1024/1*ObHvGGAs_5OX9k_z_whXpg.jpeg" /><figcaption>Docker Introduction And Configuration</figcaption></figure><h3>What is Docker?</h3><p>Docker is a platform and technology for <strong>building</strong>, <strong>shipping</strong>, and <strong>running </strong>distributed applications.</p><p>It’s <strong>open-source</strong>.</p><p>It uses <strong>containerization technology</strong>, which allows developers to package their applications and dependencies together in a single container.</p><p>This makes it easy to move the container between <strong>different environments</strong>, such as from development to production, without having to worry about compatibility issues.</p><h3>Container</h3><p>A container is a <strong>lightweight</strong>, <strong>standalone</strong>, and <strong>executable package</strong> of software that includes everything needed to run a piece of software, including the <strong>code</strong>, <strong>runtime</strong>, <strong>system tools</strong>, <strong>libraries</strong>, and <strong>settings</strong>.</p><p>Containers provide a way to package and distribute software in a way that is consistent across <strong>different environments</strong>, such as from development to production.</p><p>Containers are created from <strong>images</strong>, which are snapshots of a container’s file system and configuration.</p><p>Containers are <strong>isolated </strong>from each other and from the <strong>host system</strong>, which means that they can run independently of one another and of the host system. This makes containers a convenient way to run <strong>multiple applications</strong> on the same host without them interfering with each other.</p><h3>Images</h3><p>An image is a <strong>read-only template</strong> that contains all the necessary information to create a <strong>container</strong>.</p><p>An image is composed of multiple stacked layers, like layers in a photo editor, each changing something in the environment.</p><p>Images contain the code or binary, runtimes, dependencies, and other filesystem objects to run an application. The image relies on the host operating system (OS) kernel.</p><h3>Install Docker Desktop</h3><p><a href="https://www.docker.com/">Docker Official Website</a></p><p><strong>Install interactively</strong></p><p><a href="https://www.docker.com/products/docker-desktop/">Here</a> Download <em>Docker Desktop Installer.exe</em>.</p><p><strong>Install from the command line</strong></p><p>After downloading <em>Docker Desktop Installer.exe</em>, run the following command in a terminal to install Docker Desktop:</p><pre>&quot;Docker Desktop Installer.exe&quot; install</pre><h3>Configure</h3><p>Create <strong>Dockerfile</strong></p><p>If you already have a project, In visual studio, right-click the project folder and add <strong>Docker Support</strong>.</p><p>If you haven’t any project, <strong>Enable Docker</strong> when creating a project.</p><p><strong>Dockerfile</strong> Sample</p><pre>#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.<br><br>#Depending on the operating system of the host machines(s) that will build or run the containers, the image specified in the FROM statement may need to be changed.<br>#For more information, please see https://aka.ms/containercompat<br><br><br>#Specify image<br>FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base<br>ENV ASPNETCORE_ENVIRONMENT=DEVELOPMENT ## Environment setup (swagger)<br><br>WORKDIR /app<br>EXPOSE 80<br>EXPOSE 443<br><br>#Copy project file<br>FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build<br>WORKDIR /src<br>COPY [&quot;docker-test.csproj&quot;, &quot;.&quot;]<br>RUN dotnet restore &quot;./docker-test.csproj&quot;<br>#Copy and Build<br>COPY . .<br>WORKDIR &quot;/src/.&quot;<br>RUN dotnet build &quot;docker-test.csproj&quot; -c Release -o /app/build<br><br>FROM build AS publish<br>RUN dotnet publish &quot;docker-test.csproj&quot; -c Release -o /app/publish /p:UseAppHost=false<br><br># Build runtime image<br>FROM base AS final<br>WORKDIR /app<br>COPY --from=publish /app/publish .<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;docker-test.dll&quot;, &quot;--environment-Devlopment&quot;] #Starting the app</pre><p>To run in a <strong>Linux container</strong>, right-click the System Tray’s Docker client icon and select switch to <strong>Linux containers</strong>.</p><p>Navigate to the folder containing the <strong>Dockerfile </strong>in <strong>PowerShell</strong>.</p><p>Run the following commands to build the image in Docker:</p><pre>docker build -t {imagename}.</pre><p>Build and deploy manually</p><pre>dotnet publish -c Release -o published</pre><p>Run the app</p><p>For Windows:</p><pre>dotnet published\{imagename}.dll</pre><p>For Linux:</p><pre>dotnet published/{imagename}.dll</pre><p>Go to <a href="http://localhost:5000/"><em>http://localhost:5000</em></a> in a browser to test the app</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdecc5daafc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FluentValidation Introduction and Setup In .NET]]></title>
            <link>https://atdilakshan.medium.com/fluentvalidation-introduction-and-setup-in-net-1d1024812786?source=rss-4a33dfff0491------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d1024812786</guid>
            <category><![CDATA[fluent-validation]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Dilakshan Antony Thevathas]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 06:55:14 GMT</pubDate>
            <atom:updated>2023-02-20T11:37:25.265Z</atom:updated>
            <content:encoded><![CDATA[<h3>FluentValidation Introduction and Setup In .NET</h3><figure><img alt="FluentValidation Introduction and Setup In .NET || AT Dilakshan || Dilakshan Antony Thevathas" src="https://cdn-images-1.medium.com/max/1024/1*D8EUAOjWt3z-1UnXmxw4YQ.jpeg" /><figcaption>FluentValidation Introduction and Setup In .NET</figcaption></figure><h3>What is FluentValidation?</h3><p><strong>FluentValidation</strong> is a <strong>.NET library</strong> for building strongly-typed <strong>validation</strong> rules using a fluent interface.</p><p>It allows you to define <strong>validation </strong>rules for your domain <strong>models </strong>using a <strong>simple, readable syntax</strong>.</p><p>It can be used to <strong>validate user input</strong>, <strong>data from a database</strong>, or <strong>any other data in your application</strong>.</p><p>FluentValidation supports <strong>both synchronous and asynchronous validation</strong> and can be integrated with various frameworks and libraries such as <strong>ASP.NET Core, MVC, and Web API</strong>.</p><h3>Installation</h3><p>Using the <strong>NuGet package manager console</strong> within <strong>Visual Studio</strong> run the following command:</p><pre>Install-Package FluentValidation</pre><p>Goto <strong>NuGet package manager</strong> and Install <strong><em>FluentValidation</em></strong> Package.</p><h3>Basic Syntax</h3><pre>using FluentValidation;<br><br>namespace Project.Validators<br>{<br>    public class Validator_Name : AbstractValidator&lt;Model_Name&gt;<br>    {<br>        public Validator_Name()<br>        {<br>            RuleFor(x =&gt; x.Name).NotEmpty();  // Empty check<br>            RuleFor(x =&gt; x.Length).GreaterThan(0);  // GreaterThan check<br>        }<br>    }<br>}</pre><h3>Built-in Validators</h3><p><strong>Not Null Validator</strong></p><p>Ensures that the specified property is not null.</p><pre>RuleFor(customer =&gt; customer.Surname).NotNull();</pre><p><strong>Not Empty Validator</strong></p><p>Ensures that the specified property is not null, an empty string, or whitespace (or the default value for value types, e.g., 0 for int). When used on an IEnumerable (such as arrays, collections, lists, etc.), the validator ensures that the IEnumerable is not empty.</p><pre>RuleFor(customer =&gt; customer.Surname).NotEmpty();</pre><p><strong>Not Equal</strong></p><p>Ensures that the value of the specified property is not equal to a particular value (or not equal to the value of another property).</p><pre>//Not equal to a particular value<br>RuleFor(customer =&gt; customer.Surname).NotEqual(&quot;Foo&quot;);<br><br>//Not equal to another property<br>RuleFor(customer =&gt; customer.Surname).NotEqual(customer =&gt; customer.Forename);</pre><p><strong>Equal Validator</strong></p><p>Ensures that the value of the specified property is equal to a particular value (or equal to the value of another property).</p><pre>//Equal to a particular value<br>RuleFor(customer =&gt; customer.Surname).Equal(&quot;Foo&quot;);<br><br>//Equal to another property<br>RuleFor(customer =&gt; customer.Password).Equal(customer =&gt; customer.PasswordConfirmation);</pre><p><strong>Length Validator</strong></p><p>Ensures that the length of a particular string property is within the specified range. However, it doesn’t ensure that the string property isn’t null.</p><pre>RuleFor(customer =&gt; customer.Surname).Length(1, 250); //must be between 1 and 250 chars (inclusive)</pre><p><strong>Max Length Validator</strong></p><p>Ensures that the length of a particular string property is no longer than the specified value.</p><pre>RuleFor(customer =&gt; customer.Surname).MaximumLength(250); //must be 250 chars or fewer</pre><p><strong>Min Length Validator</strong></p><p>Ensures that the length of a particular string property is longer than the specified value.</p><pre>RuleFor(customer =&gt; customer.Surname).MinimumLength(10); //must be 10 chars or more</pre><p><strong>Less Than Validator</strong></p><p>Ensures that the value of the specified property is less than a particular value (or less than the value of another property) Example:</p><pre>//Less than a particular value<br>RuleFor(customer =&gt; customer.CreditLimit).LessThan(100);<br><br>//Less than another property<br>RuleFor(customer =&gt; customer.CreditLimit).LessThan(customer =&gt; customer.MaxCreditLimit);</pre><p><strong>Less Than Or Equal Validator</strong></p><p>Ensures that the value of the specified property is less than or equal to a particular value (or less than or equal to the value of another property) Example:</p><pre>//Less than a particular value<br>RuleFor(customer =&gt; customer.CreditLimit).LessThanOrEqualTo(100);<br><br>//Less than another property<br>RuleFor(customer =&gt; customer.CreditLimit).LessThanOrEqualTo(customer =&gt; customer.MaxCreditLimit);</pre><p><strong>Greater Than Validator</strong></p><p>Ensures that the value of the specified property is greater than a particular value (or greater than the value of another property) Example:</p><pre>//Greater than a particular value<br>RuleFor(customer =&gt; customer.CreditLimit).GreaterThan(0);<br><br>  //Greater than another property<br>  RuleFor(customer =&gt; customer.CreditLimit).GreaterThan(customer =&gt; customer.MinimumCreditLimit);</pre><p><strong>Greater Than Or Equal Validator</strong></p><p>Ensures that the value of the specified property is greater than or equal to a particular value (or greater than or equal to the value of another property) Example:</p><pre>//Greater than a particular value<br>RuleFor(customer =&gt; customer.CreditLimit).GreaterThanOrEqualTo(1);<br><br>//Greater than another property<br>RuleFor(customer =&gt; customer.CreditLimit).GreaterThanOrEqualTo(customer =&gt; customer.MinimumCreditLimit);</pre><p><strong>Predicate Validator</strong></p><p>Passes the value of the specified property into a delegate that can perform custom validation logic on the value.</p><pre>RuleFor(customer =&gt; customer.Surname).Must(surname =&gt; surname == &quot;Foo&quot;);</pre><p>Note that there is an additional overload for Must that also accepts an instance of the parent object being validated. This can be useful if you want to compare the current property with another property from inside the predicate:</p><pre>RuleFor(customer =&gt; customer.Surname).Must((customer, surname) =&gt; surname != customer.Forename)</pre><p><strong>Regular Expression Validator</strong></p><p>Ensures that the value of the specified property matches the given regular expression.</p><pre>RuleFor(customer =&gt; customer.Surname).Matches(&quot;some regex here&quot;);</pre><p><strong>Email Validator</strong></p><p>Ensures that the value of the specified property is a valid email address format.</p><pre>RuleFor(customer =&gt; customer.Email).EmailAddress();</pre><p><strong>Credit Card Validator</strong></p><p>Checks whether a string property could be a valid credit card number.</p><pre>RuleFor(x =&gt; x.CreditCard).CreditCard();</pre><p><strong>Enum Validator</strong></p><p>Checks whether a numeric value is valid to be in that enum. This is used to prevent numeric values from being cast to an enum type when the resulting value would be invalid. For example, the following is possible:</p><pre>public enum ErrorLevel <br>  {<br>     Error = 1,<br>     Warning = 2,<br>     Notice = 3<br>  }<br><br>  public class Model<br>  {<br>     public ErrorLevel ErrorLevel { get; set; }<br>  }<br><br>  var model = new Model();<br>  model.ErrorLevel = (ErrorLevel)4;</pre><p>The compiler will allow this, but a value of 4 is technically not valid for this enum. The Enum validator can prevent this from happening.</p><pre>RuleFor(x =&gt; x.ErrorLevel).IsInEnum();</pre><p><strong>Enum Name Validator</strong></p><p>Checks whether a string is a valid enum name.</p><pre>// For a case sensitive comparison<br>RuleFor(x =&gt; x.ErrorLevelName).IsEnumName(typeof(ErrorLevel));<br><br>// For a case-insensitive comparison<br>RuleFor(x =&gt; x.ErrorLevelName).IsEnumName(typeof(ErrorLevel), caseSensitive: false);</pre><p><strong>Empty Validator</strong></p><p>Opposite of the NotEmpty validator. Checks if a property value is null, or is the default value for the type. When used on an IEnumerable (such as arrays, collections, lists, etc.), the validator ensures that the IEnumerable is empty.</p><pre>RuleFor(x =&gt; x.Surname).Empty();</pre><p><strong>Null Validator</strong></p><p>Opposite of the NotNull validator. Checks if a property value is null.</p><pre>RuleFor(x =&gt; x.Surname).Null();</pre><p><strong>Exclusive Between Validator</strong></p><p>Checks whether the property value is in a range between the two specified numbers (exclusive).</p><pre>RuleFor(x =&gt; x.Id).ExclusiveBetween(1,10);</pre><p><strong>Inclusive Between Validator</strong></p><p>Checks whether the property value is in a range between the two specified numbers (inclusive).</p><pre>RuleFor(x =&gt; x.Id).InclusiveBetween(1,10);</pre><p><strong>Precision Scale Validator</strong></p><p>Checks whether a decimal value has the specified precision and scale.</p><pre>RuleFor(x =&gt; x.Amount).PrecisionScale(4, 2, false);</pre><h3>Setup</h3><p><strong>Dependencies</strong></p><blockquote>FluentValidation</blockquote><blockquote>FluentValidation.AspNetCore</blockquote><blockquote>FluentValidation.DependencyInjectionExtensions</blockquote><p><strong>Folder Structure:</strong></p><figure><img alt="Folder Structure (FluentValidation Introduction and Setup In .NET)" src="https://cdn-images-1.medium.com/max/502/1*gAYd15W43WiBAukZu3xsBQ.png" /><figcaption>Folder Structure (FluentValidation Introduction and Setup In .NET)</figcaption></figure><p><strong>AddContactRequest.cs (Models)</strong></p><pre>namespace Contact.API.Models<br>{<br>    public class AddContactRequest<br>    {<br>        public string Name { get; set; }<br>        public double Phone { get; set; }<br>        public string Email { get; set; }<br>        public string Address { get; set; }<br>    }<br>}</pre><p><strong>AddContactRequestValidator.cs (Validators)</strong></p><pre>using FluentValidation;<br><br>namespace Contact.API.Validators<br>{<br>    public class AddContactRequestValidator: AbstractValidator&lt;Models.AddContactRequest&gt;<br>    {<br>        public AddContactRequestValidator()<br>        {<br>            RuleFor(x =&gt; x.Name).NotEmpty();  // Not Empty check<br>            RuleFor(x =&gt; x.Length).GreaterThan(0);  // GreaterThan check<br>        }<br>    }<br>}</pre><p><strong>Program.cs</strong></p><pre>using FluentValidation.AspNetCore;<br><br>... // other contents<br><br>builder.Services.<br>    AddFluentValidation(options =&gt; options.RegisterValidatorsFromAssemblyContaining&lt;Program&gt;());<br><br>... // other contents<br><br>var app = builder.Build();<br><br>... // other contents</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d1024812786" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Upload in Node JS, MongoDB Using Multer, Cloudinary]]></title>
            <link>https://atdilakshan.medium.com/image-upload-in-node-js-mongodb-using-multer-cloudinary-c4ba600f110c?source=rss-4a33dfff0491------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4ba600f110c</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[image-upload]]></category>
            <category><![CDATA[cloudinary]]></category>
            <category><![CDATA[multer]]></category>
            <dc:creator><![CDATA[Dilakshan Antony Thevathas]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 17:23:56 GMT</pubDate>
            <atom:updated>2022-09-22T03:59:21.979Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Image Upload in Node JS, MongoDB Using Multer, Cloudinary AT Dilakshan" src="https://cdn-images-1.medium.com/max/1024/1*EEHQr7TZTxNNQkX5MPf1zg.png" /><figcaption>Image Upload in Node JS, MongoDB Using Multer, Cloudinary</figcaption></figure><p>In this article, we are going to learn how to <strong>upload</strong>, <strong>update</strong> and <strong>delete</strong> images in <strong>Cloudinary</strong> and how to record its records in <strong>MongoDB</strong>.</p><h3>Install node js.</h3><p>Please refer to this link for details. <a href="https://nodejs.org/en/download/package-manager/">Installing Node.js via package manager</a></p><h3>Install the required dependencies</h3><p>we need to initialize npm. When doing this the package.json file is created.</p><p>For that open terminal and run this code</p><pre>npm init</pre><p>After running this code the package.json file will look like this.</p><pre>{</pre><pre>&quot;name&quot;: &quot;cloudinary-image-upload&quot;,</pre><pre>&quot;version&quot;: &quot;1.0.0&quot;,</pre><pre>&quot;description&quot;: &quot;node js image upload using cloudinary multer mongodb&quot;,</pre><pre>&quot;main&quot;: &quot;server.js&quot;,</pre><pre>&quot;scripts&quot;: {</pre><pre>&quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;</pre><pre>},</pre><pre>&quot;author&quot;: &quot;AT Dilakshan&quot;,</pre><pre>&quot;license&quot;: &quot;ISC&quot;</pre><pre>}</pre><p>We need a few dependencies for this lesson.</p><p>The dependencies that we require are listed below.</p><p><strong><em>Express: </em></strong>Fast, unopinionated, minimalist web framework for node. <a href="https://www.npmjs.com/package/express"><strong><em>More Details</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Mongoose: </em></strong>Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks. <a href="https://www.npmjs.com/package/mongoose"><strong><em>More Details</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Multer:</em></strong> Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. <a href="https://www.npmjs.com/package/multer"><strong><em>More Details</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Cloudinary: </em></strong>The Cloudinary Node SDK allows you to quickly and easily integrate your application with Cloudinary. Effortlessly optimize, transform, upload and manage your cloud’s assets. <a href="https://www.npmjs.com/package/cloudinary"><strong><em>More Details</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Dotenv: </em></strong>Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology. <a href="https://www.npmjs.com/package/dotenv"><strong><em>More Details</em></strong></a><strong><em>.</em></strong></p><p>We need to run this code to install the required dependencies.</p><pre>npm install express mongoose multer cloudinary dotenv</pre><p>We can install the <strong>nodemon</strong> developer dependency so that the server does not stop even after the changes we make.</p><p><strong>nodemon</strong> is a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected. <a href="https://www.npmjs.com/package/nodemon"><strong><em>More Details</em></strong></a><strong><em>.</em></strong></p><p>Run this code to install it.</p><pre>npm install -g nodemon</pre><p>Now add it to the script in package.json.</p><pre>&quot;server&quot;: &quot;nodemon server&quot;</pre><p>Now our package.json file will look like this.</p><pre>{</pre><pre>&quot;name&quot;: &quot;cloudinary-image-upload&quot;,</pre><pre>&quot;version&quot;: &quot;1.0.0&quot;,</pre><pre>&quot;description&quot;: &quot;node js image upload using cloudinary multer mongodb&quot;,</pre><pre>&quot;main&quot;: &quot;server.js&quot;,</pre><pre>&quot;scripts&quot;: {</pre><pre>&quot;server&quot;: &quot;nodemon server&quot;</pre><pre>},</pre><pre>&quot;author&quot;: &quot;AT Dilakshan&quot;,</pre><pre>&quot;license&quot;: &quot;ISC&quot;,</pre><pre>&quot;dependencies&quot;: {</pre><pre>&quot;cloudinary&quot;: &quot;^1.30.1&quot;,</pre><pre>&quot;dotenv&quot;: &quot;^16.0.1&quot;,</pre><pre>&quot;express&quot;: &quot;^4.18.1&quot;,</pre><pre>&quot;mongoose&quot;: &quot;^6.5.2&quot;,</pre><pre>&quot;multer&quot;: &quot;^1.4.5-lts.1&quot;</pre><pre>}</pre><pre>}</pre><p>Next, let’s now create our folder structure.</p><h3>Folder Structure</h3><figure><img alt="image upload in cloudinary folder structure" src="https://cdn-images-1.medium.com/max/379/1*mtRsGsUM547Rm5ftUINSJA.png" /><figcaption>Folder Structure</figcaption></figure><h3>Create the server</h3><p>We’ll build a server with the name <strong>server.js</strong>.</p><pre>const express = require(&quot;express&quot;);</pre><pre>const mongoose = require(&quot;mongoose&quot;);</pre><pre>const app = express();</pre><pre>const port = 3000;</pre><pre>app.listen(port, () =&gt; {</pre><pre>console.log(`listening on port ${port}`)</pre><pre>});</pre><p>Next, let’s connect <strong>MongoDB</strong>.</p><p>We must keep the MongoDB connection string a <strong>secret</strong> while pushing our work to GitHub or the cloud.</p><p>For that, if we store the MongoDB connection string in <strong>.env</strong> then our MongoDB connection string will be secret.</p><p>We’ll create a <strong>.env</strong> file and store the MongoDB connection string.</p><pre>MONGO_CONNECTION_STRING = mongodb://localhost:27017/cloudinary</pre><p>Now let’s add it to the <strong>server. js</strong></p><pre>const express = require(&quot;express&quot;);</pre><pre>const mongoose = require(&quot;mongoose&quot;);</pre><pre><strong>const dotenv = require(&quot;dotenv&quot;);</strong></pre><pre>const app = express();</pre><pre><strong>dotenv.config();</strong></pre><pre><strong>// Connect Database</strong></pre><pre><strong>mongoose.connect(process.env.MONGO_CONNECTION_STRING)</strong></pre><pre><strong>.then((result) =&gt; {</strong></pre><pre><strong>console.log(&quot;mongodb connected&quot;);</strong></pre><pre><strong>}).catch((err) =&gt; {</strong></pre><pre><strong>console.log(err);</strong></pre><pre><strong>});</strong></pre><pre>const port = 3000;</pre><pre>app.listen(port, () =&gt; {</pre><pre>console.log(`listening on port ${port}`)</pre><pre>});</pre><pre>const app = express();</pre><pre>const port = 3000;</pre><pre>app.listen(port, () =&gt; {</pre><pre>console.log(`listening on port ${port}`)</pre><pre>});</pre><h3>Create the Schema For Database Collection</h3><p>To create the MongoDB Collection, we need to create the required fields in <strong>imageSchema.js</strong>.</p><pre>const mongoose = require(&quot;mongoose&quot;);</pre><pre>const collectionName = &quot;image&quot;; // collection Name image is pluralized(images)</pre><pre>const imageSchema = new mongoose.Schema({</pre><pre>title: {</pre><pre>type: &#39;string&#39;,</pre><pre>},</pre><pre>img: {</pre><pre>public_id: {</pre><pre>type: &#39;string&#39;,</pre><pre>},</pre><pre>secure_url: {</pre><pre>type: &#39;string&#39;,</pre><pre>}</pre><pre>},</pre><pre>});</pre><pre>module.exports = mongoose.model(collectionName, userSchema);</pre><h3>Setup Cloudinary File</h3><p>First, we need to create a cloudinary account.</p><p>Goto <a href="https://cloudinary.com/"><strong><em>Cloudinary</em></strong></a> website and register/ login. You will be redirected to your <strong>Dashboard</strong> where under <em>Account Details</em> you will find your <strong>Cloud Name</strong>, <strong>API Key</strong> and <strong>API Secret</strong>. Copy their values and inside the <strong>.env</strong> file create 3 variables to store those values.</p><h3>Create the CRUDs</h3><p>Let’s write the cruds in the <strong>imageController.js</strong> file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4ba600f110c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB Commands]]></title>
            <link>https://atdilakshan.medium.com/mongodb-commands-e7c0770115ce?source=rss-4a33dfff0491------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7c0770115ce</guid>
            <category><![CDATA[mongodb-commands]]></category>
            <category><![CDATA[mongodb-tutorial]]></category>
            <category><![CDATA[basic-mongodb]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[mongo]]></category>
            <dc:creator><![CDATA[Dilakshan Antony Thevathas]]></dc:creator>
            <pubDate>Fri, 10 Jun 2022 07:17:20 GMT</pubDate>
            <atom:updated>2022-06-10T07:17:20.104Z</atom:updated>
            <content:encoded><![CDATA[<h3>Install MongoDB NoSQL Database:</h3><p>MongoDB is very easy to install, and it is present in Ubuntu 20.04 software repository.</p><ol><li>sudo mongod</li><li>sudo mongo</li><li>show dbs</li><li>use dbName</li><li>db</li><li>db.dropDatabase</li><li>db.reateCollection(“collectionName”)</li><li>db.collectionName.drop</li><li>db.collectionName.insert()</li><li>show collections</li><li>db.collectionName.find()</li></ol><h3>Starting MongoDB Server</h3><p>You can start MongoDB on your computer with the mongod command.</p><blockquote><em>sudo mongod</em></blockquote><p>Keep the mongod window running when you want to work with your local MongoDB. MongoDB stops when you close the window.</p><h3>Start MongoDB Client</h3><p>One way to add items to a MongoDB database is through the Mongo Shell. To open up the Mongo Shell, you open another command line window and run mongo.</p><blockquote><em>sudo mongo</em></blockquote><p><strong>Note:</strong> Make sure you keep the mongod window open! You won’t be able to interact with the Mongo Shell if you close the mongod window.</p><h3>Show All Databases</h3><p>Useshow dbscommand from mongo shell to list all the available databases on MongoDB server. This will show the database name with there size.</p><blockquote><em>show dbs</em></blockquote><p>I currently have three databases. They are: admin, config and local.</p><h3>Go to a Particular Database</h3><p>Create a database called databaseName. You can use the use &lt;database&gt; command to create and switch to a new database.</p><blockquote><em>use databaseName</em></blockquote><h3>Create Collection</h3><p>Create a collection called collectionName. You can use the db.createCollection(&quot;&lt;collection name&gt;&quot;)to create a new collection.</p><blockquote><em>db.createCollection(“collectionName”)</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7c0770115ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB History]]></title>
            <link>https://atdilakshan.medium.com/mongodb-history-11649c6b3d7c?source=rss-4a33dfff0491------2</link>
            <guid isPermaLink="false">https://medium.com/p/11649c6b3d7c</guid>
            <category><![CDATA[nosql-database]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[mongo]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Dilakshan Antony Thevathas]]></dc:creator>
            <pubDate>Fri, 10 Jun 2022 07:11:33 GMT</pubDate>
            <atom:updated>2022-06-10T07:11:33.598Z</atom:updated>
            <content:encoded><![CDATA[<p>MongoDB is an open-source <a href="https://atdilshan.medium.com/what-is-nosql-79797e00d813">NoSQL</a> database management program. NoSQL is used as an alternative to traditional relational databases. NoSQL databases are quite useful for working with large sets of distributed data. MongoDB is a tool that can manage document-oriented information, and store or retrieve information.</p><p>MongoDB supports various forms of data. It is one of the many nonrelational <a href="https://atdilshan.medium.com/what-is-database-8cab921126ec">database</a> technologies that arose in the mid-2000s under the NoSQL banner — normally, for use in big data applications and other processing jobs involving data that doesn’t fit well in a rigid relational model. Instead of using tables and rows as in relational databases, the MongoDB architecture is made up of collections and documents.</p><p>Organizations can use MongoDB for its ad-hoc queries, indexing, load balancing, aggregation, server-side JavaScript execution and other features.</p><h3>How it works</h3><p>MongoDB makes use of records that are made up of documents that contain a data structure composed of field and value pairs. Documents are the basic unit of data in MongoDB. The documents are similar to JavaScript Object Notation, but use a variant called Binary JSON (BSON). The benefit of using BSON is that it accommodates more data types. The fields in these documents are similar to the columns in a relational database. Values contained can be a variety of data types, including other documents, arrays, and arrays of documents, according to the MongoDB user manual. Documents will also incorporate a primary key as a unique identifier.</p><p>Sets of documents are called <em>collections</em>, which function as the equivalent of relational database tables. Collections can contain any type of data, but the restriction is the data in a collection cannot be spread across different databases.</p><p>The mongo shell is a standard component of the open source distributions of MongoDB. Once MongoDB is installed, users connect the mongo shell to their running MongoDB instances. The mongo shell acts as an interactive JavaScript interface to MongoDB, which allows users to query and update data, and conduct administrative operations.</p><p>A binary representation of JSON-like documents is provided by the BSON document storage and data interchange format. Automatic sharding is another key feature that enables data in a MongoDB collection to be distributed across multiple systems for horizontal scalability, as data volumes and throughput requirements increase.</p><p>The NoSQL DBMS uses a single master architecture for data consistency, with secondary databases that maintain copies of the primary database. Operations are automatically replicated to those secondary databases for automatic failover.</p><h3>MongoDB history</h3><p>MongoDB was created by Dwight Merriman and Eliot Horowitz, who had encountered development and scalability issues with traditional relational database approaches while building web applications at DoubleClick, an online advertising company that is now owned by Google Inc. The name of the database was derived from the word <em>humongous</em> to represent the idea of supporting large amounts of data.</p><p>Merriman and Horowitz helped form 10Gen Inc. in 2007 to commercialize MongoDB and related software. The company was renamed MongoDB Inc. in 2013 and went public in October 2017 under the ticker symbol MDB.</p><p>The DBMS was released as open source software in 2009 and is available under the terms of Version 3.0 of the Free Software Foundation’s <a href="https://www.techtarget.com/searchdatacenter/definition/GNU-General-Public-License-GNU-GPL-or-simply-GPL">GNU</a> Affero General Public License, in addition to the commercial licenses offered by MongoDB Inc.</p><p>Organizations like the insurance company MetLife have used MongoDB for customer service applications, while other websites like Craigslist have used it for archiving data, and the CERN physics lab has used it for data aggregation and discovery. Additionally, <em>The New York Times</em> has used MongoDB to support a form-building application for photo submissions.</p><h3>Advantages of MongoDB</h3><p>The following are the few advantages of MongoDB <a href="https://atdilshan.medium.com/what-is-nosql-79797e00d813">NoSQL</a> database over relational databases.</p><ul><li>MongoDB is a schema-less <a href="https://atdilshan.medium.com/what-is-nosql-79797e00d813">NoSQL</a> database. We do not need to design the schema of the database when we are using MongoDB. This saves a lot of time. Thus, the code we write defines the schema.</li><li>No complex joins are needed in MongoDB. There is no relationship among data in MongoDB.</li><li>MongoDB is easy to scale.</li><li>It is very easy to set-up and install MongoDB.</li><li>The document query language supported by MongoDB is very simple as compared to SQL queries.</li><li>Because the MongoDB uses JSON format to store data, it is very easy to store arrays and objects.</li><li>MongoDB is free to use. There is no cost for it.</li><li>Performance of MongoDB is much higher than compared to any relational database.</li><li>There is no need for mapping of application objects to database objects in MongoDB.</li><li>MongoDB uses internal memory for storage which enables faster access to the data.</li></ul><h3>Disadvantages of MongoDB</h3><p>There are a few disadvantages of the MongoDB <a href="https://atdilshan.medium.com/what-is-nosql-79797e00d813">NoSQL</a> database as well.</p><ul><li>MongoDB uses high memory for data storage.</li><li>There is a limit for document size, i.e. 16mb.</li><li>There is no transaction support in MongoDB</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11649c6b3d7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>