<?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 Nurai on Medium]]></title>
        <description><![CDATA[Stories by Nurai on Medium]]></description>
        <link>https://medium.com/@devnurai?source=rss-4ed10a6aaa41------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bv_N5Vdrd9CM6Da0JQwU6A.jpeg</url>
            <title>Stories by Nurai on Medium</title>
            <link>https://medium.com/@devnurai?source=rss-4ed10a6aaa41------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:36:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devnurai/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[Understanding the Startup.cs File in .NET Core 8: A Comprehensive Guide]]></title>
            <link>https://medium.com/@devnurai/understanding-the-startup-cs-file-in-net-core-8-a-comprehensive-guide-3359e35974c5?source=rss-4ed10a6aaa41------2</link>
            <guid isPermaLink="false">https://medium.com/p/3359e35974c5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Nurai]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 08:33:10 GMT</pubDate>
            <atom:updated>2024-12-01T08:33:10.602Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding the Startup.cs File in .NET Core 8: A Comprehensive Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XlXyE-_xoqKMiq2u6fKx0Q.png" /></figure><p>When diving into .NET Core, one of the most crucial files in the project structure is the Startup.cs file. While .NET Core 8 emphasizes <strong>Minimal APIs</strong>, moving much of the setup to the Program.cs file, the Startup.cs file remains an essential concept for developers maintaining or migrating older projects. This blog will explore the purpose, structure, and evolution of Startup.cs to help you master its functionality.</p><h3>What is the Startup.cs File?</h3><p>The Startup.cs file is the heart of a traditional .NET Core application. It’s responsible for:</p><ol><li><strong>Configuring Services</strong>: Defining and registering dependencies for Dependency Injection (DI), database contexts, authentication, etc.</li><li><strong>Configuring Middleware</strong>: Setting up the HTTP request pipeline to process requests and generate responses.</li></ol><p>Think of it as the configuration hub for the application’s backend.</p><h3>Key Components of Startup.cs</h3><p>A standard Startup.cs file has two main methods:</p><ol><li><strong>ConfigureServices</strong>: Adds services to the application’s dependency injection container.</li><li><strong>Configure</strong>: Defines the middleware pipeline.</li></ol><p>Let’s break these down step-by-step.</p><h3>1. The Constructor</h3><pre>public Startup(IConfiguration configuration)<br>{<br>    Configuration = configuration;<br>}<br><br>public IConfiguration Configuration { get; }</pre><p>The <strong>constructor</strong> initializes the IConfiguration object, giving access to application settings (e.g., from appsettings.json).</p><h3>2. ConfigureServices</h3><p>The ConfigureServices method is where you register services for Dependency Injection (DI) and other components. It uses the IServiceCollection to make services available throughout the application.</p><p>Example:</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    // Add MVC services<br>    services.AddControllersWithViews();<br><br>    // Configure Entity Framework with SQL Server<br>    services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;<br>        options.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));<br><br>    // Register custom services<br>    services.AddScoped&lt;IMyService, MyService&gt;();<br><br>    // Add Authentication and Authorization<br>    services.AddAuthentication();<br>    services.AddAuthorization();<br><br>    // Configure third-party services<br>    services.AddSwaggerGen(); // Swagger for API documentation<br>}</pre><h4>Common Usages in ConfigureServices:</h4><ul><li><strong>MVC and Razor Pages</strong>: AddControllersWithViews()</li><li><strong>Database Contexts</strong>: Adding and configuring ORM tools like Entity Framework Core.</li><li><strong>Authentication and Authorization</strong>: Adding security layers.</li><li><strong>Third-Party Integrations</strong>: Configuring services like Swagger, Redis, or Hangfire.</li></ul><h3>3. Configure</h3><p>The Configure method defines how the app responds to HTTP requests. It sets up the middleware pipeline using the IApplicationBuilder.</p><p>Example:</p><pre>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br>    if (env.IsDevelopment())<br>    {<br>        app.UseDeveloperExceptionPage(); // Detailed error pages<br>    }<br>    else<br>    {<br>        app.UseExceptionHandler(&quot;/Home/Error&quot;);<br>        app.UseHsts();<br>    }<br><br>    app.UseHttpsRedirection();<br>    app.UseStaticFiles(); // Serve static files (CSS, JS, etc.)<br><br>    app.UseRouting(); // Enables routing<br><br>    app.UseAuthentication(); // Adds authentication middleware<br>    app.UseAuthorization();  // Adds authorization middleware<br><br>    app.UseEndpoints(endpoints =&gt;<br>    {<br>        endpoints.MapControllerRoute(<br>            name: &quot;default&quot;,<br>            pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;);<br>    });<br>}</pre><h4>Key Middleware Components:</h4><ul><li><strong>Error Handling</strong>: UseDeveloperExceptionPage and UseExceptionHandler.</li><li><strong>Static Files</strong>: Serving CSS, JavaScript, and other assets.</li><li><strong>Routing</strong>: UseRouting and endpoint mapping.</li><li><strong>Security</strong>: Authentication and Authorization middleware.</li><li><strong>Custom Middleware</strong>: You can define custom logic at any point in the pipeline.</li></ul><h3>The Role of Startup.cs in Minimal APIs</h3><p>Starting with .NET Core 6, the <strong>Minimal API</strong> approach simplifies application configuration by merging Startup.cs functionality into Program.cs.</p><p>Here’s an example of a Minimal API setup in .NET Core 8:</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>// Configure Services<br>builder.Services.AddControllersWithViews();<br>builder.Services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;<br>    options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));<br><br>// Build the application<br>var app = builder.Build();<br><br>// Configure Middleware<br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseDeveloperExceptionPage();<br>}<br><br>app.UseHttpsRedirection();<br>app.UseStaticFiles();<br>app.UseRouting();<br>app.UseAuthentication();<br>app.UseAuthorization();<br><br>app.MapControllers();<br>app.Run();</pre><p>With this structure:</p><ul><li>The ConfigureServices logic is placed in the builder.Services section.</li><li>Middleware is added directly using the app object.</li></ul><h3>When to Use Startup.cs</h3><ul><li><strong>Legacy Applications</strong>: Many existing .NET Core projects rely on Startup.cs.</li><li><strong>Complex Applications</strong>: Separating service registration and middleware logic can improve organization in large projects.</li><li><strong>Gradual Migration</strong>: When migrating older applications to newer .NET Core versions, maintaining Startup.cs can ease the transition.</li></ul><h3>Conclusion</h3><p>The Startup.cs file has been a cornerstone of .NET Core applications, providing a clear structure for configuring services and middleware. While the Minimal API in .NET Core 8 streamlines this process, understanding Startup.cs remains essential for working with legacy projects or maintaining a clean separation of concerns in complex applications.</p><p>Whether you’re diving into Startup.cs or transitioning to Minimal APIs, this knowledge empowers you to build robust and scalable .NET Core applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3359e35974c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide to IList in C#]]></title>
            <link>https://medium.com/@devnurai/comprehensive-guide-to-ilist-in-c-296deea68ab5?source=rss-4ed10a6aaa41------2</link>
            <guid isPermaLink="false">https://medium.com/p/296deea68ab5</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Nurai]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 11:02:58 GMT</pubDate>
            <atom:updated>2024-11-24T11:02:58.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XlXyE-_xoqKMiq2u6fKx0Q.png" /></figure><p>In C#, the IList&lt;T&gt; interface is a generic collection interface that represents an ordered collection of objects. It extends the functionality of ICollection&lt;T&gt; by adding features like indexing, allowing developers to access and manipulate elements directly by their index. The IList interface is widely used when working with lists that require dynamic operations, such as insertion, deletion, and indexing.</p><p>This article provides a detailed overview of IList&lt;T&gt;, its features, methods, properties, and usage with examples.</p><h3>What is IList?</h3><p>IList&lt;T&gt; is part of the System.Collections.Generic namespace and is a generic interface. It allows working with collections of a specific type (T) where the order of elements matters, and individual elements can be accessed via an index.</p><h3>Key Features of IList&lt;T&gt;</h3><ol><li><strong>Index-Based Access</strong>: Provides access to elements using an integer index.</li><li><strong>Dynamic Modification</strong>: Supports adding, removing, and inserting elements at specific positions.</li><li><strong>Type-Safe</strong>: Ensures that the collection stores only a specified type of object.</li><li><strong>Order Preserved</strong>: Maintains the order of elements as they are added.</li></ol><h3>Syntax of IList&lt;T&gt;</h3><p>To use IList&lt;T&gt;, include the System.Collections.Generic namespace:</p><pre>using System.Collections.Generic;</pre><p>Here’s how you can declare an IList:</p><pre>IList&lt;int&gt; numbers = new List&lt;int&gt;();</pre><p>In this example, numbers is an IList of integers, implemented using the List&lt;T&gt; class.</p><h3>Properties of IList&lt;T&gt;</h3><p><strong>Count</strong>: Gets the number of elements in the list.</p><pre>Console.WriteLine(numbers.Count); // Output: Number of elements</pre><p><strong>IsReadOnly</strong>: Indicates whether the list is read-only.</p><pre>Console.WriteLine(numbers.IsReadOnly); // Output: False (for List&lt;T&gt;)</pre><p><strong>Item[int index]</strong>: Allows getting or setting elements at the specified index using an indexer.</p><pre>Console.WriteLine(numbers[0]); // Gets the first element<br>numbers[0] = 100;              // Updates the first element</pre><h3>Methods of IList&lt;T&gt;</h3><h4>Adding Elements</h4><ul><li><strong>Add(T item)</strong>: Appends an element to the list.</li></ul><pre>numbers.Add(10); // Adds 10 to the list</pre><ul><li><strong>Insert(int index, T item)</strong>: Inserts an element at the specified index.</li></ul><h4>Removing Elements</h4><ul><li><strong>Remove(T item)</strong>: Removes the first occurrence of the specified element.</li></ul><pre>numbers.Remove(10); // Removes 10 if it exists</pre><ul><li><strong>RemoveAt(int index)</strong>: Removes the element at the specified index.</li></ul><pre>numbers.RemoveAt(0); // Removes the element at index 0</pre><ul><li><strong>Clear()</strong>: Removes all elements from the list.</li></ul><pre>numbers.Clear(); // Empties the list</pre><h4>Searching and Checking</h4><ul><li><strong>Contains(T item)</strong>: Checks if the list contains the specified element.</li></ul><pre>Console.WriteLine(numbers.Contains(10)); // Output: True or False</pre><ul><li><strong>IndexOf(T item)</strong>: Returns the index of the first occurrence of the specified element.</li></ul><pre>int index = numbers.IndexOf(10); // Returns -1 if not found</pre><ul><li><strong>LastIndexOf(T item)</strong>: Returns the index of the last occurrence of the specified element.</li></ul><pre>int lastIndex = numbers.LastIndexOf(10);</pre><h4>Iterating</h4><ul><li>Use a foreach loop to iterate over the elements.</li></ul><pre>foreach (var number in numbers)<br>{<br>    Console.WriteLine(number);<br>}</pre><h4>Copying Elements</h4><ul><li><strong>CopyTo(T[] array, int arrayIndex)</strong>: Copies elements from the list to a specified array starting at a particular index.</li></ul><pre>int[] array = new int[numbers.Count];<br>numbers.CopyTo(array, 0); // Copies elements into array</pre><h3>Common Implementations of IList&lt;T&gt;</h3><p><strong>List&lt;T&gt;</strong>: A resizable array implementation of IList&lt;T&gt;.</p><pre>IList&lt;int&gt; list = new List&lt;int&gt;();<br>list.Add(1);</pre><p><strong>Array</strong>: An array also implements IList, but it has a fixed size.</p><pre>int[] array = { 1, 2, 3 };<br>IList&lt;int&gt; arrayList = array;</pre><p><strong>BindingList&lt;T&gt;</strong>: Provides a data-binding friendly list implementation.</p><pre>IList&lt;string&gt; bindingList = new BindingList&lt;string&gt;();</pre><h3>Example Program</h3><p>Here’s an example demonstrating the use of IList&lt;T&gt;:</p><pre>using System;<br>using System.Collections.Generic;<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        IList&lt;string&gt; cities = new List&lt;string&gt;();<br><br>        // Adding elements<br>        cities.Add(&quot;New York&quot;);<br>        cities.Add(&quot;Los Angeles&quot;);<br>        cities.Add(&quot;Chicago&quot;);<br><br>        // Accessing elements<br>        Console.WriteLine($&quot;First City: {cities[0]}&quot;);<br><br>        // Modifying elements<br>        cities[1] = &quot;San Francisco&quot;;<br><br>        // Iterating over the list<br>        Console.WriteLine(&quot;Cities:&quot;);<br>        foreach (var city in cities)<br>        {<br>            Console.WriteLine(city);<br>        }<br><br>        // Checking existence<br>        Console.WriteLine($&quot;Contains &#39;Chicago&#39;: {cities.Contains(&quot;Chicago&quot;)}&quot;);<br><br>        // Inserting an element<br>        cities.Insert(2, &quot;Houston&quot;);<br><br>        // Removing an element<br>        cities.Remove(&quot;New York&quot;);<br>        cities.RemoveAt(1);<br><br>        // Displaying the final list<br>        Console.WriteLine(&quot;Updated Cities:&quot;);<br>        foreach (var city in cities)<br>        {<br>            Console.WriteLine(city);<br>        }<br>    }<br>}</pre><h3>Use Cases of IList&lt;T&gt;</h3><ul><li><strong>Dynamic Collections</strong>: When you need to add, remove, or modify elements dynamically.</li><li><strong>Index-Based Operations</strong>: For scenarios requiring quick access to elements by their position.</li><li><strong>Data Binding</strong>: Used in UI frameworks (e.g., WPF) for binding lists of data.</li></ul><h3>Summary of IList&lt;T&gt;</h3><p>The IList&lt;T&gt; interface in C# provides a robust foundation for creating and working with ordered collections. With its support for indexing, dynamic modification, and a variety of implementations, IList is a versatile tool in a developer’s arsenal. Whether you&#39;re building small applications or large-scale systems, understanding IList and its capabilities is essential for effective collection management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=296deea68ab5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating EF Core Migrations in .NET Core Applications]]></title>
            <link>https://medium.com/@devnurai/automating-ef-core-migrations-in-net-core-applications-a179b64e01b6?source=rss-4ed10a6aaa41------2</link>
            <guid isPermaLink="false">https://medium.com/p/a179b64e01b6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <dc:creator><![CDATA[Nurai]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 10:48:17 GMT</pubDate>
            <atom:updated>2024-11-24T10:48:17.567Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating EF Core Migrations in .NET Core Applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XlXyE-_xoqKMiq2u6fKx0Q.png" /></figure><p><strong>Introduction</strong></p><p>Managing database migrations is a critical task in any software development lifecycle. With Entity Framework Core (EF Core), migrations allow you to evolve your database schema alongside your application code. To streamline this process, especially in development and CI/CD pipelines, you can automate migrations to ensure that your database is always up to date. In this article, we’ll demonstrate how to automatically check for and apply EF Core migrations during application startup.</p><h3>Why Automate Migrations?</h3><ol><li><strong>Consistency</strong>: All environments (development, staging, production) remain in sync with the same database schema.</li><li><strong>Efficiency</strong>: Developers and CI/CD pipelines can handle migrations without manual intervention.</li><li><strong>Error Prevention</strong>: Minimizes the risk of runtime schema mismatch errors.</li></ol><h3>Setting Up EF Core Automatic Migrations</h3><p>We will use a simple example with a fictional MyAppDbContext. Assume that the application configuration includes the necessary connection string for the database.</p><h4>Step 1: Configure the Database Context</h4><p>Ensure your DbContext is set up correctly. For this example, create a MyAppDbContext class.</p><pre>using Microsoft.EntityFrameworkCore;<br><br>namespace MyApp.Data<br>{<br>    public class MyAppDbContext : DbContext<br>    {<br>        public MyAppDbContext(DbContextOptions&lt;MyAppDbContext&gt; options) <br>            : base(options) <br>        { <br>        }<br><br>        public DbSet&lt;Product&gt; Products { get; set; }<br>    }<br><br>    public class Product<br>    {<br>        public int Id { get; set; }<br>        public string Name { get; set; }<br>        public decimal Price { get; set; }<br>    }<br>}</pre><h4>Step 2: Connection String in Configuration</h4><p>Add the connection string to appsettings.json:</p><pre>{<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;DefaultConnection&quot;: &quot;Server=localhost;Database=MyAppDb;Trusted_Connection=True;MultipleActiveResultSets=true&quot;<br>  }<br>}</pre><h3>Automate Migrations in Program.cs</h3><p>Modify the Program.cs file to include logic for checking and applying pending migrations at startup.</p><pre>using Microsoft.EntityFrameworkCore;<br>using MyApp.Data;<br><br>namespace MyApp<br>{<br>    public class Program<br>    {<br>        public static void Main(string[] args)<br>        {<br>            var builder = WebApplication.CreateBuilder(args);<br><br>            // Add DbContext<br>            builder.Services.AddDbContext&lt;MyAppDbContext&gt;(options =&gt;<br>                options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));<br><br>            var app = builder.Build();<br><br>            // Apply migrations automatically<br>            ApplyMigrations(app);<br><br>            app.MapGet(&quot;/&quot;, () =&gt; &quot;Hello, World!&quot;);<br><br>            app.Run();<br>        }<br><br>        private static void ApplyMigrations(WebApplication app)<br>        {<br>            using (var scope = app.Services.CreateScope())<br>            {<br>                var dbContext = scope.ServiceProvider.GetRequiredService&lt;MyAppDbContext&gt;();<br><br>                // Check and apply pending migrations<br>                var pendingMigrations = dbContext.Database.GetPendingMigrations();<br>                if (pendingMigrations.Any())<br>                {<br>                    Console.WriteLine(&quot;Applying pending migrations...&quot;);<br>                    dbContext.Database.Migrate();<br>                    Console.WriteLine(&quot;Migrations applied successfully.&quot;);<br>                }<br>                else<br>                {<br>                    Console.WriteLine(&quot;No pending migrations found.&quot;);<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>Code Breakdown</h3><p><strong>Service Registration</strong>:</p><ul><li>Register the DbContext in the dependency injection container using AddDbContext.</li></ul><pre>builder.Services.AddDbContext&lt;MyAppDbContext&gt;(options =&gt;<br>    options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));</pre><p><strong>Create a Scoped Service</strong>:</p><ul><li>Use CreateScope() to resolve the DbContext during the application startup.</li></ul><p><strong>Check Pending Migrations</strong>:</p><ul><li>Use the GetPendingMigrations() method to fetch migrations that haven’t been applied.</li></ul><pre>var pendingMigrations = dbContext.Database.GetPendingMigrations();</pre><p><strong>Apply Migrations</strong>:</p><ul><li>If migrations are found, call the Migrate() method to apply them.</li></ul><h3>Example Output</h3><p>When you start the application, it will log the following messages based on the migration status:</p><ul><li><strong>No pending migrations</strong>:</li></ul><pre>No pending migrations found.</pre><ul><li><strong>Applying migrations</strong>:</li></ul><pre>Applying pending migrations...<br>Migrations applied successfully.</pre><h3>Benefits of This Approach</h3><ul><li><strong>Simplifies Development</strong>: No need to run Update-Database manually during every schema change.</li><li><strong>Improves CI/CD Pipelines</strong>: Automates database schema updates during deployments.</li><li><strong>Error Reduction</strong>: Prevents runtime errors caused by missing migrations.</li></ul><h3>Considerations for Production</h3><p><strong>Caution with Automatic Migrations</strong>:</p><ul><li>In production, automated migrations might lead to unintended schema changes. Use this approach carefully, especially for large databases.</li></ul><p><strong>Test Migrations Thoroughly</strong>:</p><ul><li>Ensure migration scripts are tested in staging environments before applying them to production.</li></ul><p><strong>Use Rollbacks</strong>:</p><ul><li>Always have a plan for rolling back migrations if something goes wrong.</li></ul><h3>Conclusion</h3><p>Automating EF Core migrations saves time and ensures database schema consistency across environments. By implementing this solution in your Program.cs file, your application will automatically check for and apply any pending migrations during startup. This approach is particularly beneficial for development and staging environments, but it should be used with caution in production.</p><p>With this setup in place, you can focus on building features rather than worrying about database maintenance!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a179b64e01b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Guide to Dictionaries in C#]]></title>
            <link>https://medium.com/@devnurai/complete-guide-to-dictionaries-in-c-939cea760531?source=rss-4ed10a6aaa41------2</link>
            <guid isPermaLink="false">https://medium.com/p/939cea760531</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Nurai]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 02:47:56 GMT</pubDate>
            <atom:updated>2024-11-13T02:47:56.669Z</atom:updated>
            <content:encoded><![CDATA[<p>In C#, the Dictionary class in System.Collections.Generic provides an efficient way to store and retrieve data in key-value pairs. This data structure is powerful, versatile, and highly optimized for quick data lookups, making it ideal for various real-world programming scenarios.</p><p>This article will give you an in-depth understanding of the Dictionary&lt;TKey, TValue&gt; in C#—its structure, properties, methods, and usage examples.</p><h3>What is a Dictionary in C#?</h3><p>A Dictionary&lt;TKey, TValue&gt; is a generic collection that stores data as key-value pairs. Each <strong>key</strong> in the dictionary is unique and maps to a <strong>value</strong>. Dictionaries in C# provide <strong>O(1)</strong> time complexity for operations like adding, retrieving, and deleting data if an efficient hash function is in place, making them an excellent choice for high-performance applications.</p><h3>Basic Syntax of a Dictionary</h3><p>To declare a dictionary, specify two types:</p><ul><li><strong>TKey</strong>: the type of keys in the dictionary.</li><li><strong>TValue</strong>: the type of values associated with each key.</li></ul><p>Here’s an example:</p><pre>Dictionary&lt;int, string&gt; myDictionary = new Dictionary&lt;int, string&gt;();</pre><p>In this example, myDictionary uses int as the key type and string as the value type.</p><h3>Properties of Dictionary</h3><p>Dictionaries have several important properties:</p><ul><li><strong>Count</strong>: Returns the number of key-value pairs in the dictionary.</li><li><strong>Keys</strong>: Returns a collection of all keys in the dictionary.</li><li><strong>Values</strong>: Returns a collection of all values in the dictionary.</li><li><strong>Comparer</strong>: Gets the equality comparer used for comparing keys.</li></ul><p>Here’s an example showing how to use these properties:</p><pre>var fruits = new Dictionary&lt;string, int&gt;<br>{<br>    {&quot;Apple&quot;, 1},<br>    {&quot;Banana&quot;, 2}<br>};<br><br>Console.WriteLine(fruits.Count); // Output: 2<br>foreach (var key in fruits.Keys)<br>{<br>    Console.WriteLine(key); // Output: Apple, Banana<br>}<br>foreach (var value in fruits.Values)<br>{<br>    Console.WriteLine(value); // Output: 1, 2<br>}</pre><h3>Adding Elements to a Dictionary</h3><p>To add elements to a dictionary, use the Add method or the indexer syntax []:</p><pre>Dictionary&lt;int, string&gt; numbers = new Dictionary&lt;int, string&gt;();<br>numbers.Add(1, &quot;One&quot;);<br>numbers[2] = &quot;Two&quot;; // Using the indexer syntax</pre><p><strong>Note</strong>: If you attempt to add a duplicate key with Add, an ArgumentException will be thrown. However, the indexer syntax [] will update the value if the key already exists.</p><h3>Retrieving Values from a Dictionary</h3><p>The most common way to retrieve a value is by using the key:</p><pre>string value = numbers[1];  // Retrieves the value associated with key 1</pre><p>If the key does not exist, a KeyNotFoundException will be thrown. To handle this safely, use TryGetValue, which returns true if the key exists and sets the out parameter to the associated value:</p><pre>if (numbers.TryGetValue(2, out string result))<br>{<br>    Console.WriteLine(result);<br>}<br>else<br>{<br>    Console.WriteLine(&quot;Key not found&quot;);<br>}</pre><h3>Updating an Existing Value</h3><p>To update an existing value, use the indexer syntax with the key:</p><pre>numbers[1] = &quot;Updated One&quot;;</pre><p>If the key exists, the associated value will be updated; if the key doesn’t exist, a new key-value pair will be added.</p><h3>Removing Elements from a Dictionary</h3><p>To remove an item by its key, use Remove:</p><pre>numbers.Remove(1); // Removes the key-value pair with key 1</pre><p>This method returns true if the element was successfully removed; otherwise, it returns false.</p><h3>Checking for the Existence of a Key or Value</h3><p>To check if a specific key or value exists in the dictionary, use ContainsKey or ContainsValue:</p><pre>bool hasKey = numbers.ContainsKey(1); // Returns true if key 1 exists<br>bool hasValue = numbers.ContainsValue(&quot;Two&quot;); // Returns true if &quot;Two&quot; is found as a value</pre><h3>Iterating Over a Dictionary</h3><p>A Dictionary can be iterated using foreach, where each element is a KeyValuePair&lt;TKey, TValue&gt;:</p><pre>foreach (KeyValuePair&lt;int, string&gt; kvp in numbers)<br>{<br>    Console.WriteLine($&quot;Key: {kvp.Key}, Value: {kvp.Value}&quot;);<br>}</pre><p>Alternatively, you can iterate over just the keys or values using Keys and Values properties.</p><h3>Initializing a Dictionary</h3><p>Dictionaries can be initialized at the time of declaration using a collection initializer:</p><pre>var myDictionary = new Dictionary&lt;int, string&gt;<br>{<br>    { 1, &quot;One&quot; },<br>    { 2, &quot;Two&quot; },<br>    { 3, &quot;Three&quot; }<br>};</pre><h3>Dictionary Constructors</h3><p>The Dictionary class offers multiple constructors for different scenarios:</p><p><strong>Default Constructor</strong>: Initializes an empty dictionary.</p><pre>var myDictionary = new Dictionary&lt;int, string&gt;();</pre><p><strong>Dictionary(int capacity)</strong>: Initializes a dictionary with a specified capacity, which can improve performance if the size is known.</p><pre>var myDictionary = new Dictionary&lt;int, string&gt;(100);</pre><p><strong>Dictionary(IEqualityComparer&lt;TKey&gt;)</strong>: Initializes a dictionary with a specified equality comparer for custom key comparisons.</p><pre>var caseInsensitiveDict = new Dictionary&lt;string, string&gt;(StringComparer.OrdinalIgnoreCase);</pre><p><strong>Dictionary(IDictionary&lt;TKey, TValue&gt;)</strong>: Initializes a dictionary by copying another dictionary.</p><pre>var anotherDictionary = new Dictionary&lt;int, string&gt;(myDictionary);</pre><h3>Custom Comparers for Keys</h3><p>By default, dictionaries use the default equality comparer for the key type. You can provide a custom equality comparer by implementing IEqualityComparer&lt;TKey&gt;. This can be particularly useful for case-insensitive string keys:</p><pre>var caseInsensitiveDict = new Dictionary&lt;string, string&gt;(StringComparer.OrdinalIgnoreCase);<br>caseInsensitiveDict.Add(&quot;Hello&quot;, &quot;World&quot;);<br>Console.WriteLine(caseInsensitiveDict.ContainsKey(&quot;hello&quot;)); // True</pre><h3>Thread-Safety and ConcurrentDictionary</h3><p>The Dictionary class is <strong>not thread-safe</strong>. If multiple threads are modifying a dictionary concurrently, it could cause unpredictable behavior. For thread-safe operations, use the ConcurrentDictionary&lt;TKey, TValue&gt; from System.Collections.Concurrent.</p><pre>using System.Collections.Concurrent;<br><br>ConcurrentDictionary&lt;int, string&gt; safeDict = new ConcurrentDictionary&lt;int, string&gt;();<br>safeDict.TryAdd(1, &quot;One&quot;);</pre><h3>Performance Characteristics of Dictionary</h3><p>Dictionaries are highly efficient due to their <strong>O(1)</strong> complexity for retrieval, insertion, and deletion in most cases, thanks to hashing. However, performance can degrade with poor hash functions, leading to increased collisions and slower operations.</p><h3>Common Exceptions in Dictionary Operations</h3><p>Dictionaries in C# can throw the following exceptions:</p><ul><li><strong>ArgumentNullException</strong>: If a null key is used.</li><li><strong>ArgumentException</strong>: If a duplicate key is added with Add.</li><li><strong>KeyNotFoundException</strong>: If a key not present in the dictionary is accessed.</li></ul><h3>Example Program</h3><p>The following example demonstrates basic dictionary operations:</p><pre>using System;<br>using System.Collections.Generic;<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        var dictionary = new Dictionary&lt;int, string&gt;<br>        {<br>            {1, &quot;one&quot;},<br>            {2, &quot;two&quot;},<br>            {3, &quot;three&quot;}<br>        };<br><br>        // Retrieving values<br>        Console.WriteLine(dictionary[2]); // Output: two<br><br>        // Updating an element<br>        dictionary[2] = &quot;updated two&quot;;<br><br>        // Removing an element<br>        dictionary.Remove(1);<br><br>        // Iterating through the dictionary<br>        foreach (var kvp in dictionary)<br>        {<br>            Console.WriteLine($&quot;Key: {kvp.Key}, Value: {kvp.Value}&quot;);<br>        }<br><br>        // Checking existence<br>        Console.WriteLine(dictionary.ContainsKey(2)); // Output: True<br>    }<br>}</pre><h3>Summary of Dictionary in C#</h3><p>In C#, the Dictionary&lt;TKey, TValue&gt; class is an essential data structure for storing key-value pairs with high efficiency. It provides a wide range of functionalities for adding, retrieving, updating, and removing elements and is optimized for rapid data access. The dictionary allows for customization through equality comparers and supports various initialization methods, making it versatile for many use cases.</p><p>While dictionaries are not inherently thread-safe, the ConcurrentDictionary&lt;TKey, TValue&gt; offers a safe alternative for multi-threaded applications. Whether you’re developing simple or complex applications, dictionaries in C# are a robust, high-performance solution for organizing data as key-value pairs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=939cea760531" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Program.cs File in .NET Core 8: An In-Depth Exploration]]></title>
            <link>https://medium.com/@devnurai/understanding-the-program-cs-file-in-net-core-8-an-in-depth-exploration-d38437ea6b3c?source=rss-4ed10a6aaa41------2</link>
            <guid isPermaLink="false">https://medium.com/p/d38437ea6b3c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Nurai]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 06:36:28 GMT</pubDate>
            <atom:updated>2024-09-29T06:38:45.839Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding the Program.cs File in .NET Core 8: An In-Depth Exploration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XlXyE-_xoqKMiq2u6fKx0Q.png" /></figure><p>In .NET Core 8, the Program.cs file serves as the main entry point for any web application, responsible for setting up the application&#39;s configuration, dependency injection (DI), middleware, and the HTTP request pipeline. Over recent versions, particularly since .NET 6, the Program.cs file has been simplified into a minimalistic, streamlined structure, combining what used to be split into the Startup.cs and Program.cs files into a single unified approach.</p><p>In this detailed blog post, we’ll dive deeper into each section of the Program.cs file, discussing not only the basic components but also additional configurations, advanced features, and customization options that are relevant in .NET Core 8.</p><h3>Key Components of the Program.cs File</h3><ol><li><strong>Namespaces and Usings: Importing Essential Libraries</strong></li><li><strong>Creating the Builder: </strong><strong>WebApplication.CreateBuilder(args)</strong></li><li><strong>Configuring Services: </strong><strong>builder.Services</strong></li><li><strong>Building the Application: </strong><strong>builder.Build()</strong></li><li><strong>Configuring the Middleware Pipeline</strong></li><li><strong>Environment-Specific Configuration</strong></li><li><strong>Running the Application: </strong><strong>app.Run()</strong></li></ol><p>Let’s break each component down into greater detail.</p><h3>1. Namespaces and Usings: Importing Essential Libraries</h3><p>At the top of the Program.cs file, we see several namespaces that bring in functionality necessary to build and run an ASP.NET Core application. These imports provide access to essential features such as configuring middleware, setting up routing, and registering services for dependency injection.</p><pre>using Microsoft.AspNetCore.Builder;<br>using Microsoft.Extensions.DependencyInjection;<br>using Microsoft.Extensions.Hosting;</pre><ul><li><strong>Microsoft.AspNetCore.Builder</strong>: This namespace contains classes and extension methods for building the HTTP request pipeline, such as WebApplication, UseRouting(), and UseMiddleware().</li><li><strong>Microsoft.Extensions.DependencyInjection</strong>: This namespace provides methods for configuring services in the dependency injection (DI) container.</li><li><strong>Microsoft.Extensions.Hosting</strong>: Contains classes that support hosting functionality for the application, such as environment detection (IHostEnvironment) and running long-lived services.</li></ul><p>If your app requires additional functionality, such as logging, authentication, or database interaction, you will need to import the appropriate namespaces here as well, e.g.:</p><pre>using Microsoft.Extensions.Logging;<br>using Microsoft.EntityFrameworkCore;</pre><h3>2. <strong>Creating the Builder: </strong><strong>WebApplication.CreateBuilder(args)</strong></h3><pre>var builder = WebApplication.CreateBuilder(args);</pre><p>The CreateBuilder method is a high-level entry point that abstracts much of the setup previously required in .NET Core 2.x and 3.x applications. This single line of code does the following:</p><ul><li><strong>Loads Configuration</strong>: It loads configuration settings from various sources like appsettings.json, environment variables, command-line arguments, and any custom configuration sources you add.</li><li><strong>Sets Up Logging</strong>: It configures logging based on the current environment (e.g., development, production) and any specified logging settings.</li><li><strong>Initializes Dependency Injection</strong>: The DI container is initialized, allowing services to be registered and injected throughout the app.</li></ul><p>This method simplifies the application startup process by handling all the default setup needed to run the app while still allowing customization if required.</p><h4>Advanced Customizations</h4><p>You can modify the builder configuration to include additional settings, such as adding support for custom configuration providers or enhancing logging:</p><pre>builder.Configuration.AddJsonFile(&quot;customsettings.json&quot;, optional: true, reloadOnChange: true);<br>builder.Logging.AddConsole();</pre><p>Here, you can load a custom configuration file or modify logging behavior.</p><h3>3. <strong>Configuring Services: </strong><strong>builder.Services</strong></h3><p>After creating the builder, you can configure the services that will be used across the application. This is where Dependency Injection (DI) is set up by registering services within the DI container, allowing them to be injected into controllers, middleware, and other parts of the app.</p><pre>builder.Services.AddControllers();</pre><ul><li><strong>AddControllers()</strong>: Registers the necessary services for using MVC pattern, enabling controllers to handle HTTP requests. It adds support for API controllers and routing, setting the stage for the MapControllers() call later in the middleware setup.</li></ul><h4>Additional Service Configurations</h4><p>In real-world applications, this section of the Program.cs file can include many other services. Some common examples:</p><ul><li><strong>Database Context</strong>:</li></ul><pre>builder.Services.AddDbContext&lt;MyDbContext&gt;(options =&gt;<br>    options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));</pre><p>This registers MyDbContext with the DI container, configuring it to use SQL Server based on connection string settings from the configuration file.</p><ul><li><strong>Authentication &amp; Authorization</strong>:</li></ul><pre>builder.Services.AddAuthentication(&quot;Bearer&quot;)<br>    .AddJwtBearer(options =&gt;<br>    {<br>        options.Authority = &quot;https://your-identity-provider&quot;;<br>        options.Audience = &quot;your-api&quot;;<br>    });<br>builder.Services.AddAuthorization();</pre><p>This configures the app to use JWT authentication for securing APIs and adds authorization services to control access to endpoints.</p><ul><li><strong>Swagger (API Documentation)</strong>:</li></ul><p>Swagger helps in generating API documentation and testing endpoints:</p><pre>builder.Services.AddSwaggerGen();</pre><p>Once this is registered, you can configure Swagger middleware later in the pipeline to automatically generate and serve API documentation.</p><p><strong>Dependency Injection with Scopes</strong>: Services in .NET Core are typically registered with one of three lifetimes:</p><ul><li><strong>Singleton</strong>: A single instance of the service is created and shared across the entire app.</li><li><strong>Scoped</strong>: A new instance of the service is created for each request.</li><li><strong>Transient</strong>: A new instance is created every time the service is requested.</li></ul><pre>builder.Services.AddSingleton&lt;IMyService, MyService&gt;();   // Singleton<br>builder.Services.AddScoped&lt;IUserService, UserService&gt;();  // Scoped<br>builder.Services.AddTransient&lt;ILoggingService, LoggingService&gt;(); // Transient</pre><ul><li><strong>Adding HttpClient</strong>:</li></ul><p>Modern applications often consume external APIs. Instead of manually creating instances of HttpClient, you should use the built-in HttpClientFactory:</p><pre>builder.Services.AddHttpClient();</pre><ul><li><strong>Configure Options Pattern</strong>:</li></ul><p>You can use the Options Pattern to bind configuration settings from appsettings.json to strongly typed classes. For example, if you have the following configuration:</p><pre>&quot;AppSettings&quot;: {<br>  &quot;ApiKey&quot;: &quot;your-api-key&quot;<br>}</pre><p>You can bind this to a class:</p><pre>builder.Services.Configure&lt;AppSettings&gt;(builder.Configuration.GetSection(&quot;AppSettings&quot;));</pre><ul><li><strong>Caching</strong>:</li></ul><pre>builder.Services.AddDistributedMemoryCache();<br>builder.Services.AddSession();</pre><p>Adds support for distributed caching and session management in the app.</p><ul><li><strong>Third-Party Services</strong>:</li></ul><p>You can also register third-party services, such as SendGrid for email, Stripe for payments, etc., using this section.</p><h4>Using IServiceCollection Extensions:</h4><p>IServiceCollection can be extended by adding custom service configurations. You can write your own extension methods to simplify service registration:</p><pre>public static class MyCustomServiceExtensions<br>{<br>    public static IServiceCollection AddMyServices(this IServiceCollection services)<br>    {<br>        services.AddSingleton&lt;IMyService, MyService&gt;();<br>        // Add more services here<br>        return services;<br>    }<br>}<br><br>// Registering in Program.cs<br>builder.Services.AddMyServices();</pre><h3>4. <strong>Building the Application: </strong><strong>builder.Build()</strong></h3><pre>var app = builder.Build();</pre><p>Once services have been registered, the Build() method is called to create the WebApplication object. This object encapsulates the application and its entire configuration, ready for use.</p><p>This is an important step, as it finalizes the setup process, resolves all services from the DI container, and prepares the HTTP request pipeline.</p><h3>5. <strong>Configuring the Middleware Pipeline</strong></h3><p>After building the app, the next step is to configure the middleware. The middleware pipeline is responsible for handling all incoming HTTP requests, and it defines how requests are processed by the application.</p><pre>if (app.Environment.IsDevelopment())<br>{<br>    app.UseDeveloperExceptionPage();<br>}<br>else<br>{<br>    app.UseExceptionHandler(&quot;/Home/Error&quot;);<br>    app.UseHsts();<br>}<br><br>app.UseHttpsRedirection();<br>app.UseStaticFiles();<br>app.UseRouting();<br>app.UseAuthorization();<br>app.MapControllers();</pre><h4>Common Middleware Components:</h4><ul><li><strong>app.Environment.IsDevelopment()</strong>: Checks whether the app is running in the development environment. This is useful for configuring environment-specific behavior.</li><li><strong>UseDeveloperExceptionPage()</strong>: Displays detailed error information in development mode, which is useful for debugging.</li><li><strong>UseExceptionHandler(&quot;/Home/Error&quot;)</strong>: In production, this middleware handles exceptions and directs users to a custom error page.</li><li><strong>UseHsts()</strong>: Enforces HTTP Strict Transport Security (HSTS), improving security by instructing browsers to use HTTPS for future requests.</li><li><strong>UseHttpsRedirection()</strong>: Automatically redirects HTTP requests to HTTPS to ensure encrypted communication.</li><li><strong>UseStaticFiles()</strong>: Serves static files such as CSS, JavaScript, and images from the wwwroot folder.</li><li><strong>UseRouting()</strong>: Enables endpoint routing, which maps incoming requests to the appropriate route handlers like controllers.</li><li><strong>UseAuthorization()</strong>: Adds authorization checks, ensuring that only authenticated and authorized users can access protected routes.</li><li><strong>MapControllers()</strong>: Maps HTTP routes to controller actions, enabling the MVC architecture.</li></ul><h4>Custom Middleware</h4><p>You can add custom middleware to the pipeline to perform tasks such as logging, request validation, or even altering HTTP responses. A custom middleware might look like this:</p><pre>app.Use(async (context, next) =&gt;<br>{<br>    // Perform an action before the next middleware<br>    Console.WriteLine(&quot;Processing request...&quot;);<br>    <br>    await next.Invoke(); // Call the next middleware in the pipeline<br><br>    // Perform an action after the next middleware<br>    Console.WriteLine(&quot;Response sent.&quot;);<br>});</pre><h3>6. Environment-Specific Configuration</h3><p>The Program.cs file supports environment-specific configurations, allowing you to change behaviors or settings depending on whether the app is running in Development, Production, or Staging.</p><pre>if (app.Environment.IsDevelopment())<br>{<br>    app.UseDeveloperExceptionPage();<br>}<br>else<br>{<br>    app.UseExceptionHandler(&quot;/Home/Error&quot;);<br>    app.UseHsts();<br>}</pre><h4>Environment Variables:</h4><p>You can define different environment variables by setting the ASPNETCORE_ENVIRONMENT variable. For example, in a development machine, you might set:</p><pre>set ASPNETCORE_ENVIRONMENT=Development</pre><p>This helps you load different appsettings files like appsettings.Development.json or apply different configurations.</p><h3><strong>7. Running the Application: </strong><strong>app.Run()</strong></h3><pre>app.Run();</pre><p>The Run() method starts the application and begins listening for incoming HTTP requests. At this point, the middleware pipeline is fully configured, and the app is ready to handle requests. This is where the long-running process begins that keeps the web server alive and responsive to incoming traffic.</p><h3>Advanced Features in .NET Core 8</h3><p>While the basic structure of Program.cs remains relatively straightforward, .NET Core 8 brings additional features and flexibility:</p><h4>Minimal APIs</h4><p>Starting with .NET 6 and continuing in .NET 8, Minimal APIs allow you to build lightweight, high-performance APIs without the overhead of the traditional MVC structure. Here’s an example of configuring a minimal API within Program.cs:</p><pre>var app = builder.Build();<br><br>app.MapGet(&quot;/hello&quot;, () =&gt; &quot;Hello World!&quot;);<br><br>app.Run();</pre><p>This is a quick way to set up API endpoints directly in Program.cs, ideal for microservices or simple applications.</p><h4>Background Services</h4><p>.NET Core 8 also allows you to register long-running services that can execute in the background:</p><pre>builder.Services.AddHostedService&lt;BackgroundWorker&gt;();</pre><p>Here, BackgroundWorker could be a class implementing IHostedService that runs background tasks while the app is running.</p><h3>Conclusion</h3><p>The Program.cs file in .NET Core 8 is the foundational entry point for configuring and running your application. By understanding its components—such as creating the application builder, registering services, configuring the middleware pipeline, and running the application—you gain control over how your application behaves, performs, and scales.</p><p>Whether you’re building a simple API, a full-featured web app, or leveraging advanced features like background services, mastering the Program.cs file equips you with the tools to build modern, efficient, and robust applications in .NET Core 8.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d38437ea6b3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Connect Your Localhost Port with a Live Server Using Ngrok]]></title>
            <link>https://medium.com/@devnurai/how-to-connect-your-localhost-port-with-a-live-server-using-ngrok-15fb699459e1?source=rss-4ed10a6aaa41------2</link>
            <guid isPermaLink="false">https://medium.com/p/15fb699459e1</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[ngrok]]></category>
            <dc:creator><![CDATA[Nurai]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 06:47:58 GMT</pubDate>
            <atom:updated>2024-08-09T06:47:58.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_37AxPL17UFF9_22k-47OA.png" /></figure><h3>Introduction</h3><p>When developing locally, sharing your work with others can be challenging, especially if they need access to your localhost environment. Ngrok solves this problem by creating a secure tunnel to your localhost, making it accessible via a public URL. In this guide, we’ll walk you through connecting your localhost port with a live server using ngrok.</p><h3>What is Ngrok?</h3><p>Ngrok is a reverse proxy that creates a secure tunnel from a public endpoint to a web server running locally on your machine. It allows you to expose your localhost to the internet safely, enabling others to access your local applications through a public URL.</p><h3>Step 1: Install Ngrok</h3><p>Before using ngrok, you need to install it. Follow the steps below to install ngrok on your machine:</p><ol><li><strong>Visit the Ngrok Website:</strong> Go to the official ngrok website: <a href="https://ngrok.com/">https://ngrok.com/</a>.</li><li><strong>Sign Up for an Account:</strong> If you don’t already have an ngrok account, sign up for one. After signing up, you’ll receive an authentication token, which is necessary to run ngrok.</li><li><strong>Download Ngrok:</strong> Download ngrok for your operating system. Ngrok is available for Windows, macOS, and Linux.</li><li><strong>Extract the Downloaded File:</strong> After downloading, extract the file to a directory of your choice.</li><li><strong>Install Ngrok (Optional):</strong> Move the ngrok executable to a directory that’s included in your system’s PATH, so you can run ngrok from any command line.</li></ol><h3>Step 2: Authenticate Your Ngrok Installation</h3><p>To authenticate ngrok with your account, you’ll need to add your authentication token:</p><ol><li><strong>Copy the Authentication Token:</strong> After signing in, you’ll see an authentication token on the ngrok dashboard.</li><li><strong>Run the Authentication Command:</strong> Open your terminal or command prompt and run the following command, replacing YOUR_AUTH_TOKEN with the token you copied:</li></ol><pre>ngrok authtoken YOUR_AUTH_TOKEN</pre><p>This command associates your ngrok installation with your account.</p><h3>Step 3: Start Your Local Development Server</h3><p>Before running ngrok, ensure that your local development server is running on the port you want to expose. For example, if you’re running a web application on port 3000, ensure it&#39;s accessible at <a href="http://localhost:3000.">http://localhost:3000.</a></p><h3>Step 4: Start Ngrok</h3><p>Now that your server is running, you can start ngrok to expose it to the internet:</p><p><strong>Run Ngrok:</strong> In your terminal, run the following command, replacing 3000 with your localhost port number:</p><pre>ngrok http 3000</pre><p><strong>View the Public URL:</strong> Once ngrok is running, it will display a public URL that forwards traffic to your localhost. You’ll see something like this:</p><pre>Forwarding                    http://abcd1234.ngrok.io -&gt; http://localhost:3000<br>Forwarding                    https://abcd1234.ngrok.io -&gt; http://localhost:3000</pre><p><strong>Share the Public URL:</strong> You can now share the http or https public URL with others, and they will be able to access your local application as if it were hosted on a live server.</p><h3>Step 5: Secure Your Ngrok Tunnel (Optional)</h3><p>Ngrok also supports additional options for securing your tunnel:</p><p><strong>Password Protection:</strong> You can add basic authentication to your ngrok tunnel by running the following command:</p><pre>ngrok http -auth=&quot;username:password&quot; 3000</pre><p>Replace username and password with your desired credentials. Anyone accessing the public URL will be prompted to enter these credentials.</p><p><strong>Custom Subdomains:</strong> If you’re using the free plan, ngrok generates a random subdomain. However, with a paid plan, you can use custom subdomains:</p><pre>ngrok http -subdomain=mycustomdomain 3000</pre><p>Replace mycustomdomain with your desired subdomain.</p><h3>Step 6: Monitor and Analyze Traffic (Optional)</h3><p>Ngrok provides a web interface to monitor and analyze the traffic going through your tunnel:</p><ol><li><strong>Access the Web Interface:</strong> Open http://localhost:4040 in your browser. This interface provides real-time traffic monitoring, request details, and response data.</li><li><strong>Inspect Requests:</strong> You can inspect each request, replay them, and debug issues directly from the web interface.</li></ol><h3>Conclusion</h3><p>Ngrok is a powerful tool that simplifies sharing your local development environment with the outside world. Whether you’re collaborating with teammates, testing webhooks, or demonstrating your work to clients, ngrok makes it easy and secure. Follow this guide to connect your localhost port with a live server using ngrok, and start sharing your local applications with ease.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15fb699459e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Fix the “npm : File C:\Program Files\nodejs\npm.ps1]]></title>
            <link>https://medium.com/@devnurai/how-to-fix-the-npm-file-c-program-files-nodejs-npm-ps1-69515d0fb02b?source=rss-4ed10a6aaa41------2</link>
            <guid isPermaLink="false">https://medium.com/p/69515d0fb02b</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[powershell]]></category>
            <dc:creator><![CDATA[Nurai]]></dc:creator>
            <pubDate>Sun, 21 Jul 2024 13:43:59 GMT</pubDate>
            <atom:updated>2024-07-21T13:43:59.713Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Fix the “npm : File C:\Program Files\nodejs\npm.ps1 cannot be loaded because running scripts is disabled” Error</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IxLvZjAfhZXvs89uZpG_AA.png" /></figure><p>If you’ve encountered the error message below while trying to run npm install or any npm command, don&#39;t worry—you&#39;re not alone, and the solution is straightforward:</p><pre>npm : File C:\Program Files\nodejs\npm.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.<br>At line:1 char:1<br>+ npm i<br>+ ~~~<br>    + CategoryInfo          : SecurityError: (:) [], PSSecurityException<br>    + FullyQualifiedErrorId : UnauthorizedAccess</pre><p>This error occurs because PowerShell’s execution policy is set to restrict running scripts. In this article, we’ll walk you through the steps to resolve this issue.</p><h4>Step-by-Step Solution</h4><p><strong>1. Open PowerShell as Administrator</strong></p><p>First, you need to open PowerShell with administrative privileges:</p><ul><li><strong>Windows 10/11:</strong> Press Windows + X and select &quot;Windows PowerShell (Admin)&quot; or &quot;Windows Terminal (Admin)&quot; if you have Windows Terminal installed.</li><li><strong>Windows 7/8:</strong> Search for “PowerShell” in the Start menu, right-click on “Windows PowerShell,” and select “Run as administrator.”</li></ul><p><strong>2. Check the Current Execution Policy</strong></p><p>To understand the current restriction level, you can check the execution policy by running the following command:</p><pre>Get-ExecutionPolicy</pre><p>You’ll see one of the following policies: Restricted, RemoteSigned, AllSigned, or Unrestricted. The most restrictive is Restricted, which prevents all scripts from running.</p><p><strong>3. Change the Execution Policy</strong></p><p>To allow scripts to run, you need to change the execution policy to RemoteSigned. This policy allows scripts created on your local computer to run, but requires that scripts downloaded from the internet be signed by a trusted publisher.</p><p>Run the following command:</p><pre>Set-ExecutionPolicy RemoteSigned</pre><p>You may be prompted to confirm the change. Type Y (for Yes) and press Enter.</p><p><strong>4. Retry Your npm Command</strong></p><p>Now, you can try running your npm command again:</p><pre>npm i</pre><p>This time, it should work without any issues.</p><h4>Additional Information</h4><p>The execution policies in PowerShell are a security feature to prevent the execution of potentially harmful scripts. Here’s a brief overview of the available policies:</p><ul><li><strong>Restricted:</strong> No scripts can be run.</li><li><strong>AllSigned:</strong> Only scripts signed by a trusted publisher can be run.</li><li><strong>RemoteSigned:</strong> Downloaded scripts must be signed by a trusted publisher before they can be run.</li><li><strong>Unrestricted:</strong> All scripts can be run, but a warning appears before running downloaded scripts.</li></ul><p>For most users, RemoteSigned provides a good balance between security and usability.</p><h4>Conclusion</h4><p>By following these steps, you should be able to resolve the “running scripts is disabled on this system” error and successfully run your npm commands. Remember to always consider the security implications when changing execution policies on your system.</p><p>Feel free to share this article with others who might encounter the same issue. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69515d0fb02b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Git Commands: From Basic to Advanced]]></title>
            <link>https://medium.com/@devnurai/mastering-git-commands-from-basic-to-advanced-58e39d5ca9fd?source=rss-4ed10a6aaa41------2</link>
            <guid isPermaLink="false">https://medium.com/p/58e39d5ca9fd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Nurai]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 04:25:20 GMT</pubDate>
            <atom:updated>2024-06-15T04:25:20.150Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tyrGlH841a1aCkQdf-HfFQ.png" /></figure><p>Git, a distributed version control system, is an essential tool for developers to manage code changes efficiently. Understanding Git commands is crucial for collaborating on projects, maintaining code integrity, and tracking history. This blog will take you through a comprehensive journey of Git commands, from the basics to advanced usage, ensuring you become proficient in Git operations.</p><h3>Basic Git Commands</h3><h3>1. Installing Git</h3><p>Before using Git, you need to install it on your system. For most platforms, you can download it from <a href="https://git-scm.com/">git-scm.com</a>.</p><h3>2. Configuring Git</h3><p>Setting up your identity in Git is crucial for tracking changes.</p><pre>git config --global user.name &quot;Your Name&quot;<br>git config --global user.email &quot;your.email@example.com&quot;</pre><h3>3. Initializing a Repository</h3><p>To start tracking a project with Git, initialize a new repository.</p><pre>git init</pre><h3>4. Cloning a Repository</h3><p>Clone an existing repository from a remote server to your local machine.</p><pre>git clone https://github.com/username/repository.git</pre><h3>5. Checking the Status</h3><p>Check the status of your working directory and staging area.</p><pre>git status</pre><h3>6. Adding Changes</h3><p>Add changes in your working directory to the staging area.</p><pre>git add &lt;filename&gt;  # Add a specific file<br>git add .           # Add all changes in the current directory</pre><h3>7. Committing Changes</h3><p>Commit the staged changes to the repository with a message.</p><pre>git commit -m &quot;Commit message&quot;</pre><h3>8. Viewing Commit History</h3><p>View the commit history of the repository.</p><pre>git log</pre><h3>9. Pushing Changes</h3><p>Push your local commits to a remote repository.</p><pre>git push origin main</pre><h3>10. Pulling Changes</h3><p>Fetch and integrate changes from a remote repository.</p><pre>git pull origin main</pre><h3>Intermediate Git Commands</h3><h3>1. Branching</h3><p>Create, list, and switch branches to manage different versions of your project.</p><pre>git branch            # List all branches<br>git branch &lt;branch&gt;   # Create a new branch<br>git checkout &lt;branch&gt; # Switch to a branch</pre><h3>2. Merging Branches</h3><p>Merge changes from one branch into another.</p><pre>git merge &lt;branch&gt;</pre><h3>3. Resolving Merge Conflicts</h3><p>During a merge, conflicts may arise. Manually edit the conflicting files, then add and commit them.</p><pre># After editing the conflicting files<br>git add &lt;conflicted-file&gt;<br>git commit -m &quot;Resolved merge conflict&quot;</pre><h3>4. Rebasing</h3><p>Rebase your branch to apply its commits on top of another branch.</p><pre>git checkout &lt;feature-branch&gt;<br>git rebase main</pre><h3>5. Stashing Changes</h3><p>Temporarily store changes that you want to save but not commit yet.</p><pre>git stash          # Stash current changes<br>git stash pop      # Apply stashed changes</pre><h3>6. Viewing Differences</h3><p>See the changes between commits, branches, and your working directory.</p><pre>git diff &lt;commit&gt; &lt;commit&gt;   # Differences between commits<br>git diff &lt;branch&gt; &lt;branch&gt;   # Differences between branches<br>git diff                     # Differences in the working directory</pre><h3>7. Tagging</h3><p>Create tags to mark specific points in the repository’s history, often used for releases.</p><pre>git tag &lt;tagname&gt;<br>git push origin &lt;tagname&gt;</pre><h3>Advanced Git Commands</h3><h3>1. Rewriting History with Rebase</h3><p>Interactively rebase to rewrite commit history.</p><pre>git rebase -i HEAD~n  # Where n is the number of commits to look back</pre><h3>2. Cherry-Picking Commits</h3><p>Apply changes from a specific commit to your current branch.</p><pre>git cherry-pick &lt;commit&gt;</pre><h3>3. Using Bisect for Debugging</h3><p>Use binary search to find the commit that introduced a bug.</p><pre>git bisect start<br>git bisect bad      # Mark the current commit as bad<br>git bisect good &lt;commit&gt; # Mark an earlier commit as good<br># Git will now help you find the commit that introduced the bug</pre><h3>4. Submodules</h3><p>Include and manage external repositories within your project.</p><pre>git submodule add https://github.com/username/repo.git<br>git submodule update --init --recursive</pre><h3>5. Hooks</h3><p>Automate tasks with Git hooks, scripts that run at certain points in the Git workflow.</p><pre># For example, to create a pre-commit hook<br>echo -e &#39;#!/bin/sh\nexec git diff --cached --check&#39; &gt; .git/hooks/pre-commit<br>chmod +x .git/hooks/pre-commit</pre><h3>6. Resetting Changes</h3><p>Undo changes in your working directory, staging area, or repository history.</p><pre>git reset &lt;commit&gt;          # Reset to a specific commit<br>git reset --hard &lt;commit&gt;   # Discard changes in working directory<br>git reset --soft &lt;commit&gt;   # Keep changes in working directory</pre><h3>7. Squashing Commits</h3><p>Combine multiple commits into one to tidy up commit history.</p><pre>git rebase -i HEAD~n  # Mark commits to be squashed with &#39;s&#39;</pre><h3>8. Reflog</h3><p>View the reference log to see changes made to branches and commits.</p><pre>git reflog</pre><h3>Conclusion</h3><p>Mastering Git commands is a journey that enhances your productivity and collaboration in software development. From initializing repositories to advanced techniques like rebasing and submodules, Git offers a wide range of functionalities to manage your code effectively. Keep practicing these commands, and you’ll find yourself more confident and efficient in handling version control tasks. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58e39d5ca9fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FluentValidation in ASP.NET Core: A Detailed Guide]]></title>
            <link>https://medium.com/@devnurai/fluentvalidation-in-asp-net-core-a-detailed-guide-893f9837001d?source=rss-4ed10a6aaa41------2</link>
            <guid isPermaLink="false">https://medium.com/p/893f9837001d</guid>
            <category><![CDATA[fluent-validation]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Nurai]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 03:51:02 GMT</pubDate>
            <atom:updated>2024-06-15T03:51:02.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3y7_YZafmFS-IkWN1rxuCg.png" /></figure><p>Validation is a crucial aspect of any application. Ensuring that user inputs are correct and within expected parameters helps maintain data integrity and enhances user experience. ASP.NET Core offers several ways to implement validation, and one of the most effective and flexible methods is through FluentValidation. In this comprehensive guide, I will delve into FluentValidation, why it’s beneficial, and how to seamlessly integrate it into your ASP.NET Core projects.</p><h3><strong>What is FluentValidation?</strong></h3><p>FluentValidation is a popular .NET library designed for building strongly-typed validation rules for your models. It utilizes a fluent interface, making it easy to create complex validation logic in a readable and maintainable way. FluentValidation goes beyond the basic data annotations provided by ASP.NET Core, offering a richer set of validation capabilities.</p><h3>Why Use FluentValidation?</h3><p>There are several compelling reasons to use FluentValidation:</p><ul><li><strong>Separation of Concerns</strong>: FluentValidation allows you to separate your validation logic from your model classes, promoting cleaner code architecture.</li><li><strong>Readability and Maintainability</strong>: The fluent syntax of FluentValidation makes your validation rules easy to read and maintain.</li><li><strong>Extensibility</strong>: FluentValidation supports custom validators, enabling you to address specific validation requirements unique to your business logic.</li><li><strong>Seamless Integration</strong>: FluentValidation integrates smoothly with ASP.NET Core, allowing you to leverage its features with minimal configuration.</li></ul><h3>Setting Up FluentValidation in ASP.NET Core</h3><p>Let’s walk through the steps to set up and use FluentValidation in an ASP.NET Core application.</p><h3>Step 1: Install FluentValidation</h3><p>First, you need to install the FluentValidation library. This can be done via the NuGet Package Manager or the .NET CLI.</p><h4>Using NuGet Package Manager:</h4><p>Open the NuGet Package Manager Console and run the following command:</p><pre>Install-Package FluentValidation.AspNetCore</pre><h4>Using .NET CLI:</h4><p>Run the following command in your terminal:</p><pre>dotnet add package FluentValidation.AspNetCore</pre><h3>Step 2: Create Your Model</h3><p>Assume we have a simple User model that we want to validate. This model might look something like this:</p><pre>public class User<br>{<br>    public string Name { get; set; }<br>    public string Email { get; set; }<br>    public int Age { get; set; }<br>}</pre><h3>Step 3: Create a Validator</h3><p>Next, create a validator for the User model. This validator will define the rules for validating the properties of the User model.</p><pre>using FluentValidation;<br><br>public class UserValidator : AbstractValidator&lt;User&gt;<br>{<br>    public UserValidator()<br>    {<br>        RuleFor(user =&gt; user.Name)<br>            .NotEmpty().WithMessage(&quot;Name is required.&quot;)<br>            .Length(2, 50).WithMessage(&quot;Name must be between 2 and 50 characters.&quot;);<br><br>        RuleFor(user =&gt; user.Email)<br>            .NotEmpty().WithMessage(&quot;Email is required.&quot;)<br>            .EmailAddress().WithMessage(&quot;A valid email address is required.&quot;);<br><br>        RuleFor(user =&gt; user.Age)<br>            .InclusiveBetween(18, 60).WithMessage(&quot;Age must be between 18 and 60.&quot;);<br>    }<br>}</pre><h3>Step 4: Register FluentValidation</h3><p>To use FluentValidation in your ASP.NET Core project, you need to register it in the Startup.cs file. This ensures that the validators are discovered and used by the ASP.NET Core dependency injection system.</p><h4>In .NET 5 and earlier:</h4><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddControllers();<br>    services.AddFluentValidation(fv =&gt; fv.RegisterValidatorsFromAssemblyContaining&lt;UserValidator&gt;());<br>}</pre><h4>In .NET 6 and later:</h4><p>If you are using .NET 6 or later, the registration can be done in the Program.cs file.</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddControllers();<br>builder.Services.AddFluentValidation(fv =&gt; fv.RegisterValidatorsFromAssemblyContaining&lt;UserValidator&gt;());<br><br>var app = builder.Build();<br><br>app.MapControllers();<br>app.Run();</pre><h3>Step 5: Update Your Controller</h3><p>With FluentValidation registered, update your controller to leverage the validation logic. ASP.NET Core’s model binding will automatically use FluentValidation to validate incoming requests.</p><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class UsersController : ControllerBase<br>{<br>    [HttpPost]<br>    public IActionResult CreateUser(User user)<br>    {<br>        if (!ModelState.IsValid)<br>        {<br>            return BadRequest(ModelState);<br>        }<br><br>        // Process the valid user data here<br><br>        return Ok();<br>    }<br>}</pre><h3>Step 6: Test Your Validation</h3><p>Run your application and test the validation by sending various requests to your API. You should see validation errors when the input does not meet the defined rules.</p><h3>Advanced Features of FluentValidation</h3><p>FluentValidation offers a range of advanced features that can help you create more sophisticated validation logic.</p><h3>Custom Validators</h3><p>You can create custom validators to handle specific validation scenarios. For example, if you want to create a custom validator to ensure that a string property contains only alphabetic characters, you can do so like this:</p><pre>public class AlphabeticValidator&lt;T&gt; : PropertyValidator&lt;T, string&gt;<br>{<br>    public override bool IsValid(ValidationContext&lt;T&gt; context, string value)<br>    {<br>        return value.All(char.IsLetter);<br>    }<br><br>    public override string Name =&gt; &quot;AlphabeticValidator&quot;;<br><br>    protected override string GetDefaultMessageTemplate(string errorCode)<br>        =&gt; &quot;{PropertyName} must contain only alphabetic characters.&quot;;<br>}</pre><p>You can then use this custom validator in your UserValidator:</p><pre>public class UserValidator : AbstractValidator&lt;User&gt;<br>{<br>    public UserValidator()<br>    {<br>        RuleFor(user =&gt; user.Name)<br>            .SetValidator(new AlphabeticValidator&lt;User&gt;())<br>            .WithMessage(&quot;Name must contain only alphabetic characters.&quot;)<br>            .NotEmpty().WithMessage(&quot;Name is required.&quot;)<br>            .Length(2, 50).WithMessage(&quot;Name must be between 2 and 50 characters.&quot;);<br><br>        RuleFor(user =&gt; user.Email)<br>            .NotEmpty().WithMessage(&quot;Email is required.&quot;)<br>            .EmailAddress().WithMessage(&quot;A valid email address is required.&quot;);<br><br>        RuleFor(user =&gt; user.Age)<br>            .InclusiveBetween(18, 60).WithMessage(&quot;Age must be between 18 and 60.&quot;);<br>    }<br>}</pre><h3>Conditional Validation</h3><p>FluentValidation allows you to apply validation rules conditionally. For instance, you might want to validate a field only if another field has a certain value.</p><pre>RuleFor(user =&gt; user.Email)<br>    .NotEmpty().WithMessage(&quot;Email is required.&quot;)<br>    .EmailAddress().When(user =&gt; !string.IsNullOrEmpty(user.Email)).WithMessage(&quot;A valid email address is required.&quot;);</pre><h3>Collection Validation</h3><p>If your model contains a collection, you can validate each element within that collection using the ForEach method.</p><pre>public class Order<br>{<br>    public List&lt;OrderItem&gt; Items { get; set; }<br>}<br><br>public class OrderItem<br>{<br>    public string ProductName { get; set; }<br>    public int Quantity { get; set; }<br>}<br><br>public class OrderValidator : AbstractValidator&lt;Order&gt;<br>{<br>    public OrderValidator()<br>    {<br>        RuleForEach(order =&gt; order.Items).SetValidator(new OrderItemValidator());<br>    }<br>}<br><br>public class OrderItemValidator : AbstractValidator&lt;OrderItem&gt;<br>{<br>    public OrderItemValidator()<br>    {<br>        RuleFor(item =&gt; item.ProductName)<br>            .NotEmpty().WithMessage(&quot;Product name is required.&quot;);<br><br>        RuleFor(item =&gt; item.Quantity)<br>            .GreaterThan(0).WithMessage(&quot;Quantity must be greater than zero.&quot;);<br>    }<br>}</pre><h3>Conclusion</h3><p>FluentValidation is a powerful tool that enhances the validation capabilities of ASP.NET Core applications. By using FluentValidation, you can write more maintainable and expressive validation logic, making your code cleaner and easier to manage. Whether you are building simple applications or complex enterprise systems, FluentValidation provides the flexibility and extensibility needed to handle your validation requirements effectively. Start integrating FluentValidation into your ASP.NET Core projects today and experience the benefits of more robust and readable validation logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=893f9837001d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to host website on Github with custom domain?]]></title>
            <link>https://medium.com/@devnurai/how-to-host-website-on-github-with-custom-domain-e03e52361dca?source=rss-4ed10a6aaa41------2</link>
            <guid isPermaLink="false">https://medium.com/p/e03e52361dca</guid>
            <category><![CDATA[hosting]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[domain-names]]></category>
            <dc:creator><![CDATA[Nurai]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 10:25:49 GMT</pubDate>
            <atom:updated>2023-04-13T10:26:40.201Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, you will get to know how you can host your custom domain name website for free using the Github.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_JfvuQo1j_kRg2R2e4H8_A.jpeg" /><figcaption>Host your custom domain website for free using Github pages.</figcaption></figure><h3>Hosting a website on GitHub with a custom domain can be done by following these steps:</h3><ul><li><strong>Create a GitHub repository for your website: </strong>If you haven’t already done so, create a new repository on GitHub for your website. Make sure to name it “<em>username.github.io</em>”, where “<em>username</em>” is your GitHub username.</li><li><strong>Upload your website files: </strong>Upload your website files to the repository. You can do this by using the GitHub web interface or by using a Git client.</li><li><strong>Set up your custom domain: </strong>Go to your domain registrar and set up a CNAME record that points your custom domain to your GitHub Pages URL. This will look something like “<em>yourdomain.com</em> CNAME <em>username.github.io</em>”.</li><li><strong>Configure GitHub Pages: </strong>In your repository settings, go to the “<em>GitHub Pages</em>” section and select the “<em>Custom domain</em>” option. Enter your custom domain name and click “<em>Save</em>”.</li><li><strong>Update your DNS settings:</strong> In your domain registrar’s DNS settings, add a CNAME record that points your custom domain to your GitHub Pages URL.</li><li><strong>Wait for DNS propagation: </strong>DNS changes can take some time to propagate, so you may need to wait a few hours or up to a day for your custom domain to start working with your GitHub Pages site.</li></ul><p>Once all of these steps are completed, your website should be successfully hosted on GitHub with your custom domain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e03e52361dca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>