<?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 Breno Batista Machado on Medium]]></title>
        <description><![CDATA[Stories by Breno Batista Machado on Medium]]></description>
        <link>https://medium.com/@brenobm?source=rss-a0f3444e6d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0WmNtcplh8VZX-nD39OqmA.jpeg</url>
            <title>Stories by Breno Batista Machado on Medium</title>
            <link>https://medium.com/@brenobm?source=rss-a0f3444e6d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 16:32:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brenobm/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[Building a Project Management Tool with ASP.NET 7 and React: Part 2— User Authentication]]></title>
            <link>https://medium.com/@brenobm/building-a-project-management-tool-with-asp-net-7-and-react-part-2-user-authentication-d118041fec3c?source=rss-a0f3444e6d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d118041fec3c</guid>
            <category><![CDATA[web-api-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[aspnet-core-web-api]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Breno Batista Machado]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 08:24:28 GMT</pubDate>
            <atom:updated>2023-10-30T17:24:16.144Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y92My_sHQqOkdjJBj-stCQ.png" /></figure><p>Welcome back to the second installment of our hands-on tutorial series where we meticulously craft a dynamic project management tool from scratch! If you’ve been following along, you know that we embarked on this enlightening journey with an insightful introduction and environment setup in Part 1. In this segment, our expedition will primarily revolve around establishing a robust authentication system and configuring the database to safeguard and manage user data with finesse.</p><p>Before diving in, let’s swiftly navigate through the roadmap of our tutorial series to grasp the trajectory of our learning journey:</p><ol><li><a href="https://medium.com/@brenobm/building-a-project-management-tool-with-asp-net-f5f40cd84a04"><strong>Introduction &amp; Environment Setup</strong></a></li><li><strong>User Authentication (You are here)</strong></li><li>Project Management</li><li>Task Management</li><li>Team Management</li><li>Dashboard &amp; Overview</li><li>Bonus Features</li><li>Styling &amp; Final Touches</li><li>Deployment &amp; Conclusion</li></ol><p>Ensuring that users are who they claim to be, authentication stands as the bastion of a secure web application. Our focus will be to weave in ASP.NET Core Identity into our project, a powerful membership system that furnishes a suite of functionalities like user registration, password recovery, and authentication seamlessly out of the box.</p><p>Paired with authentication, configuring the database is pivotal. We’ll employ MS SQL Server, laying the groundwork for our application to manage dynamic data efficiently. As architects of this tool, we aim to construct secure, reliable, and functional backend infrastructures, paving the way for enhanced user experiences and interactions.</p><p>So, buckle up as we embark on this segment of our journey, reinforcing our project management tool with essential security and functional features, marking another significant milestone in our development adventure.</p><h3>Authentication with ASP.NET Core</h3><p>Authentication is a crucial part of any application. It ensures that the identity of users is verified, and only authenticated users can access specific resources within an application. In this part of the tutorial, we will focus on implementing authentication in our project management tool using ASP.NET Core Identity.</p><h3>1. Understanding Authentication in Web Applications</h3><p>Authentication is the cornerstone of security for web applications. It is the process that ensures an application knows who its users are and whether they are who they say they are. Before delving into the practical aspects of authentication in our project, let’s first build a solid understanding of the core concepts and the role authentication plays in application security.</p><h4>Defining Authentication</h4><p>At its core, authentication is the process of verifying the identity of a user, system, or application. In the context of web applications, it primarily focuses on validating user identities. When a user tries to access a web application, they are usually required to provide credentials, such as a username and password. The application then verifies these credentials against stored data to ensure they are correct, granting access if the validation is successful.</p><h4>Role in Application Security</h4><p>Authentication serves as the first line of defense in securing an application. It acts as a gateway, ensuring that only authorized users can access certain functionalities and data. Without a robust authentication mechanism, malicious actors could easily access sensitive information and functionalities, leading to a wide array of potential security issues such as data breaches and unauthorized actions.</p><p>In our project management tool, authentication will secure user data and projects, ensuring that only authorized users can create, modify, or delete projects and tasks. It is paramount to establish a secure authentication process to uphold the integrity and confidentiality of user data and projects.</p><h4>Key Concepts and Components</h4><ul><li><strong>Credentials</strong>: These are the pieces of information used to verify a user’s identity. In most cases, this involves a username and password, but it could also include other factors like a security token or biometric data.</li><li><strong>Tokens</strong>: Tokens are used in token-based authentication to grant users access after successful login. A token is a piece of data generated by the server that can be used for subsequent authentication requests, ensuring the user doesn’t have to provide credentials repeatedly.</li><li><strong>Sessions</strong>: Sessions represent a period of interaction between the user and the application. Once a user is authenticated, a session is established, allowing the user to interact with the application securely. Sessions have a start and end, usually ending when the user logs out or after a period of inactivity.</li><li><strong>Multi-factor Authentication (MFA)</strong>: MFA adds an additional layer of security by requiring users to provide two or more verification factors to prove their identity. This could involve something they know (password), something they have (a phone), or something they are (biometric verification).</li></ul><p>Understanding these fundamental concepts is crucial as they form the foundation upon which we will build our authentication system. With a solid grasp of what authentication entails and why it is so essential, we are now better equipped to implement it effectively in our ASP.NET Core project, ensuring the security of our project management tool.</p><h3>2. Setting Up Authentication using ASP.NET Core Identity</h3><p>ASP.NET Core Identity is a powerful membership system that adds login functionality to your application, helping to manage users, passwords, profile data, roles, claims, tokens, email confirmation, and more. It’s a comprehensive and extensible system that provides all the necessary tools to secure your application and manage user-related data effectively.</p><h4>Introduction to ASP.NET Core Identity</h4><ul><li><strong>Comprehensive Membership System</strong>: ASP.NET Core Identity is a complete package that deals with user management and authentication, from user registration to password recovery.</li><li><strong>Modular and Extensible</strong>: It allows for the customization of data models, and you can also plug in different storage systems such as Azure Table Storage, NoSQL databases, etc.</li><li><strong>Claims-based Authentication</strong>: This feature enables the application to assign claims to users. Claims are key-value pairs associated with a user that you can use to control access in your application.</li><li><strong>Role-based Authorization</strong>: This is a feature that allows you to categorize users into roles for the management of access control.</li><li><strong>Security Stamps</strong>: Security stamps enable you to invalidate a user’s session when their security profile changes, such as when a password is modified.</li><li><strong>Third-party Login</strong>: ASP.NET Core Identity supports third-party login providers such as Google, Facebook, Twitter, etc., which can simplify the authentication process for users.</li></ul><h4>Integration into the Project</h4><p>The integration of ASP.NET Core Identity into our project can be done by following the steps below:</p><p>1. Installing Necessary Packages</p><ul><li>In your Visual Studio, navigate to NuGet Package Manager.</li><li>Install the following packages:<br>-Microsoft.AspNetCore.Identity.EntityFrameworkCore at the projects:<br>=&gt;ManagementTool.Entities-<br>=&gt;ManagementTool.Infrastructure.Persistence<br>=&gt;ManagementTool.UI.WebApi<br>-Microsoft.AspNetCore.Identity.UI at the project:<br>=&gt;ManagementTool.UI.WebApi <br>- Microsoft.EntityFrameworkCore.Design<br>=&gt;ManagementTool.Infrastructure.Persistence <br>- Microsoft.EntityFrameworkCore.SqlServer <br>=&gt;ManagementTool.UI.WebApi<br>=&gt;ManagementTool.Infrastructure.Persistence</li></ul><p>2. Configuring the Data Context</p><ul><li>Customize the user identity class by extending IdentityUser. This allows for the addition of extra fields in the user model.</li></ul><pre>// Project: ManagementTool.Entities<br>using Microsoft.AspNetCore.Identity;<br><br>namespace ManagementTool.Entities.Identity;<br><br>public class ApplicationUser : IdentityUser<br>{<br>    public string Name { get; set; }<br>    public string Avatar { get; set; }<br>}</pre><ul><li>Inherit from IdentityDbContext in your data context class. Ensure you import the necessary namespaces.</li></ul><pre>// Project: ManagementTool.Infrastrucutre.Persistence<br>using ManagementTool.Entities.Identity;<br>using Microsoft.AspNetCore.Identity.EntityFrameworkCore;<br><br>namespace ManagementTool.Infrastructure.Persistence.Context;<br><br>public class ApplicationDbContext : IdentityDbContext&lt;ApplicationUser&gt;<br>{<br>    public ApplicationDbContext(DbContextOptions&lt;ApplicationDbContext&gt; options)<br>    : base(options)<br>    {<br>    }<br>}</pre><p>3. Configuring Program.cs</p><ul><li>In Program.cs, add the following services and configure the application to use authentication and authorization.</li></ul><pre>// ... (other services configuration)<br><br>builder.Services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;<br>        options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;ApplicationConnectionString&quot;)));<br><br>// Adding Identity services<br>builder.Services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;()<br>    .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;()<br>    .AddDefaultTokenProviders();<br><br>// Adding authentication services<br>builder.Services.AddAuthentication(options =&gt;<br>{<br>    options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;<br>    options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;<br>    options.DefaultSignInScheme = IdentityConstants.ExternalScheme;<br>});<br><br>// ... (other services configuration)<br><br>var app = builder.Build(); // Existing code<br><br>app.UseAuthentication();<br>app.UseAuthorization();<br><br>// ... (other middleware configuration)</pre><ul><li>In this step it was configured the ASP.NET Core Identity to use the new ApplicationUser model as the user identity and using the ApplicationDbContext that inherits all the Identity Entity Framework configuration necessary.</li><li>Ensure that include the following imports:</li></ul><pre>using ManagementTool.Entities.Identity;<br>using ManagementTool.Infrastructure.Persistence.Context;<br>using Microsoft.AspNetCore.Identity;<br>using Microsoft.EntityFrameworkCore;</pre><p>4. Configure the database connection string</p><ul><li>In appsettings.json file add the connection string that was configured when installing the Microsoft SQL Server Express in the previous part, changing the database name to PMTool</li></ul><pre>  &quot;ConnectionStrings&quot;: {<br>    &quot;ApplicationConnectionString&quot;: &quot;Server=localhost\SQLEXPRESS;Database=PMTool;Trusted_Connection=True;&quot;<br>  }</pre><p>5. Setting up the Database</p><ul><li>Run the commands below in the Package Manager Console. These commands will generate the code for the migrations and them apply the migrations, setting up the necessary tables in your database. If you don’t have the ef tool installed, use this command to install it: dotnet tool install --global dotnet-ef</li></ul><pre>dotnet ef migrations add Identity --project ManagementTool.Infrastructure.Persistence --startup-project ManagementTool.UI.WebApi<br>dotnet ef database update --project ManagementTool.Infrastructure.Persistence --startup-project ManagementTool.UI.WebApi</pre><ul><li><strong>TIP:</strong> If you run an error like:</li></ul><pre>Only the invariant culture is supported in globalization-invariant mode. See https://aka.ms/GlobalizationInvariantMode for more information. (Parameter &#39;name&#39;)<br>en-us is an invalid culture identifier.</pre><ul><li>Change InvariantGlobalization to false in the file ManagementTool.UI.WebApi.csproj.</li></ul><pre>  &lt;PropertyGroup&gt;<br>    &lt;TargetFramework&gt;net7.0&lt;/TargetFramework&gt;<br>    &lt;Nullable&gt;disable&lt;/Nullable&gt;<br>    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;<br>    &lt;InvariantGlobalization&gt;false&lt;/InvariantGlobalization&gt;<br>  &lt;/PropertyGroup&gt;</pre><p>6. Configuring the Application for User Registration and Login</p><p>ASP.NET Core Identity comes bundled with Razor Class Library (RCL) that includes prebuilt Razor pages for user account management functionalities like registration, login, and password reset. While this is a handy feature that can accelerate development, in this tutorial, we’ve chosen a different path. Since our front end will be constructed using React.js in the later sections of this tutorial, we will bypass the built-in Razor pages in favor of developing a custom Web API. This API will expose endpoints for user registration, login, and password reset functionalities, ensuring that our React.js front end has the necessary hooks for user authentication.</p><p>Let’s outline the basic functionalities that our Web API will expose:</p><ul><li><strong>User Registration</strong>: An endpoint that will allow new users to register, creating a new account within the application.<br>- URI: /api/register<br>- Method: POST</li><li><strong>User Login</strong>: An endpoint that will authenticate users, returning an authentication token upon successful login. <br>- URI: /api/login <br>- Method: POST</li><li><strong>Password Reset</strong>: An endpoint that facilitates the password reset process, allowing users to recover access to their accounts if they forget their password.<br>- URI: /api/reset-password <br>- Method: POST</li></ul><p>By creating these endpoints, we lay the groundwork for the React.js front end, which will be developed in Part 3 of this tutorial series, to interact with the ASP.NET Core back end for authentication-related activities effectively. This approach ensures a separation of concerns, where the back end focuses on data processing and business logic, and the front end concentrates on user interaction and experience.</p><p>By following the steps above, you should have successfully integrated ASP.NET Core Identity into your project. ASP.NET Core Identity will now handle user authentication, simplifying the process of managing user accounts, roles, and claims, thus providing a secure environment for user data and interactions in your application.</p><h3>3. Building Authentication Features</h3><h4>User Registration Endpoint</h4><p>Now we’ll write the code for implementing the User Registration endpoint for your Project Management Tool. It will allow the new users register in the our tool. We’ll be creating an API controller that includes a POST endpoint for user registration.</p><p>First, let’s define a model to handle the registration data:</p><pre>// Project: ManagementTool.Entities<br>using System.ComponentModel.DataAnnotations;<br><br>namespace ManagementTool.Entities.Register;<br><br>public class RegisterModel<br>{<br>    [Required]<br>    public string Name { get; set; }<br><br>    [Required]<br>    [EmailAddress]<br>    public string Email { get; set; }<br><br>    [Required]<br>    [StringLength(100, ErrorMessage = &quot;The {0} must be at least {2} and at max {1} characters long.&quot;, MinimumLength = 6)]<br>    public string Password { get; set; }<br><br>    [Compare(&quot;Password&quot;, ErrorMessage = &quot;The password and confirmation password do not match.&quot;)]<br>    public string ConfirmPassword { get; set; }<br><br>    public string Avatar { get; set; }<br>}</pre><p>Now, let’s create the AccountsController to handle user registration:</p><pre>// Project: ManagementTool.UI.WebApi<br>using ManagementTool.Entities.Register;<br>using Microsoft.AspNetCore.Identity;<br>using Microsoft.AspNetCore.Mvc;<br><br>namespace ManagementTool.UI.WebApi.Controllers;<br><br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class AccountsController : ControllerBase<br>{<br>    private readonly UserManager&lt;ApplicationUser&gt; _userManager;<br>    private readonly SignInManager&lt;ApplicationUser&gt; _signInManager;<br><br>    public AccountsController(UserManager&lt;ApplicationUser&gt; userManager, SignInManager&lt;ApplicationUser&gt; signInManager)<br>    {<br>        _userManager = userManager;<br>        _signInManager = signInManager;<br>    }<br><br>    [HttpPost(&quot;register&quot;)]<br>    public async Task&lt;IActionResult&gt; Register(RegisterModel model)<br>    {<br>        if (ModelState.IsValid)<br>        {<br>            var user = new ApplicationUser<br>            {<br>                UserName = model.Email,<br>                Email = model.Email,<br>                Name = model.Name,<br>                Avatar = model.Avatar<br>            };<br><br>            var result = await _userManager.CreateAsync(user, model.Password);<br><br>            if (result.Succeeded)<br>            {<br>                await _signInManager.SignInAsync(user, isPersistent: false);<br>                return Ok(new { Message = &quot;Registration successful&quot; });<br>            }<br><br>            foreach (var error in result.Errors)<br>            {<br>                ModelState.AddModelError(string.Empty, error.Description);<br>            }<br>        }<br><br>        return BadRequest(ModelState);<br>    }<br>}</pre><p>This AccountsController has a Register method that:</p><ul><li>Receives registration data (email and password) from the client.</li><li>Creates a new user using the UserManager.</li><li>Signs in the user and returns a success message if registration is successful.</li><li>Returns validation errors if the registration fails.</li></ul><p>With the configurations we did previously in the program.cs file, for adding authentication and authorization, will ensure that the necessary services, like UserManager and SignInManager, will be properly registered in the Dependency Injection container, and the middleware will be correctly configured to handle authentication and authorization in your application.</p><p>As our initial WebApi project uses Minimal API’s, we need to change this configuration to use the Controllers files. For this, we need to change the fileprogram.cs for:</p><ul><li>Include the AddControllers, include it after the AddAuthorization</li></ul><pre>// ... (other services configuration)<br><br>builder.Services.AddControllers();<br><br>// ... (other services configuration)<br></pre><ul><li>Removing this code:</li></ul><pre>var summaries = new[]<br>{<br>    &quot;Freezing&quot;, &quot;Bracing&quot;, &quot;Chilly&quot;, &quot;Cool&quot;, &quot;Mild&quot;, &quot;Warm&quot;, &quot;Balmy&quot;, &quot;Hot&quot;, &quot;Sweltering&quot;, &quot;Scorching&quot;<br>};<br><br>app.MapGet(&quot;/weatherforecast&quot;, (ILogger&lt;Program&gt; logger) =&gt;<br>{<br>    logger.LogDebug(&quot;Executing `/weatherforecast`&quot;);<br>    var forecast =  Enumerable.Range(1, 5).Select(index =&gt;<br>        new WeatherForecast<br>        (<br>            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),<br>            Random.Shared.Next(-20, 55),<br>            summaries[Random.Shared.Next(summaries.Length)]<br>        ))<br>        .ToArray();<br>    return forecast;<br>})<br>.WithName(&quot;GetWeatherForecast&quot;)<br>.WithOpenApi();</pre><p>And replace that for:</p><pre>app.MapControllers();</pre><p>For the avatar upload functionality, it involves creating an endpoint that can handle file uploads, saving the image in a retrievable location, and returning a URL to access the image.</p><p>1. Create a Folder to Store Avatars</p><p>First, create a folder within your project where the avatar images will be stored. For instance, you can create a folder named Avatars within the wwwroot directory. The wwwroot directory is a special folder in ASP.NET Core projects where static files can be stored and directly accessed via a URL.</p><p>2. Configure Static Files Middleware</p><p>Ensure that your application is configured to serve static files. This configuration is usually available by default. In the Configure method within program.cs, you should have the following line:</p><pre>app.UseStaticFiles(); // Enable static files middleware</pre><p>3. Create the Avatar Upload Endpoint</p><p>In your controller AccountsController, create an endpoint to handle avatar uploads. This endpoint should accept a file, save it within the Avatars folder, and return a URL to access the file.</p><pre>    [HttpPost(&quot;avatar&quot;)]<br>    public async Task&lt;IActionResult&gt; UploadAvatar(IFormFile avatar)<br>    {<br>        if (avatar == null || avatar.Length == 0)<br>            return BadRequest(&quot;No file uploaded.&quot;);<br><br>        var uploadsFolder = Path.Combine(&quot;wwwroot&quot;, &quot;Avatars&quot;);<br>        if (!Directory.Exists(uploadsFolder))<br>        {<br>            Directory.CreateDirectory(uploadsFolder);<br>        }<br><br>        var uniqueFileName = Guid.NewGuid().ToString() + &quot;_&quot; + avatar.FileName;<br>        var filePath = Path.Combine(uploadsFolder, uniqueFileName);<br><br>        using (var fileStream = new FileStream(filePath, FileMode.Create))<br>        {<br>            await avatar.CopyToAsync(fileStream);<br>        }<br><br>        var avatarUrl = Url.Content($&quot;~/Avatars/{uniqueFileName}&quot;);<br><br>        return Ok(new { avatarUrl });<br>    }<br>}</pre><ul><li>This endpoint is a POST method that accepts a file as input.</li><li>It checks whether a file is uploaded.</li><li>It saves the file in the Avatars directory under wwwroot.</li><li>It generates a unique filename using a GUID to avoid filename conflicts.</li><li>The file is saved with a combination of a unique identifier and the original filename.</li><li>It returns the URL to access the uploaded avatar.</li></ul><p>Before deeping dive to the next endpoint, the Login, let’s talk about JWT Tokens.</p><h4>Understanding JWT Tokens</h4><p>JWT, which stands for JSON Web Token, is a compact, URL-safe token format used for securely transmitting information between parties. The information can be verified and trusted because it is digitally signed, and it can also be encrypted for added security.</p><p>A JWT token consists of three parts:</p><ol><li><strong>Header</strong>: The header typically consists of two parts: the type of token, which is JWT, and the signing algorithm, such as HMAC SHA256 or RSA.</li><li><strong>Payload</strong>: The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.</li><li><strong>Signature</strong>: To create the signature part, you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.</li></ol><p>For example, if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:</p><pre>HMACSHA256(<br>  base64UrlEncode(header) + &quot;.&quot; +<br>  base64UrlEncode(payload),<br>  secret)</pre><p>The resulting JWT serves as a token that can be sent over the network and can be verified by the receiver to ensure its integrity and authenticity. JWTs are commonly used for authentication and information exchange in web development. In the context of authentication, after a user logs in, a server could generate a JWT that encodes the user’s information and permissions. This JWT can then be sent to the client, who can include it in their subsequent requests, allowing the server to identify and authorize the user.</p><p>In our application, we utilize JWTs to manage user sessions securely. After a successful login, the backend server generates a JWT that encompasses the user’s details, which is then utilized for authorizing the user to access protected routes and resources. Thus, enabling a secure and efficient way to manage user authentication and authorization within our application.</p><h4>Why We Chose JWT for Authentication</h4><p>Choosing JWT as our authentication method comes with several benefits that align well with our application’s architecture and goals:</p><ol><li><strong>Statelessness: </strong>JWTs are self-contained, carrying all the information necessary for verification. This property allows our application to be stateless, enabling better scalability as our application grows.</li><li><strong>Security:</strong> JWTs can be signed and encrypted, ensuring the data’s integrity and confidentiality. This feature is crucial for secure transmission of sensitive information over the network.</li><li><strong>Decoupling: </strong>Since JWTs are self-contained, our authentication mechanism becomes decoupled, making it more flexible. This flexibility is beneficial as our application comprises a React.js frontend and an ASP.NET Core backend.</li><li><strong>Standardized: </strong>JWT is a widely adopted standard (RFC 7519), ensuring that our application follows industry best practices, and allows us to leverage existing libraries and tools.</li><li><strong>Cross-Domain Authentication: </strong>JWT facilitates a smooth and secure cross-domain authentication process, essential for our application where the backend and frontend exist separately.</li></ol><h4>Flow Between the ASP.NET Core WebAPI and React.js UI using JWT</h4><p><strong>1. User Registration/Login:</strong></p><ul><li>The user registers or logs in through the React.js frontend by providing necessary details such as username and password.</li><li>The frontend sends these details to the ASP.NET Core WebAPI.</li></ul><p><strong>2. Token Generation:</strong></p><ul><li>Upon successful authentication, the backend generates a JWT that encodes the user’s information and permissions, then sends this token back to the frontend.</li></ul><p><strong>3. Token Storage:</strong></p><ul><li>The frontend receives the token and stores it securely, typically in HTTP cookies or the browser’s localStorage/sessionStorage.</li></ul><p><strong>4. Authenticated Requests:</strong></p><ul><li>For subsequent requests to protected endpoints, the frontend attaches the JWT in the Authorization header of the HTTP request. It usually follows the “Bearer TOKEN” schema.</li></ul><p><strong>5. Token Verification:</strong></p><ul><li>The backend receives the request, extracts the token from the Authorization header, and verifies its validity, such as checking the signature and expiration time.</li></ul><p><strong>6. Access to Protected Resources:</strong></p><ul><li>If the token is valid, the backend grants access to the protected resources. Otherwise, it returns an error, prompting the frontend to handle it, possibly by asking the user to log in again.</li></ul><p><strong>7. Token Renewal/Expiration:</strong></p><ul><li>Tokens might have an expiration time for added security. In such cases, the frontend must implement a renewal strategy, such as using refresh tokens, to ensure that the user remains authenticated without needing to log in again manually.</li></ul><p>This flow ensures a secure, efficient, and scalable authentication mechanism, compatible with our application’s decoupled architecture, enhancing user experience and application security.</p><h4>Configuring JWT Authentication</h4><p>We need to make a few configurations in our project to enable the usage of JWT Token as our authentication mechanism.</p><p>First, it is necessary to include the following two packages in the project WebApi project</p><pre>System.IdentityModel.Tokens<br>Microsoft.AspNetCore.Authentication.JwtBearer</pre><p>In the program.cs file, configure the application to use JWT authentication by adding necessary services and middleware.</p><pre>// ... Other configurations ...<br><br>var jwtSettings = builder.Configuration.GetSection(&quot;JwtSettings&quot;);<br>builder.Services.Configure&lt;JwtSettings&gt;(jwtSettings);<br><br>var secret = Encoding.ASCII.GetBytes(jwtSettings.Get&lt;JwtSettings&gt;().Secret);<br><br>// Adding authentication services<br>builder.Services.AddAuthentication(options =&gt;<br>{<br>    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;<br>    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;<br>    options.DefaultSignInScheme = IdentityConstants.ExternalScheme;<br>}).AddJwtBearer(token =&gt;<br>{<br>    token.RequireHttpsMetadata = false;<br>    token.SaveToken = true;<br>    token.TokenValidationParameters = new TokenValidationParameters<br>    {<br>        ValidateIssuerSigningKey = true,<br>        IssuerSigningKey = new SymmetricSecurityKey(secret),<br>        ValidateIssuer = false,<br>        ValidateAudience = false<br>    };<br>});<br><br>// ... Other configurations ...</pre><p>And configure the secret on appsettings.json, to include your secret key, and creates the settings model class.</p><pre>{<br>  &quot;JwtSettings&quot;: {<br>    &quot;Secret&quot;: &quot;YourSecretKeyHere&quot;<br>  },<br>  // ... Other settings ...<br>}</pre><pre>// Project: ManagementTool.Entities<br>namespace ManagementTool.Entities.Settings;<br><br>public class JwtSettings<br>{<br>    public string Secret { get; set; }<br>}</pre><h4>Login Endpoint</h4><p>Now that we’ve laid the foundation by creating a user account registration endpoint, it’s time to march forward and facilitate our users with the ability to log in to their accounts. Our goal here is quite straightforward but crucial. We aim to craft an endpoint that stands responsible for authenticating the user credentials. But that’s just part of the story!</p><p>We are not just authenticating the user; we are creating a secure passage for the user to interact with our application seamlessly. This is where the JWT (JSON Web Token) comes into play. Our endpoint will not just stop at authenticating, but it will go a step further by generating a JWT token for the authenticated user.</p><p>So, in essence, our login endpoint will be a two-fold process:</p><ol><li>Authenticate the user by verifying the provided credentials.</li><li>Generate a JWT token that will serve as a passkey for the users, granting them the required access.</li></ol><p>This token then travels back to the user, unlocking the doors to interact with the various functionalities of our application, ensuring a secure and smooth user experience. In the upcoming sections, we’ll dive deep into the actual implementation, guiding you through the journey of bringing this login endpoint to life, paired with JWT token generation and management. So, buckle up, and let’s get it rolling!</p><p>First, let’s implement the request model class:</p><pre>// Project: ManagementTool.Entities<br>using System.ComponentModel.DataAnnotations;<br><br>namespace ManagementTool.Entities.Login;<br><br>public class LoginModel<br>{<br>    [Required]<br>    public string Email { get; set; }<br>    <br>    [Required] <br>    public string Password { get; set; }<br>}</pre><p>Then, the endpoint code. We’ll create a new controller AuthController.cs, with the required parameters on the constructor IOptions&lt;JwtSettings&gt; jwtSettings.</p><pre>// Project: ManagementTool.UI.WebApi<br>using ManagementTool.Entities.Identity;<br>using ManagementTool.Entities.Login;<br>using ManagementTool.Entities.Settings;<br>using Microsoft.AspNetCore.Identity;<br>using Microsoft.AspNetCore.Mvc;<br>using Microsoft.Extensions.Options;<br>using Microsoft.IdentityModel.Tokens;<br>using System.IdentityModel.Tokens.Jwt;<br>using System.Security.Claims;<br>using System.Text;<br>namespace ManagementTool.UI.WebApi.Controllers;<br><br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class AuthController : ControllerBase<br>{<br>    private readonly UserManager&lt;ApplicationUser&gt; _userManager;<br>    private readonly IOptions&lt;JwtSettings&gt; _jwtSettings;<br><br>    public AuthController(<br>        UserManager&lt;ApplicationUser&gt; userManager,<br>        IOptions&lt;JwtSettings&gt; jwtSettings)<br>    {<br>        _userManager = userManager;<br>        _jwtSettings = jwtSettings;<br>    }<br><br>    [HttpPost(&quot;login&quot;)]<br>    public async Task&lt;IActionResult&gt; Login([FromBody] LoginModel model)<br>    {<br>        var user = await _userManager.FindByEmailAsync(model.Email);<br>        if (user == null || !await _userManager.CheckPasswordAsync(user, model.Password))<br>        {<br>            return Unauthorized();<br>        }<br><br>        var authClaims = new List&lt;Claim&gt;<br>        {<br>            new(ClaimTypes.Name, user.UserName),<br>            new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),<br>            new(ClaimTypes.NameIdentifier, user.Id),<br>        };<br><br>        var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Value.Secret));<br><br>        var token = new JwtSecurityToken(<br>            expires: DateTime.Now.AddHours(3),<br>            claims: authClaims,<br>            signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)<br>        );<br><br>        return Ok(new<br>        {<br>            token = new JwtSecurityTokenHandler().WriteToken(token),<br>            expiration = token.ValidTo<br>        });<br>    }<br>}</pre><ul><li>This code involves a controller with a login endpoint that authenticates users and generates JWT tokens.</li><li>It uses UserManager to find users and validate passwords.</li><li>It creates JWT tokens with claims and a signature, and it sets the expiration of the token.</li></ul><h4>Password Reset Flow</h4><p>The password reset flow typically follows these steps:</p><h4>1. Requesting a Password Reset</h4><ul><li>User Interaction: The user interacts with the front end, typically entering their email address to initiate the password reset process.</li><li>Backend Process: The backend receives the request, generates a secure token, and sends an email to the user with a link containing this token.</li></ul><h4>2. Email Confirmation</h4><ul><li>Receiving Email: The user receives an email containing a unique link to reset their password. This link includes a secure token as a parameter.</li><li>Clicking the Link: The user clicks the link, which leads them to a password reset page.</li></ul><h4>3. Resetting the Password</h4><ul><li>Entering New Password: The user enters a new password (and confirms it) on the reset page.</li><li>Backend Process: The backend validates the token, ensures it hasn’t expired, and then updates the user’s password in the database.</li></ul><h4>4. Completion and Redirection</h4><ul><li>Success Message: The user is informed of the successful password reset and is often redirected to the login page to sign in with their new password.</li></ul><h3>Detailed Backend Flow:</h3><ul><li>Token Generation and Email Sending:<br>- When the user requests a password reset, the backend generates a unique token.<br>- This token is either attached to the user’s record in the database or stored separately with a reference to the user.<br>- An email is sent to the user’s registered email address with a unique URL containing the token.</li><li>Token Verification:<br>- When the user accesses the reset page via the unique URL, the token in the URL is verified against the stored token.<br>- Checks are made to ensure the token hasn’t expired or been used previously.</li><li>Password Reset: <br>- Once the token is verified, the user is allowed to reset their password.<br>- The new password is hashed and stored in the database, replacing the old password hash.</li></ul><p>Implementing this flow in your ASP.NET Core application will involve using built-in features of the ASP.NET Core Identity system, customization to suit our specific needs, and the integration of email services to handle the sending of password reset emails.</p><p>To fulfill this flow, it requires the following endpoints in our backend:</p><h4>1. Request Password Reset</h4><ul><li><strong>Path</strong>: /api/auth/request-password-reset</li><li><strong>Method</strong>: POST</li><li><strong>Description</strong>: This endpoint is responsible for initiating the password reset process. It takes the user’s email as input, generates a secure token, and sends a password reset email to the user.</li><li><strong>Parameters</strong>: <br>-Email: The email of the user requesting the password reset.</li></ul><h4>2. Verify Token and Reset Password</h4><ul><li><strong>Path</strong>: /api/auth/reset-password</li><li><strong>Method</strong>: POST</li><li><strong>Description</strong>: This endpoint allows the user to reset their password. It takes the secure token and the new password as input, validates the token, and updates the user’s password in the database if valid.</li><li><strong>Parameters</strong>: <br>-Token: The secure token sent to the user&#39;s email. <br>-NewPassword: The new password that the user wants to set.<br>-ConfirmPassword: A confirmation of the new password.</li></ul><h4>3. Validate Reset Token</h4><ul><li><strong>Path</strong>: /api/auth/validate-reset-token</li><li><strong>Method</strong>: POST or GET</li><li><strong>Description</strong>: Optionally, you might want an endpoint to solely validate the token before allowing the user to enter a new password. It checks if the token is valid and has not expired.</li><li><strong>Parameters</strong>: <br>-Token: The secure token sent to the user&#39;s email.</li></ul><p>Here is a simplified diagram of how these endpoints interact in the flow:</p><ol><li>User Requests Password Reset</li></ol><ul><li>Frontend sends a POST request to /api/auth/request-password-reset with the user&#39;s email.</li><li>Backend sends a reset email with a token.</li></ul><p>2. User Clicks on Email Link</p><ul><li>User is directed to a password reset page on the frontend, or optionally, the frontend first verifies the token by calling /api/auth/validate-reset-token.</li></ul><p>3. User Resets Password</p><ul><li>Frontend sends a POST request to /api/auth/reset-password with the new password and the token.</li><li>Backend validates the token, resets the password, and responds with a success or error message.</li></ul><p>These endpoints together allow for a secure and user-friendly password reset process, with clear separation of concerns and steps, enhancing security and maintainability. Now let’s to proceed with the code implementation details for these endpoints.</p><h4>Request Password Reset Endpoint</h4><p>For this endpoint we will create a new action on the existing AuthController.cs, and including a new required service on the constructor IEmailService emailService.</p><pre><br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class AuthController : ControllerBase<br>{<br>    private readonly UserManager&lt;ApplicationUser&gt; _userManager;<br>    private readonly IOptions&lt;JwtSettings&gt; _jwtSettings;<br>    private readonly IOptions&lt;AuthSettings&gt; _authSettings;<br>    private readonly IEmailService _emailService;<br><br>    public AuthController(<br>        UserManager&lt;ApplicationUser&gt; userManager,<br>        IOptions&lt;JwtSettings&gt; jwtSettings,<br>        IOptions&lt;AuthSettings&gt; authSettings,<br>        IEmailService emailService)<br>    {<br>        _userManager = userManager;<br>        _jwtSettings = jwtSettings;<br>        _authSettings = authSettings;<br>        _emailService = emailService;<br>    }<br><br>    // ... (Existing actions)<br><br>    [HttpPost(&quot;request-password-reset&quot;)]<br>    public async Task&lt;IActionResult&gt; RequestPasswordReset([FromBody] ResetPasswordRequestModel model)<br>    {<br>        var user = await _userManager.FindByEmailAsync(model.Email);<br>        if (user == null)<br>        {<br>            // User doesn&#39;t exist, return a generic response to avoid enumeration attacks<br>            return Ok(&quot;If an account matches that email, a password reset email has been sent.&quot;);<br>        }<br><br>        var token = await _userManager.GeneratePasswordResetTokenAsync(user);<br><br>        var resetLink = $&quot;{_authSettings.Value.ResetPasswordUrl}/{token}&quot;;        var message = $&quot;To reset your password, please click on this link {resetLink}&quot;;<br><br>        await _emailService.SendEmailAsync(model.Email, &quot;Reset Password&quot;, message);<br><br>        return Ok(&quot;Password reset email has been sent.&quot;);<br>    }<br>}</pre><p>I will revisit the IEmailService class later, for now, let’s just define the interface.</p><pre>// Project: ManagementTool.Core.Services<br>namespace ManagementTool.Core.Services.Messaging;<br><br>public interface IEmailService<br>{<br>    Task SendEmailAsync(string email, string subject, string message);<br>}</pre><p>And we need to create the request model for this APIas well.</p><pre>// Project: ManagementTool.Entities<br>namespace ManagementTool.Entities.ResetPassword;<br><br>public class ResetPasswordRequestModel<br>{<br>    public string Email { get; set; }<br>}</pre><p>And we can see the class AuthSettings on the controller, it will hold the reset password link, that will be configured on appsettings.json</p><pre>{<br>  // Others configurations<br><br>  &quot;AuthSettings&quot;: {<br>    &quot;ResetPasswordUrl&quot;: &quot;https://localhost:5173/reset-password&quot;<br>  }<br>}</pre><pre>// Project: ManagementTool.Entities<br>namespace ManagementTool.Entities.Settings;<br><br>public class AuthSettings<br>{<br>    public string ResetPasswordUrl { get; set; }<br>}</pre><p>And we are just missing the configuration on program.cs to include the dependency injection of this class.</p><pre>builder.Services.Configure&lt;AuthSettings&gt;(builder.Configuration.GetSection(&quot;AuthSettings&quot;));</pre><h3>Overview of SendGrid</h3><p><strong>SendGrid </strong>is a cloud-based email delivery service that assists businesses with email delivery. <a href="https://sendgrid.com/pricing/">SendGrid </a>helps you send transactional or marketing emails, and it has various features like analytics and APIs that allow custom integrations, among others. It’s especially powerful for developers who need to send transactional emails from their applications.</p><h4>How to Configure SendGrid:</h4><ol><li><strong>Create a SendGrid Account:</strong></li></ol><ul><li>Visit the SendGrid website and sign up for a free account.</li><li>The free tier allows you to send up to 100 emails per day forever.</li></ul><p><strong>2. Verify Your Email:</strong></p><ul><li>After signing up, verify your email address by confirming it through a verification email sent by SendGrid.</li></ul><p><strong>3. Create an API Key:</strong></p><ul><li>o to the API keys section in the settings of your SendGrid dashboard.</li><li>Create a new API key by giving it a name and choosing the “Full Access” permission.</li><li>Save the API key; you’ll need it to configure the EmailService in your application.</li></ul><h3>Implementing EmailService Using SendGrid:</h3><p>First, install the SendGrid NuGet package: SendGrid at the project ManagementTool.Infrastructure.</p><p>Create the appsettings.json section for storing the SendGrid API Key and sender information. We’ll need to create the respective model for this configuration.</p><pre>  &quot;SendGridSettings&quot;: {<br>    &quot;FromEmail&quot;: &quot;your@email.com&quot;,<br>    &quot;FromName&quot;: &quot;Your Name&quot;,<br>    &quot;ApiKey&quot;: &quot;SendGridApiKeyComesHere-PleaseNotSaveOnGit&quot;<br>  }</pre><pre>// Project: ManagementTool.Entities<br>namespace ManagementTool.Entities.Settings;<br><br>public class SendGridSettings<br>{<br>    public string ApiKey { get; set; }<br><br>    public string FromEmail { get; set; }<br><br>    public string FromName { get; set; }<br>}</pre><p>And configure the DI for this configuration section in Program.cs:</p><pre>// ... Other configurations ...<br><br>builder.Services.Configure&lt;SendGridSettings&gt;(builder.Configuration.GetSection(&quot;SendGridSettings&quot;));<br><br>// ... Other configurations ...</pre><p>Here’s a way to implement the EmailService:</p><pre>// ManagementTool.Infrastructure<br>using ManagementTool.Core.Services.Messaging;<br>using ManagementTool.Entities.Settings;<br>using Microsoft.Extensions.Options;<br>using SendGrid;<br>using SendGrid.Helpers.Mail;<br><br>namespace ManagementTool.Infrastructure.Messaging;<br><br>public class EmailService : IEmailService<br>{<br>    private readonly IOptions&lt;SendGridSettings&gt; _sendGridSettings;<br><br>    public EmailService(IOptions&lt;SendGridSettings&gt; sendGridSettings)<br>    {<br>        _sendGridSettings = sendGridSettings;<br>    }<br><br>    public async Task SendEmailAsync(string email, string subject, string message)<br>    {<br>        var client = new SendGridClient(_sendGridSettings.Value.ApiKey);<br>        var from = new EmailAddress(_sendGridSettings.Value.FromEmail, _sendGridSettings.Value.FromName);<br>        var to = new EmailAddress(email);<br>        var msg = MailHelper.CreateSingleEmail(from, to, subject, message, message);<br>        await client.SendEmailAsync(msg);<br>    }<br>}</pre><p>And finally, register the EmailService on the DI container in the Program.cs.</p><pre>// ... (other services configuration)<br><br>builder.Services.AddTransient&lt;IEmailService, EmailService&gt;();<br><br>// ... (other services configuration)</pre><h3>Verify Token and Reset Password</h3><p>Path: /api/auth/reset-password</p><p>Resetting a password involves two essential steps: verifying the token and updating the password. Our endpoint will receive a token, user email, and the new password from the client. Let’s delve deeper into implementing this endpoint.</p><h4>Step 1: Define the Model</h4><p>First, let’s define a model that will handle the data from the client. The model will include properties such as Email, Token, and NewPassword.</p><pre>// Project: ManagementTool.Entities<br>using System.ComponentModel.DataAnnotations;<br><br>namespace ManagementTool.Entities.ResetPassword;<br><br>public class ResetPasswordModel<br>{<br>    [Required]<br>    [EmailAddress]<br>    public string Email { get; set; }<br><br>    [Required]<br>    public string Token { get; set; }<br><br>    [Required]<br>    [DataType(DataType.Password)]<br>    public string NewPassword { get; set; }<br>}</pre><h4>Step 2: Creating the Endpoint</h4><p>Now, let’s create an HTTP POST endpoint that will handle the password resetting process in our AuthController .</p><pre>    [HttpPost(&quot;reset-password&quot;)]<br>    public async Task&lt;IActionResult&gt; ResetPassword(ResetPasswordModel model)<br>    {<br>        if (!ModelState.IsValid)<br>            return BadRequest(ModelState);<br><br>        var user = await _userManager.FindByEmailAsync(model.Email);<br>        if (user == null)<br>            return BadRequest(&quot;Invalid token or email.&quot;);<br><br>        var resetPassResult = await _userManager.ResetPasswordAsync(user, model.Token, model.NewPassword);<br>        if (!resetPassResult.Succeeded)<br>            return BadRequest(resetPassResult.Errors);<br><br>        return Ok(&quot;Password has been successfully reset.&quot;);<br>    }</pre><h3>Validate Reset Token</h3><p>Path: /api/auth/validate-reset-token</p><p>This endpoint will receive a token and user email, and its responsibility is to validate whether the token associated with the email is valid or not.</p><h4>Step 1: Define the Model</h4><p>Let’s define a model that will handle the data from the client. The model will include properties such as Email and Token.</p><pre>// Project: ManagementTool.Entities<br>using System.ComponentModel.DataAnnotations;<br><br>namespace ManagementTool.Entities.ResetPassword;<br><br>public class ValidateResetTokenModel<br>{<br>    [Required]<br>    [EmailAddress]<br>    public string Email { get; set; }<br><br>    [Required]<br>    public string Token { get; set; }<br>}</pre><h4>Step 2: Creating the Endpoint</h4><p>Now, let’s create an HTTP POST endpoint that will handle the token validation process.</p><pre>    [HttpPost(&quot;validate-reset-token&quot;)]<br>    public async Task&lt;IActionResult&gt; ValidateResetToken(ValidateResetTokenModel model)<br>    {<br>        if (!ModelState.IsValid)<br>            return BadRequest(ModelState);<br><br>        var user = await _userManager.FindByEmailAsync(model.Email);<br>        if (user == null)<br>            return BadRequest(&quot;Invalid token or email.&quot;);<br><br>        var validToken = await _userManager.VerifyUserTokenAsync(user,<br>                            _userManager.Options.Tokens.PasswordResetTokenProvider,<br>                            &quot;ResetPassword&quot;, model.Token);<br><br>        if (!validToken)<br>            return BadRequest(&quot;Invalid token.&quot;);<br><br>        return Ok(&quot;Token is valid.&quot;);<br>    }</pre><h3>Testing the Authentication Flow</h3><p><strong>Step 1: Protecting an API Endpoint</strong></p><p>For our test, we will create an dummy endpoint, just to ensure the authentication flow works.</p><p>Create a new controller for the endpoint. Decorate the endpoint with an [Authorize] attribute to ensure it&#39;s protected by JWT authentication.</p><pre>using ManagementTool.Entities.Identity;<br>using Microsoft.AspNetCore.Authorization;<br>using Microsoft.AspNetCore.Identity;<br>using Microsoft.AspNetCore.Mvc;<br><br>namespace ManagementTool.UI.WebApi.Controllers;<br><br>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>public class GreetingController : ControllerBase<br>{<br>    private readonly UserManager&lt;ApplicationUser&gt; _userManager;<br><br>    public GreetingController(UserManager&lt;ApplicationUser&gt; userManager)<br>    {<br>        _userManager = userManager;<br>    }<br><br>    [Authorize]<br>    [HttpGet]<br>    public async Task&lt;IActionResult&gt; GetGreeting()<br>    {<br>        var user = await _userManager.GetUserAsync(User);<br>        return Ok($&quot;Hello .Net Devs! I&#39;m {user.UserName}&quot;);<br>    }<br>}</pre><h4>Step 2: Testing the Secured Endpoint</h4><p>All tests will executed using Swagger interface, that comes configured by default on the ASP.NET Web API projects.<br>The Swagger interface describes all the endpoints in the project and allows to test them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_iRPiRY6jkAFIIHySd_Xww.png" /></figure><p>1. Uploading an Avantar</p><ul><li>Endpoint: /api/account/avatar</li><li>Method: POST</li><li>Body: Swagger will have an button for upload an image file</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNS46_RXs6kBZ5euJneZCA.png" /></figure><p>2. Registering a New User</p><ul><li>Endpoint: /api/account/register</li><li>Method: POST</li><li>Body:</li></ul><pre>{<br>  &quot;name&quot;: &quot;Your Name&quot;,<br>  &quot;email&quot;: &quot;yourvalidemail@email.com&quot;,<br>  &quot;password&quot;: &quot;YourStrongPwd#123&quot;,<br>  &quot;confirm password&quot;: &quot;YourStrongPwd#123&quot;,<br>  &quot;avatar&quot;: &quot;/Avatars/a3ed4451-4dc2-4147-adc7-5441c23898f3_management-tool-article.png&quot; // Response from upload avatar endpoint<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v04cxewOJ20eabHIhtF9hw.png" /></figure><p>3. Authenticating the User</p><ul><li>Endpoint: /api/account/login</li><li>Method: POST</li><li>Body:</li></ul><pre>{<br>    &quot;Email&quot;: &quot;example@email.com&quot;,<br>    &quot;Password&quot;: &quot;YourSecurePassword&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueJaamrHs8U4gP-Dmf53Vw.png" /></figure><p>After a successful login, you will receive a JWT token in the response.</p><p>4. Calling the Protected Endpoint</p><p>For this endpoint, we’ll use Postman, to allow us to use the JWT Token.</p><p>On Postman, make a call like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*he9r7IrPFPObYXnxo6jGXw.png" /></figure><ul><li><strong>Endpoint</strong>: /greeting</li><li><strong>Method</strong>: GET</li><li><strong>Headers</strong>:<br>- <strong>Key</strong>: Authorization<br>- <strong>Value</strong>: Bearer YOUR_JWT_TOKEN</li></ul><p>After setting the Authorization header with the received JWT token, you can access the protected endpoint, and you should receive the personalized greeting.</p><p>By following these steps, you can effectively protect your API endpoints and test the authentication mechanism using JWT tokens within your ASP.NET Core application.</p><h3>Overview of Entity Framework Core (EF Core)</h3><p>Previous, when configuring the ASP.Net Core Identity, we executed some commands related to Entity Framework Core. Basically we were creating the database tables necessary for the Identity framework to work.</p><p>Entity Framework Core (EF Core) is an advanced Object-Relational Mapping (ORM) framework for .NET, allowing developers to work with databases using .NET objects. It eliminates the need for most of the data-access code that developers usually need to write. EF Core provides various functionalities such as change tracking, query translation, and others out of the box.</p><h4>Principal Concepts</h4><ul><li><strong>DbContext</strong>: The DbContext class is a primary class in EF Core, representing a session with the database. It allows querying and saving data, and it’s a conduit to access configured models and their relationships.</li><li><strong>DbSet</strong>: DbSet represents a collection of entities of a specific type, where you can perform create, read, update, and delete operations.</li><li><strong>Migrations</strong>: Migrations in EF Core enable syncing changes in the data model with the database schema. Migrations include schema creations, table creations, and managing relationships.</li><li><strong>LINQ Queries</strong>: EF Core uses Language Integrated Query (LINQ) to retrieve and manipulate data. LINQ queries offer compile-time syntax checking, static typing, and IntelliSense support in Visual Studio.</li></ul><h4>How it Works</h4><p>EF Core supports two main workflows:</p><ol><li><strong>Database-First</strong>: In this approach, the database schema is pre-existing, and EF Core generates the corresponding models and DbContext based on the database schema. It’s mainly used when you have an existing database, and you want to generate the models without manual intervention.</li><li><strong>Code-First</strong>: This approach involves creating the application’s data model in code first. EF Core migrations can then be used to generate a database schema based on these models. Developers have control over the model’s design without having to worry about the database design.</li></ol><h3>Style of Usage in Our Project: Code-First</h3><p>In our project, we will utilize the Code-First approach. Here’s an overview of how we’ll proceed:</p><ul><li><strong>Models</strong>: We will begin by creating our models, which will represent the application’s data and define the schema of our database.</li><li><strong>Configurations with Fluent API</strong>: Fluent API will allow us to configure our models. Fluent API provides more configuration options than Data Annotations. It enables us to configure our model to database mappings, giving us more control over the database schema.</li><li><strong>Migrations</strong>: Migrations will be used to keep the database schema in sync with the models. Whenever we make changes to our models, we will create a migration that EF Core will use to apply the changes to the database.</li></ul><p>By using the Code-First approach, we maintain the flexibility of evolving our application’s data model and ensuring that these changes are reflected in our database schema through migrations. This approach aligns well with the iterative and incremental nature of modern web application development.</p><h3>Conclusion</h3><p>In this part of the tutorial, we have laid a strong foundation for authentication in our Project Management Tool. We began by understanding the essential concept of authentication in web applications, diving into details about its significance and the usual flows followed. Following this, we introduced ASP.NET Core Identity as a powerful tool to manage users and their authentication. A crucial part of our tutorial was dedicated to implementing various endpoints such as User Registration, User Login, and Password Reset, each crafted meticulously to manage different aspects of user authentication.</p><p>We also introduced Entity Framework Core, discussing its core concepts, functionalities, and the different approaches it offers, such as Code First and Database First. Our focus was on the Code First approach, where we handled model creation and database interactions programmatically.</p><p>Alongside, we incorporated external services like SendGrid to manage email sending for password reset functionality, ensuring that our application could interact beyond its boundaries in a secure and reliable manner. Lastly, we secured an API endpoint using JWT tokens, ensuring it’s accessible only with a valid token, thus safeguarding our application’s sensitive data.</p><h3>Next Steps</h3><p>In the upcoming Part 3 of the tutorial, we’ll delve into Project Management, an essential component of our application. Here’s a glimpse of what to expect:</p><ul><li>Designing the Project Model and its CRUD Operations: We will structure our project model, carefully defining necessary attributes and relationships. This will be complemented by the implementation of CRUD operations, ensuring our application can manage project data effectively.</li><li>Concepts and Setup Configuration for React.js: A comprehensive introduction to React.js will be provided, preparing you for the frontend development of our application. Necessary configurations and setup will be discussed in detail to get you started.</li><li>Implementing the Frontend Components: Armed with React.js knowledge, we will develop various frontend components responsible for project creation, editing, and deletion, ensuring a user-friendly interface and experience.</li><li>Introduction to Testing: A new dimension will be added by introducing testing to our application. Both unit tests and integrated tests will be discussed, providing you with the tools necessary to ensure the reliability and robustness of your application.</li></ul><p>Stay tuned for a detailed and enriching continuation of our journey in developing a robust Project Management Tool!</p><p>And, as usual, all the code in this tutorial can be found on my <a href="https://github.com/brenobm/ManagementTool/tree/part_2-User_Authentication">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d118041fec3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Project Management Tool with ASP.NET]]></title>
            <link>https://medium.com/@brenobm/building-a-project-management-tool-with-asp-net-f5f40cd84a04?source=rss-a0f3444e6d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5f40cd84a04</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[web-api-development]]></category>
            <dc:creator><![CDATA[Breno Batista Machado]]></dc:creator>
            <pubDate>Tue, 24 Oct 2023 22:56:48 GMT</pubDate>
            <atom:updated>2023-10-30T08:25:08.214Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Project Management Tool with ASP.NET 7 and React: Part 1 — Introduction &amp; Environment Setup</h3><p>Welcome to the beginning of an exhilarating journey where we embark on the mission to build a comprehensive Project Management Tool from scratch. This series is designed to guide you through every corner, every decision, and every step of creating a dynamic, robust, and efficient web application. Our technological allies in this journey will be ASP.NET 7 for the backend, React for the frontend, and SQL Server Express to safeguard our data, all homed by the powerful Azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_iQYY5NfH6vn9FVDEgIskw.png" /></figure><h3>Series Overview</h3><p>This tutorial is tentatively structured into nine meticulous parts, each dedicated to unfolding vital chapters of our project. However, flexibility is our friend; the actual number of parts may vary as we delve deeper into each section, ensuring that each feature and concept receives the spotlight it deserves.</p><ol><li><strong>Introduction &amp; Environment Setup<br></strong>- Introduce the project, its features, and the tech stack.<br>- Set up the development environment: installing necessary tools, creating a new project, etc.</li><li><a href="https://medium.com/@brenobm/building-a-project-management-tool-with-asp-net-7-and-react-part-2-user-authentication-d118041fec3c"><strong>User Authentication</strong></a> <br>- Setting up an authentication system.<br>- Creating register, login, and password reset functionalities.</li><li><strong>Project Management<br></strong>- Designing the project model and its CRUD operations.<br>- Implementing the frontend components for project creation, editing, and deletion.</li><li><strong>Task Management<br></strong>- Designing the task model and its CRUD operations.<br>- Implementing the frontend components for task creation, editing, and deletion.</li><li><strong>Team Management<br></strong>- Designing the user model for team members.<br>- Implementing invite and removal functionalities.</li><li><strong>Dashboard &amp; Overview<br></strong>- Creating a dashboard for projects and tasks.<br>- Implementing an overview of tasks (e.g., pie chart or progress bar to show completed vs. pending tasks).</li><li><strong>Bonus Features<br></strong>- Implementing notifications.<br>- Adding a commenting system for tasks.</li><li><strong>Styling &amp; Final Touches<br></strong>- Introduction to styling the application to make it visually appealing.<br>- Using CSS frameworks or styled components in React for styling.</li><li><strong>Deployment &amp; Conclusion<br></strong>- Preparing the project for deployment to Azure.<br>- Reflecting on what has been learned, potential improvements, and next steps.</li></ol><h3>Our Objective</h3><p>Our saga has a clear objective: to offer a panoramic view of building a full-fledged project, knitting together various technologies and practices to breathe life into our Project Management Tool. We’ll wander through authentic user stories, sculpting functionalities that echo real-world needs and solutions.</p><p>However, while our eyes are set on a horizon of comprehensiveness, our feet tread the path of simplicity and clarity. We aim to unfurl the big picture, painting broad strokes that manifest the project’s architecture and flow. It means that while we will touch on various concepts and stages essential for web development, we may not delve into the abyss of every intricate detail.</p><p>Stay with us, explore, and witness the chronicles of constructing a Project Management Tool that resonates with practicality, functionality, and usability.</p><h3>Project Description</h3><p>In this series, we will build a Project Management Tool, a sophisticated application designed to simplify the complexities of managing various aspects of projects. The tool will serve as a centralized hub where users can seamlessly manage projects, tasks, and team collaborations. Each feature of our tool is tailored to enhance efficiency and productivity, ensuring that project goals are met with precision and clarity.</p><p>Here’s a comprehensive breakdown of the user stories that will form the blueprint of our Project Management Tool:</p><h3>User Authentication</h3><ul><li>As a user, I want to register so that I can access the tool’s features and manage projects.</li><li>As a user, I want to log in to access my dashboard and engage with my projects and tasks.</li><li>As a user, I want to reset my password in case I forget it, ensuring that I can always access my account.</li></ul><h3>Project Creation and Management</h3><ul><li>As a user, I want to create a new project to initiate and organize the necessary tasks and assign team members.</li><li>As a user, I want to edit project details to ensure that project information, such as titles, descriptions, and deadlines, remains accurate and up-to-date.</li><li>As a user, I want to delete a project when it is completed or no longer needed, maintaining a clean and focused dashboard.</li></ul><h3>Task Creation and Assignment</h3><ul><li>As a user, I want to add tasks to a project to outline the necessary steps for project completion.</li><li>As a user, I want to edit task details to manage task assignees, descriptions, and statuses efficiently.</li><li>As a user, I want to delete a task to keep the project organized and focused on remaining action items.</li></ul><h3>Team Member Management</h3><ul><li>As a user, I want to invite team members to a project to collaborate and distribute tasks effectively.</li><li>As a user, I want to remove team members from a project to manage the team structure as project needs evolve.</li></ul><h3>Dashboard</h3><ul><li>As a user, I want to view all my projects on a dashboard for a quick and easy overview.</li><li>As a user, I want to see an overview of tasks to easily comprehend the progress and statuses of various projects and tasks.</li></ul><p>These user stories will serve as our guiding stars, steering the direction of our project as we embark on this hands-on journey through the realms of ASP.NET, React, SQL Server Express, and Azure.</p><h3>Technology Stack</h3><ul><li>In this tutorial series, our mission is to construct a seamless Project Management Tool. To accomplish this, we’ve enlisted a robust set of technologies, each bringing unique strengths to our project. Let’s dive into our technology stack and unravel how each component contributes to our application’s architecture and functionality.</li></ul><h3>ASP.NET 7</h3><p>Our backend champion is ASP.NET 7, a powerful and flexible framework renowned for building high-performance, modern web applications. Within the realms of ASP.NET 7:</p><ul><li>Entity Framework (EF) 7: We’ll harness EF 7, an advanced ORM (Object-Relational Mapper), to manage our database interactions with elegance and efficiency. EF 7 will act as our bridge, seamlessly connecting our application’s objects with the database, fostering a streamlined data interaction landscape.</li><li>REST Web APIs: The essence of our backend will be manifested through RESTful Web APIs, serving as the lifeblood of our application’s data flow. These APIs will facilitate smooth and secure interactions between our frontend, built with React, and the data housed in our SQL Server database.</li></ul><h3>React</h3><p>React, our frontend maestro, empowers our application with a dynamic and responsive user interface. Revered for its component-based architecture, React will allow us to craft reusable components, ensuring a consistent and efficient development process, as well as a cohesive user experience.</p><h3>SQL Server Express</h3><p>Our choice for data safeguarding is SQL Server Express, a reliable and robust database management system. SQL Server Express will house our application’s data, ensuring it’s organized, secure, and accessible for smooth and efficient operations.</p><h3>Azure</h3><p>Azure, Microsoft’s cloud computing service, will be the home where our application takes flight to be accessible to users worldwide. Our deployment strategy on Azure will involve:</p><ul><li>App Service: We’ll utilize Azure App Service for hosting our web application. This fully managed platform enables us to build, deploy, and scale our application with ease, allowing us to focus on crafting and enhancing our application’s features.</li><li>Database Hosting: Our SQL Server Express database will also find its home on Azure, ensuring it benefits from Azure’s reliability, security, and scalability features.</li><li>Continuous Integration/Continuous Deployment (CI/CD): By leveraging Azure’s CI/CD capabilities, we’ll foster a streamlined deployment pipeline, ensuring that our application’s latest and greatest versions are effortlessly and continuously delivered to our users.</li></ul><h3>Setting Up the Environment on Windows 11</h3><h3>Prerequisites:</h3><ul><li>Operating System: Windows 11</li><li>Development Tools: Visual Studio 2022 Community Edition</li><li>Database: SQL Server Express</li></ul><h3>Steps:</h3><h4>1. Install Visual Studio 2022 Community Edition</h4><ul><li>Download: Visit the <a href="https://visualstudio.microsoft.com/downloads/">official Visual Studio download page</a> and download Visual Studio 2022 Community Edition.</li><li>Installation: Run the installer and select the necessary workloads and components, ensuring that you choose the ASP.NET and web development workload, which includes essential tools and features for web development.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9PZ6u1L69NxLY25exWxAw.png" /></figure><ul><li>Configuration: Configure Visual Studio based on your preferences to tailor the IDE to your workflow.</li></ul><h4>2. Install SQL Server Express</h4><ul><li>Download: Acquire SQL Server Express from the <a href="https://www.microsoft.com/en-us/sql-server/sql-server-downloads">official download page</a>.</li><li>Installation: Follow the installation process, choosing the basic installation for the default configurations.</li><li>Configuration: Write down the Connection String and the Instance Name for connecting later.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sPwS2eRvIFwSXoGLU1_0Qw.png" /></figure><h4>3. Configure SQL Server Express</h4><ul><li>Connect to the Server: <a href="https://learn.microsoft.com/en-us/sql/ssms/sql-server-management-studio-ssms?view=sql-server-ver16">Open SQL Server Management Studio (SSMS)</a> and connect to the server using the credentials configured during the installation process.</li><li>Create a Database: Initiate a new database that will serve as the data repository for our Project Management Tool.</li><li>Manage Connections: Ensure that the server is configured to allow the necessary connections, facilitating smooth communication between our application and the database.</li></ul><h3>Creating the First Project in Visual Studio</h3><ol><li>Open Visual Studio 2022 and select “Create a new project.”</li><li>Choose “React and ASP.NET Core (Preview)” and click “Next.” This action will forge two distinct projects: a pure React project and an ASP.NET Web API Project.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GdxPQwVYqLIrXVyQwdt5yA.png" /></figure><p>3. Name your project, choose a location, and click “Create.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0C36DKLz5DB_DSMLlhmiw.png" /></figure><p>4. The project will have both the React App Project and the WebApi Project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nv0wph1Y5sKDuCcvzrRzWA.png" /></figure><p>5. For clarity, let’s bestow more intuitive names upon these projects:</p><ul><li>Rename reactapp to ManagementTool.UI.App.</li><li>Rename webapi to ManagementTool.UI.WebApi.</li><li>A simple way to rename a project is by clicking on the Project Name, pressing &quot;F2,&quot; and then typing in the new name.</li></ul><p>6. Execute the project by hitting the “Start” button or pressing the “F5” key. Doing so will operate both projects simultaneously, inaugurating two browser windows — one flaunting the Swagger Definition for the Web API project and the other exhibiting the React App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Chd8s0_N9scLKljiYxsAkg.png" /></figure><p>Now that we have our first project structure, let’s create the additional projects that we are going to organize our code.</p><figure><a href="https://learn.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/common-web-application-architectures#clean-architecture"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uOTVRrrsF2bRbeNe.png" /></a></figure><p>We are going to use the Clean Architecture<a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">¹</a><a href="https://learn.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/common-web-application-architectures#clean-architecture">²</a> structure for our project, a concept introduced by Robert C. Martin (Uncle Bob), aimed at creating a separation of concerns by dividing the software into different layers. This architecture promotes the independence of software components, allowing for improved maintainability and flexibility:</p><ul><li><strong>User Interface (UI) -</strong> This layer is responsible for interacting with the users, capturing their inputs, and presenting data and results. It encompasses everything related to the user experience, including views, controllers, and presenters. Communicates with the Application Core to process and retrieve data, ensuring that user actions trigger appropriate application responses.<br>- <strong><em>ManagementTool.UI.App</em></strong> — The Frontend as a SPA application on React.js<br>- <strong><em>ManagementTool.UI.WebApi</em></strong> — The Backend as a Web API in ASP.NET.</li><li><strong>Infrastructure</strong>: This layer houses technical concerns that support application functionalities, such as database access, file systems, and network services. It contains the implementation of interfaces defined in the Application Core. Interfaces with external systems and manages data flow into the Application Core, acting as a bridge for data exchange.<br>- <strong><em>ManagementTool.Infrastructure</em></strong> — Framework-specific code, where we going to include the import of 3rd party frameworks<br>- <strong><em>ManagementTool.Infrastructure.Persistence</em></strong> — Where we are going to implement the Entity Framework code to access our Microsoft SQL Server database.</li><li><strong>Application Core</strong>: The heart of the system, containing business logic, use cases, entities, and abstractions of external services. It holds the high-level rules of the application and orchestrates its fundamental operations.Coordinates between the UI and Infrastructure layers, processing data, and executing business rules to facilitate specific use cases.<br>- <strong><em>ManagementTool.Core.Services</em></strong> — Implementation of the Business Layers<br>- <strong><em>ManagementTool.Core.Persistence</em></strong> — Interface of the Persistence Layer, being independent of any framework</li><li><strong>Application Entities</strong>: Entities reside within the Application Core and represent the application’s business objects. They encapsulate the business logic and data pertinent to the application’s domain. Engages directly with the business logic and use cases in the Application Core, enabling the representation and manipulation of business concepts.<br>- <strong><em>ManagementTool.Entities </em></strong>— Where we are going to implement our model.</li></ul><p>So, we still need to create a few projects.</p><ol><li>Fortify your solution by adding new projects. Right-click on the Solution, select Add &gt; New Project, choose “Class Library” (C#), and sail through the subsequent prompts.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwpFAc39v2zS0HnUfU9xuA.png" /></figure><p>2. Select “Class Library” (for C#), and click “Next”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEid_0BR0zhC7WI4UpuoNg.png" /></figure><p>3. Fill the project name, and “Next”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-CnRGTp-Kx3kCfJIoQPOSg.png" /></figure><p>4. Select the Framework for .NET 7.0 and “Create”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QkFHdWknXqJtJpZO_M5IhA.png" /></figure><p>5. Remove the created file “Class1.cs”. We are going to populate the projects with classes later.</p><p>6. Do it for all necessary projects until you have this structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*KlIJ16r3OywSwNB6SaZ7mg.png" /></figure><p>In this tutorial we will ignore the Nullable feature, so for that, double-click in each Project file and edit the &lt;Nullable&gt;enable&lt;/Nullable&gt; to &lt;Nullable&gt;disable&lt;/Nullable&gt;. Do it for all projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*cFKPbNzidP07EIktIFG_8Q.png" /></figure><h3>Integrating Serilog into ASP.NET Web API for Enhanced Logging</h3><p>Logging is a crucial aspect of any application, providing insights into the application’s operations, errors, and performance. Serilog offers a powerful, easy-to-use logging library that can be seamlessly integrated into ASP.NET projects. Follow the steps below to integrate Serilog into your ASP.NET Web API:</p><h3>Step 1: Installing Necessary Packages</h3><ol><li>Open your ASP.NET Web API project in Visual Studio.</li><li>Navigate to NuGet Package Manager.</li><li>Install the Serilog.AspNetCore package. You might also consider installing sinks such as Serilog.Sinks.Console and Serilog.Sinks.File for output to different destinations.</li></ol><pre>Serilog.AspNetCore<br>Serilog.Sinks.Console<br>Serilog.Sinks.File</pre><h3>Step 2: Configuring Serilog</h3><ol><li>In your Program.cs file, post the instantiation of WebApplicationBuilder, embed Serilog’s configuration.</li></ol><pre>using Serilog;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>// Add services to the container.<br>var logger = new LoggerConfiguration()<br>    .ReadFrom.Configuration(builder.Configuration)<br>    .Enrich.FromLogContext()<br>    .CreateLogger();<br><br>builder.Logging.ClearProviders();<br>builder.Logging.AddSerilog(logger);<br><br>// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>// ... (rest of the code)</pre><p>2. Adjusting appsettings.json: Incorporate Serilog configurations, specifying log output to both console and a daily rolling file in JSON format.</p><pre>{<br>  &quot;Logging&quot;: {<br>    &quot;LogLevel&quot;: {<br>      &quot;Default&quot;: &quot;Information&quot;,<br>      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;<br>    }<br>  },<br>  &quot;Serilog&quot;: {<br>    &quot;Using&quot;: [ &quot;Serilog.Sinks.Console&quot;, &quot;Serilog.Sinks.File&quot; ],<br>    &quot;MinimumLevel&quot;: {<br>      &quot;Default&quot;: &quot;Debug&quot;<br>    },<br>    &quot;WriteTo&quot;: [<br>      {<br>        &quot;Name&quot;: &quot;Console&quot;,<br>        &quot;Args&quot;: {<br>          &quot;outputTemplate&quot;: &quot;{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] {Message}{NewLine}{Exception}&quot;<br>        }<br>      },<br>      {<br>        &quot;Name&quot;: &quot;File&quot;,<br>        &quot;Args&quot;: {<br>          &quot;path&quot;: &quot;Logs/managementtool-.json&quot;,<br>          &quot;rollingInterval&quot;: &quot;Day&quot;,<br>          &quot;formatter&quot;: &quot;Serilog.Formatting.Json.JsonFormatter, Serilog&quot;<br>        }<br>      }<br>    ]<br>  },<br>  &quot;AllowedHosts&quot;: &quot;*&quot;<br>}</pre><p>3. To witness Serilog in action, infuse some logging within your existing code. In the Program.cs file, enrich the app.MapGet(&quot;/weatherforecast&quot;, () =&gt; segment by injecting ILogger&lt;Program&gt; and invoking the LogDebug method.</p><pre>app.MapGet(&quot;/weatherforecast&quot;, (ILogger&lt;Program&gt; logger) =&gt;<br>{<br>    logger.LogDebug(&quot;Executing `/weatherforecast`&quot;);<br>    var forecast =  Enumerable.Range(1, 5).Select(index =&gt;<br>        new WeatherForecast<br>        (<br>            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),<br>            Random.Shared.Next(-20, 55),<br>            summaries[Random.Shared.Next(summaries.Length)]<br>        ))<br>        .ToArray();<br>    return forecast;<br>})<br>.WithName(&quot;GetWeatherForecast&quot;)<br>.WithOpenApi();</pre><p>4. Execute your project, scrutinizing both the console and the designated log file. You should discern the log entry: Executing &#39;/weatherforecast&#39;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-d2EJfdQjHsz7AuCnGQskg.png" /></figure><p>Congratulations! You’ve set up your development environment and created the initial project. Stay tuned for the next part, where we will dive into User Authentication!<br>By the way, the source code for all examples can be found on my <a href="https://github.com/brenobm/ManagementTool/tree/part_1-Introduction-And-Envvironment-Setup">GitHub Repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5f40cd84a04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Growth of C#: A Look Through Its Versions]]></title>
            <link>https://medium.com/@brenobm/the-growth-of-c-a-look-through-its-versions-4bbd0b120521?source=rss-a0f3444e6d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bbd0b120521</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Breno Batista Machado]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 23:54:29 GMT</pubDate>
            <atom:updated>2023-10-20T23:54:29.308Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A tech world" src="https://cdn-images-1.medium.com/max/1024/1*Odp5Wh9dQYiM2f6zT5LmXw.png" /></figure><p>C# is a programming language made by Microsoft. Since it started in 2000, it has changed a lot to help programmers do their work easier and better. Every new version of C# brings new tools and features. In this article, we will go through all the versions of C#, from the first one to the upcoming C# 12.0. We will see what new things each version brought to help programmers.</p><h3>C# Version 1</h3><p>C# 1.0 was introduced alongside .NET Framework 1.0 and Visual Studio 2002. Here are the major features of this version:</p><ul><li><strong>Classes</strong>: Fundamental building blocks for creating objects.</li><li><strong>Structs</strong>: Value types which can contain data and behavior.</li><li><strong>Interfaces</strong>: Contracts that can be implemented by classes and structs.</li><li><strong>Events</strong>: A way for a class to provide notifications to clients of that class when some interesting thing happens to an object.</li><li><strong>Properties</strong>: Members that provide a flexible mechanism to read, write, or compute the value of a private field.</li><li><strong>Delegates</strong>: Type-safe function pointers or callbacks​.</li></ul><p>These features laid the foundation for the language and provided a strong object-oriented programming model. Additional features in C# 1.0 include Operators and expressions, Statements, and Attributes as well as higher-order functions through delegates which distinguished C# from C, C++, and Java at that time​.</p><h3>C# Version 2.0</h3><p>C# 2.0 was released in 2005 along with Visual Studio 2005, introducing several significant features that aided developers in writing more concise and type-safe code. Here are the major features introduced in C# 2.0:</p><ul><li><strong>Generics</strong>: Allowed developers to write a single class or method that could work with any data type, improving type safety and reducing code duplication.</li><li><strong>Nullable Types</strong>: Provided a way to assign null to value types, which was not possible before. This feature is crucial for database interaction where fields may have null values​.</li><li><strong>Anonymous Methods</strong>: Enabled developers to declare inline methods, making it easier to write event handlers and delegate code​.</li><li><strong>Partial Types</strong>: Allowed splitting the definition of classes, structs, or interfaces over multiple files, making it easier to manage the code in large projects​.</li><li><strong>Iterators</strong>: Simplified the process of creating custom collections by automatically generating necessary enumeration methods through the yield keyword​.</li><li><strong>Static Classes</strong>: Ensured that a class contained only static members and could not be instantiated​.</li><li><strong>Covariance and Contravariance</strong>: Provided more flexible method overriding and interface implementation, allowing for more intuitive type conversions​.</li><li><strong>Other Delegate-Related Enhancements</strong>: Introduced other enhancements related to delegates, making delegate handling more robust​.</li><li><strong>Property Accessor Accessibility</strong>: Provided more control over the accessibility of getter/setter methods in properties, allowing for a different accessibility level for a property’s getter and setter​.</li></ul><p>These features enhanced the programming capabilities, type safety, and code management in C# applications, marking a significant step forward in the evolution of the language.</p><h3>C# Version 3.0</h3><p>C# 3.0, released in 2007 alongside Visual Studio 2008, focused on data management and query capabilities, making significant strides towards seamless data manipulation within the language. Here are the major features introduced in this version:</p><ul><li><strong>Language Integrated Query (LINQ)</strong>: A set of features that extends powerful query capabilities into the C# language, allowing developers to interact with data in a more intuitive and type-safe way​.</li><li><strong>Lambda Expressions</strong>: Provided a concise, functional syntax for writing anonymous methods, allowing for writing delegates or expression tree types in a more readable and maintainable manner​.</li><li><strong>Extension Methods</strong>: Allowed developers to add new methods to existing types without modifying them, aiding in code organization and readability​.</li><li><strong>Automatic Properties</strong>: Simplified property declaration by allowing automatic backing fields, reducing boilerplate code for property declarations​​​​.</li><li><strong>Anonymous Types</strong>: Enabled developers to define a class structure inline and initialize objects with it, useful in scenarios like LINQ where type definition is not known in advance.</li><li><strong>Object and Collection Initializers</strong>: Provided a more concise syntax to initialize objects and collections, improving code readability​.</li><li><strong>Implicitly Typed Variables and Arrays</strong>: Allowed the compiler to infer the type of variables and arrays at compile-time, making the code more readable and less verbose​.</li><li><strong>Query Expressions</strong>: Provided a SQL-like syntax to perform queries on data sources, working hand-in-hand with LINQ to simplify data manipulation.</li><li><strong>Expression Trees</strong>: Enabled holding a code structure in data structures instead of executing them, often used in the construction of dynamic LINQ queries​</li></ul><p>These features significantly enhanced the ability to manage and query data within C# applications, making C# 3.0 a pivotal version in the language’s evolution towards data management and processing.</p><h3>C# Version 4.0</h3><p>C# 4.0 was released on April 11, 2010, along with the 4.0 runtime and development environment Visual Studio 2010. This version brought several new features to the language, making it more flexible and easing interoperability with other systems. Here are the major features introduced:</p><ul><li><strong>Dynamic Programming</strong>: A new keyword dynamic was introduced which signals to the compiler that the type of an object is defined at runtime. This is particularly useful for interacting with code created in dynamic languages such as Python and Ruby. The dynamic keyword allows operations to be performed on objects that get resolved at runtime, making C# more capable in handling dynamic types and operations​.</li><li><strong>Named and Optional Parameters</strong>: Optional parameters allow assigning a default value to a method parameter, eliminating the need to specify a value every time the method is called. Named parameters allow skipping parameters that have default values, and only naming the parameters that have non-default values, providing a more flexible method invocation strategy​.</li><li><strong>Covariance and Contravariance</strong>: These features allow for more flexible assignment of generic types, making it easier to manage and manipulate collections of objects in a type-safe manner​​.</li><li><strong>Better COM Interop Support</strong>: Improved support for interoperability with COM components, making it easier to work with COM APIs from C# code​​.</li></ul><p>These features significantly eased the process of working in dynamic programming scenarios, improved parameter handling in method invocation, and enhanced interoperability, making C# 4.0 a notable step forward in the language’s evolution.</p><h3>C# Version 5.0</h3><p>C# 5.0 was released on August 15, 2012, alongside .NET Framework 4.5 and Visual Studio 2012, focusing on making asynchronous programming simpler and more intuitive. Here are the major features introduced in this version:</p><ul><li><strong>Async Programming</strong>: The introduction of async and await keywords allowed developers to write asynchronous code more easily and intuitively, almost as if it were synchronous code. The async keyword is used to specify that a method is asynchronous, while the await keyword is used within an async method to await the completion of a task. This alleviated the need for callbacks (also known as continuations) to capture the results of asynchronous operations, which previously complicated code and exception handling​​.</li><li><strong>Caller Information</strong>: Caller Information attributes were introduced to help with tracing, debugging, and creating diagnostic tools. These attributes provide information about the caller of a method, including: <br>-CallerFilePathAttribute: The full path of the source file that contains the caller at compile time. <br>-CallerLineNumberAttribute: The line number in the source file at which the method is called. <br>-CallerMemberNameAttribute: The method or property name of the caller​.</li><li><strong>Enhanced Support for Covariance and Contravariance</strong>: This version also continued to improve support for covariance and contravariance, facilitating more flexible assignment of generic types.</li></ul><p>These enhancements notably simplified asynchronous programming and provided better debugging and diagnostic capabilities, making C# 5.0 a significant update for developers.</p><h3>C# Version 6.0</h3><p>C# 6.0 was released on July 20, 2015, alongside Visual Studio 2015 and .NET Framework 4.6, introducing a variety of features aimed at simplifying code and enhancing readability. Here are the major features introduced in this version:</p><ul><li><strong>Auto-Property Initializers</strong>: Allows properties to be initialized directly within their declaration, eliminating the need for a separate constructor or property setter​​.</li><li><strong>Primary Constructors</strong>: Introduces a shortcut syntax for defining constructors with parameters, although this feature was marked as ‘experimental’ and required a specific project setting to enable​​.</li><li><strong>Dictionary Initializers</strong>: Simplifies the syntax for creating and initializing dictionaries​<a href="https://www.codeproject.com/articles/874205/new-features-in-csharp">1</a>​.</li><li><strong>Declaration Expressions</strong>: Enables local variables to be declared within an expression, allowing more concise code​.</li><li><strong>Static Using Statements</strong>: Allows static members to be accessed directly without specifying the type name​​.</li><li><strong>Await in Catch and Finally blocks</strong>: Enables the use of the await keyword within catch and finally blocks, simplifying asynchronous error handling and cleanup code​.</li><li><strong>Exception Filters</strong>: Introduces a new syntax for filtering exceptions using a conditional expression​​.</li><li><strong>Null-Conditional Operator</strong>: Provides a shorthand syntax for checking for null values before accessing members or elements, reducing the amount of code required for null checks​.</li><li><strong>Enhancement to Auto Properties</strong>: C# 6 allows only getters on auto properties, which is beneficial for immutable data types​​.</li><li><strong>Using Static</strong>: Now, to use any static method, there’s no need to use the class name; developers can declare the namespace with the static keyword for that class​​.</li><li><strong>nameof Expressions</strong>: This feature allows developers to obtain the simple (unqualified) string name of a variable, type, or member​​.</li></ul><p>These features collectively reduced the amount of boilerplate code, simplified error handling, and enhanced code readability, making C# 6.0 a substantial upgrade towards writing clean and maintainable code.</p><h3>C# Version 7.0</h3><p>C# 7.0, released along with Visual Studio 2017 and .NET Framework 4.7, aimed to enhance data consumption, code simplification, and performance. The most notable features in this version are tuples and pattern matching, among others, that collectively brought a focus on data management and code simplification to the forefront. Here are the major features introduced in this version:</p><ul><li><strong>Tuples</strong>: Tuples allow methods to return multiple values, which could be of different or the same types. This feature enhances code readability and data management capabilities​​.</li><li><strong>Pattern Matching</strong>: This concept is utilized to simplify code based on conditions, aiding in creating appropriate objects based on different conditions. It significantly simplifies code that is conditional on the shape of data​​.</li><li><strong>Out Variables and Discards</strong>: The language now supports the declaration of out variables in the argument list of a method call, making the code more concise. Discards are write-only variables whose values are deliberately ignored, used when you want to discard the out variable.</li><li><strong>Digit Separators and Binary Literals</strong>: Digit separators make it easier to read large numeric literals by allowing underscores as separators. Binary literals provide a direct way to express binary numbers, improving code readability​​.</li><li><strong>Deconstruction</strong>: Deconstruction allows decomposing tuples and user-defined types into individual variables, enhancing code readability and data management​​​​.</li><li><strong>Local Functions</strong>: Local functions are function definitions that are nested inside other functions, aiding in encapsulating and organizing code.</li><li><strong>Ref Returns and Ref Locals</strong>: These features enable functions to return references to variables (instead of values) and to declare local variables that are references to other variables, respectively. This facilitates more efficient data access and manipulation.</li><li><strong>Generalized Async Return Types</strong>: This feature allows async methods to return types other than Task, Task&lt;T&gt;, and void, providing more flexibility in asynchronous programming​.</li><li><strong>Expression-Bodied Members</strong>: Expression-bodied members allow properties, constructors, and finalizers to have bodies that are expressions instead of statement blocks, simplifying the syntax for members that simply return a value​​.</li><li><strong>Throw Expressions</strong>: This feature allows the throw statement to be used as an expression, enabling more concise and expressive error handling code​​.</li><li><strong>Async Main</strong>: The Main method can now have the async modifier, allowing await expressions within it. This is particularly useful for console applications that need to call asynchronous methods​.</li></ul><p>These features collectively made C# 7.0 a strong upgrade towards simplifying syntax, improving code readability, and enhancing data management capabilities.</p><h3>C# Version 8.0</h3><p>C# 8.0, released in September 2019 alongside .NET Core 3.x and .NET Standard 2.1, brought about a number of features and improvements focusing on code simplification, null safety, and performance enhancements. Here are the major features introduced in this version:</p><ul><li><strong>Default Interface Methods</strong>: Prior to C# 8.0, interfaces could only declare method signatures without providing any implementation. This version introduced the ability to provide default implementations for methods within interfaces, without breaking existing implementations​.</li><li><strong>Nullable Reference Types</strong>: A significant step towards eliminating null reference exceptions, this feature allows developers to specify whether a reference type variable can be null or not, providing better null safety in the codebase​.</li><li><strong>Ranges and Indices</strong>: Two new operators, ^ (System.Index) and .. (System.Range), were introduced to simplify the way elements within collections are accessed. The ^ operator allows indexing from the end, while the .. operator defines a range to work on​​.</li><li><strong>Null Coalescing Assignment</strong>: The null coalescing assignment operator ??= simplifies checking for null and assigning a value if a variable is null, thereby making code more readable and concise​​.</li><li><strong>Disposable Ref Structs</strong>: While structs with the ref keyword were introduced in C# 7.2 for high-performance scenarios, C# 8.0 made it possible to dispose of these structs by defining a Dispose method, even though they can&#39;t implement interfaces like IDisposable.</li><li><strong>Static Local Functions</strong>: C# 8.0 allows the declaration of static local functions, ensuring that they do not capture any variables from the enclosing scope, which can help prevent certain classes of bugs and potentially improve performance​.</li><li><strong>Using Declarations</strong>: This feature introduces a simplified syntax for the using statement, making it easier to ensure that resources are properly disposed of, and reducing nesting and improving code readability​.</li><li><strong>Readonly Members</strong>: C# 8.0 allowed for individual members of a struct to be declared as readonly, whereas in previous versions, this was only possible at the whole structure level​​.</li><li><strong>Asynchronous Streams</strong>: This version of C# also introduced asynchronous streams, enhancing support for asynchronous programming patterns​.</li><li><strong>Enhancements to Pattern Matching</strong>: C# 8.0 included improvements to pattern matching, one of the features introduced in C# 7.0, to simplify code based on conditions​​.</li><li><strong>Enhanced Interpolation</strong>: In this version, the interpolated verbatim strings, which are prefixed with $ and @, can be written in any order: $@ or @$, making string interpolation more flexible.</li><li><strong>Switch Expressions</strong>: This feature introduces a new form of the switch statement that is more concise and can be used in more scenarios​.</li></ul><p>These features collectively made C# 8.0 a substantial upgrade, focusing on code readability, null safety, and performance enhancements, among other improvements.</p><h3>C# Version 9.0</h3><p>C# 9.0 was officially released in November 2020, alongside .NET 5. This version focused on supporting native cloud applications, modern software engineering practices, and more readable, concise code, with many of its features reliant on new features in the .NET 5.0 libraries and updates to the .NET Common Language Runtime (CLR) that are part of .NET 5.0​​. Here are the major features introduced in this version:</p><ul><li><strong>Records</strong>: Provides a simplified way to define a reference type with immutable properties using the record keyword, aiding in encapsulating data​​.</li><li><strong>Init Only Setters</strong>: Allows properties to be set at the time of object initialization, promoting immutability​​.</li><li><strong>Top-level Statements</strong>: Simplifies program entry point declaration by removing the need for a Main method in a class or struct, thus reducing boilerplate code​​.</li><li><strong>Pattern Matching Enhancements</strong>: Introduces new pattern matching features to simplify code based on conditions​​.</li><li><strong>Performance and Interop Enhancements</strong>: Includes features like native sized integers and function pointers to improve performance and interoperability​​.</li><li><strong>Target-typed New Expressions</strong>: Allows the type of new expressions to be inferred, reducing verbosity​​.</li><li><strong>Static Anonymous Functions</strong>: Introduces static lambdas or anonymous methods, which do not capture the surrounding scope, thus potentially improving performance​​.</li><li><strong>Target-typed Conditional Expressions</strong>: Enhances type inference in conditional expressions, reducing the amount of required type annotations​.</li><li><strong>Covariant Return Types</strong>: Allows overriding methods to return more derived types than the methods they override, improving type safety and expressiveness​.</li><li><strong>Extension </strong><strong>GetEnumerator Support for </strong><strong>foreach Loops</strong>: Extends support for custom collection types in foreach loops​.</li><li><strong>Lambda Discard Parameters</strong>: Simplifies lambda expressions when certain parameters are not used​​.</li><li><strong>Attributes on Local Functions</strong>: Allows attributes to be applied to local functions, providing more meta-information about the function’s behavior​​.</li><li><strong>Support for Code Generators</strong>: Introduces a way to generate code at compile-time, allowing for metaprogramming scenarios​.</li><li><strong>Module Initializers</strong>: Provides a way to specify methods that are run when a module is initialized​.</li><li><strong>New Features for Partial Methods</strong>: Extends the partial method feature with accessibility modifiers and return values​.</li><li><strong>Warning Wave 5</strong>: Introduces a new set of compiler warnings to assist in identifying potential issues in code​​.</li></ul><p>These features collectively work towards simplifying code, promoting immutability, enhancing performance, and improving interop scenarios.</p><h3>C# Version 10.0</h3><p>C# 10.0 was released in November 2021 alongside Visual Studio 2022 and .NET 6, with a primary goal of making it easier and more convenient to work with, especially in terms of simplifying code and enhancing developer productivity. Some of the principal features and enhancements introduced in this version are as follows:</p><ul><li><strong>Record Structs</strong>: Value type records can now be declared using the record struct or readonly record struct declarations, distinguishing a record as a reference type with the record class declaration​.</li><li><strong>Improvements of Structure Types</strong>: Features such as the ability to declare an instance parameterless constructor in a structure type and initialize an instance field or property at its declaration were introduced. Additionally, a left-hand operand of the with expression can be of any structure type or an anonymous (reference) type​.</li><li><strong>Interpolated String Handlers</strong>: This feature allows the creation of a type that builds the resulting string from an interpolated string expression, which is used in many APIs in the .NET libraries​​.</li><li><strong>Global Using Directives</strong>: By adding the global modifier to any using directive, it instructs the compiler that the directive applies to all source files in the compilation, typically all source files in a project​​.</li><li><strong>File-scoped Namespace Declaration</strong>: A new form of the namespace declaration was introduced to declare that all declarations that follow are members of the declared namespace, saving both horizontal and vertical space for namespace declarations​​.</li><li><strong>Extended Property Patterns</strong>: Nested properties or fields within a property pattern can now be referenced, making pattern matching more flexible and powerful​.</li><li><strong>Improvements on Lambda Expressions</strong>: Several improvements were made to how lambda expressions are handled, such as allowing lambda expressions to have a natural type, declaring a return type when the compiler can’t infer it, and applying attributes to lambda expressions​​.</li><li><strong>Allow Const Interpolated Strings</strong>: const strings can now be initialized using string interpolation if all the placeholders are themselves constant strings, enhancing the readability of constant strings​.</li><li><strong>Record Types Can Seal ToString</strong>: The sealed modifier can now be added when overriding ToString in a record type, preventing the compiler from synthesizing a ToString method for any derived record types​​.</li><li><strong>Allow Both Assignment and Declaration in the Same Deconstruction</strong>: This feature removes a restriction from earlier versions of C# where a deconstruction could either assign all values to existing variables or initialize newly declared variables, but not both​​.</li><li><strong>Improved Definite Assignment</strong>: Many scenarios where definite assignment and null-state analysis produced false positive warnings have been addressed, enhancing the definite assignment analysis in the language​​.</li><li><strong>Allow AsyncMethodBuilder Attribute on Methods, CallerArgumentExpression Attribute, Enhanced #line Pragma, and Warning Wave 6</strong>: These features and enhancements provide more capabilities and tools for developers to write clean, efficient, and error-free code​​.</li></ul><p>Other notable mentions include Constant Interpolated Strings, Lambda Improvements, and Null Parameter Checking​.</p><p>The features introduced in C# 10.0 collectively work towards simplifying the syntax, promoting code readability and maintainability, and providing more expressive power to developers. With the support on .NET 6, these features are expected to significantly benefit developers working on modern software projects, especially those targeting cloud-native and microservices architectures.</p><h3>C# Version 11.0</h3><p>C# 11.0, released alongside .NET 7 and Visual Studio 2022, continued the journey of making the language more expressive, flexible, and friendly for developers. The focus was on enhancing string handling, pattern matching, and type safety which are crucial for modern software development. The introduction of features like raw string literals, generic attributes, and required members aimed at reducing boilerplate code and improving the developer experience. Here are the major features introduced in this version:</p><ul><li><strong>Raw String Literals</strong>: This feature allows developers to write strings as they are, without the need to escape special characters. This is particularly useful when working with file paths or regular expressions, making the code more readable and maintainable.</li><li><strong>Generic Math Support</strong>: Provides enhanced support for performing mathematical operations in a type-safe manner. This feature is beneficial when working with different numeric types, allowing for more accurate and efficient computations.</li><li><strong>Generic Attributes</strong>: Introduced the ability to use generic types within attribute declarations. This enhances the flexibility and reusability of custom attributes across different types and scenarios.</li><li><strong>UTF-8 String Literals</strong>: Supports UTF-8 encoding in string literals, facilitating the handling of text in different character encodings which is crucial for globalization and localization of applications.</li><li><strong>Newlines in String Interpolation Expressions</strong>: Allows the inclusion of newlines within string interpolation expressions, making it easier to format multiline strings in a readable and intuitive manner.</li><li><strong>List Patterns</strong>: Enables pattern matching with lists, allowing developers to destructure and match on elements within lists in a concise and expressive manner.</li><li><strong>File-local Types</strong>: This feature allows for the definition of types local to a file, promoting better organization and encapsulation of code.</li><li><strong>Required Members</strong>: Introduces a new required modifier for fields and properties to ensure they are initialized by constructors or callers, thereby promoting better code safety and reducing the possibility of null reference exceptions.</li><li><strong>Auto-default Structs</strong>: Provides automatic provision of default values for structs, reducing boilerplate code and ensuring structs are always in a valid state when instantiated.</li><li><strong>Pattern Match</strong>: Enhancements in pattern matching capabilities allow for more expressive and concise code when working with different types and conditions.</li><li><strong>Span&lt;char&gt; on a Constant String</strong>: Allows the use of Span&lt;char&gt; on constant strings, facilitating efficient manipulation and examination of string data without allocations.</li><li><strong>Extended </strong><strong>nameof Scope</strong>: Extends the scope of the nameof operator, improving code readability and maintainability especially in scenarios involving reflection or expression trees.</li><li><strong>Numeric </strong><strong>IntPtr and Scoped </strong><strong>ref</strong>: Supports numeric IntPtr and scoped ref fields, providing more fine-grained control over memory and references.</li><li><strong>Static Abstract and Static Virtual Members in Interfaces</strong>: Introduces new member types in interfaces, allowing for more expressive and flexible interface definitions.</li><li><strong>Relaxed Right-shift Requirements and Unsigned Right-shift Operator</strong>: Enhanced shift operations with relaxed requirements and the introduction of an unsigned right-shift operator, providing more options for bitwise operations.</li></ul><p>These features collectively enrich the expressiveness, safety, and flexibility of C# code, making version 11 a substantial upgrade, especially in the areas of string handling, pattern matching, and type safety.</p><h3>C# Version 12.0</h3><p>C# 12.0, anticipated to be released with .NET 8 and Visual Studio 2023, aims at further simplifying the syntax and enhancing the conciseness and readability of the code. With a keen eye on reducing the ceremony in code writing and embracing the principle of “less is more”, this version introduces features like primary constructors, inline arrays, and collection expressions. It also experiments with advanced concepts like interceptors, showcasing the language’s continuous evolution towards modern programming paradigms. Here are the major features introduced in this version:</p><ul><li><strong>Primary Constructors</strong>: Simplifies constructor syntax for classes and structs by allowing parameter declarations directly within the class or struct declaration. This helps in reducing boilerplate code and making the code more concise.</li><li><strong>Optional Parameters in Lambda Expressions</strong>: Enables the use of optional parameters with default values in lambda expressions. This feature enhances the flexibility of lambda expressions, making them more powerful and easier to use in various scenarios.</li><li><strong>Alias Any Type</strong>: This feature extends aliasing to any type using the using directive. It enhances code readability and maintainability, especially in projects with complex type hierarchies or external dependencies.</li><li><strong>Inline Arrays</strong>: Allows the declaration of fixed-size arrays within structs without having to specify a separate array type. This is beneficial in high-performance scenarios where minimizing heap allocations is crucial.</li><li><strong>Collection Expressions</strong>: Introduces a terse syntax for creating collections, providing a uniform and efficient way to initialize collections with a set of values.</li><li><strong>Interceptors (Preview Feature)</strong>: An experimental feature introduced for intercepting method or property calls. It’s in preview mode and may provide a powerful mechanism for aspect-oriented programming, diagnostics, and other cross-cutting concerns once fully realized.</li></ul><p>These features collectively aim at enhancing code conciseness, flexibility, and performance, making C# 12 an exciting upgrade for developers. Each feature brings a set of benefits that streamline the development process, reducing the amount of code required to achieve common tasks, and providing powerful new tools for handling complex programming challenges.</p><p>We can observe the evolution of C# from version 1.0.</p><pre>using System;<br>using System.Collections;<br><br>public class Animal<br>{<br>    public string Name { get; set; }<br>    public virtual void Speak()<br>    {<br>        Console.WriteLine(&quot;Some generic animal sound&quot;);<br>    }<br>}<br><br>public class Dog : Animal<br>{<br>    public override void Speak()<br>    {<br>        Console.WriteLine(&quot;Woof!&quot;);<br>    }<br>}<br><br>public class Cat : Animal<br>{<br>    public override void Speak()<br>    {<br>        Console.WriteLine(&quot;Meow!&quot;);<br>    }<br>}<br><br>public class Program<br>{<br>    public static void Main(string[] args)<br>    {<br>        ArrayList animals = new ArrayList();<br>        animals.Add(new Dog { Name = &quot;Buddy&quot; });<br>        animals.Add(new Cat { Name = &quot;Kitty&quot; });<br><br>        foreach (Animal animal in animals)<br>        {<br>            Console.WriteLine(animal.Name + &quot; says:&quot;);<br>            animal.Speak();<br>        }<br>    }<br>}</pre><p>To version 12, while maintaining the same core semantics between both versions.</p><pre>using System;<br>using System.Collections.Generic;<br><br>public abstract record Animal(string Name)<br>{<br>    public abstract void Speak();<br>}<br><br>public record Dog(string Name) : Animal(Name)<br>{<br>    public override void Speak() =&gt; Console.WriteLine(&quot;Woof!&quot;);<br>}<br><br>public record Cat(string Name) : Animal(Name)<br>{<br>    public override void Speak() =&gt; Console.WriteLine(&quot;Meow!&quot;);<br>}<br><br>public class Program<br>{<br>    public static void Main(string[] args)<br>    {<br>        List&lt;Animal&gt; animals = new() { new Dog(&quot;Buddy&quot;), new Cat(&quot;Kitty&quot;) };<br><br>        foreach (var animal in animals)<br>        {<br>            Console.WriteLine($&quot;{animal.Name} says:&quot;);<br>            animal.Speak();<br>        }<br>    }<br>}</pre><p>Can you enumerate all the features used in the second code snippet, and mention which version of C# they were introduced in?</p><h3>Conclusion</h3><p>Going through all the versions of C# shows how much it has improved over time. Microsoft keeps adding new things to help programmers do more with less effort. The next version, C# 12.0, will bring even more helpful tools. It shows that C# will keep being an important language for many programmers. With every new version, C# becomes better and helps programmers solve today’s challenges.</p><h3>References used on this Article</h3><ul><li><a href="https://devblogs.microsoft.com/dotnet/new-features-in-c-7-0/#:~:text=C,other%20features%20big%20and%20small">.NET Blog: New Features in C# 7.0</a></li><li><a href="https://www.bytehide.com/csharp-12-features">ByteHide: C# 12 is Coming! Features that will Blow your Mind​​.</a></li><li><a href="https://www.c-sharpcorner.com/blogs/c-sharp-10-features#:~:text=C,Lambda%20Improvements%20Null%20Parameter%20Checking">C# Corner: C# 10 Features</a></li><li><a href="https://www.c-sharpcorner.com/UploadFile/kalisk/C-Sharp-6-features-overview/#:~:text=This%20article%20outlines%20the%20new,only%20getters%20on%20auto%20properties">C# Corner: C# 6 Features Overview</a></li><li><a href="https://www.c-sharpcorner.com/article/c-sharp-8-new-exciting-features/">C# Corner: C# 8.0 — New Features</a></li><li><a href="https://www.c-sharpcorner.com/learn/learn-c-sharp-80#:~:text=C,only%20struct%20members">C# Corner: Learn C# 8.0</a></li><li><a href="https://www.c-sharpcorner.com/UploadFile/8ef97c/full-C-Sharp-6-0-in-single-article-on-visual-studio-2015-preview/#:~:text=List%20of%20All%20New%20Features,nameof%20Expression">C# Corner: List of All New Features in C# 6.0: Part 1</a></li><li><a href="https://www.c-sharpcorner.com/uploadfile/john_charles/new-features-of-C-Sharp-4-0/">C# Corner: New features of C# 4.0</a></li><li><a href="https://www.c-sharpcorner.com/article/c-sharp-versions/#:~:text=The%20major%20features%20of%20C,small%20enhancements%20to%20the%20language">C# Corner: C# Versions</a></li><li><a href="https://www.c-sharpcorner.com/article/new-features-in-C-Sharp-2-0/#:~:text=In%20this%20article,%20I%20will,safe">C# Corner: New features in C# 2.0</a></li><li><a href="https://www.c-sharpcorner.com/article/whats-new-in-C-sharp-11">C# Corner: What’s New In C# 11?​​.</a></li><li><a href="https://www.codemag.com/Article/2010032/Introducing-C">Code Magazine: Introducing C# 9.0</a></li><li><a href="https://www.codemag.com/article/0911071#:~:text=Visual%20C,work%20and%20provide%20suggestions%20of">Code Magazine: What’s New in Visual C# 4.0?</a></li><li><a href="https://www.codeproject.com/articles/874205/new-features-in-csharp">CodeProject: New Features in C# 6.0</a></li><li><a href="https://dev.to/jai00271/c-features-from-5-0-6-0-and-7-0-2ldn#:~:text=C,static%20keyword%20for%20that%20class">DEV Community: C# features from 5.0, 6.0 and 7.0</a></li><li><a href="https://devtut.github.io/csharp/c-7-0-features.html">DevTut: C# | C# 7.0 Features</a></li><li><a href="https://dotnettutorials.net/lesson/csharp-7-new-features/">Dot Net Tutorials: C# 7 New Features with Examples</a></li><li><a href="https://www.dottutorials.net/csharp-11-features">Dot Tutorials: What’s New in C# 11​.</a></li><li><a href="https://www.dotnettricks.com/learn/csharp/new-features-added-to-csharp-50#:~:text=22%20aug,Async%20Feature%20%28Asynchronous%20Methods">DotNet Tricks: New features added to C# 5.0</a></li><li><a href="https://dotnetcrunch.in/csharp-version-history-features/">DotNetCrunch: C# Version History: Detailed List of C# Features From Version 1 to 10</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Odp5Wh9dQYiM2f6zT5LmXw.png" /></figure><ul><li><a href="https://dotnetpattern.com/csharp-versions-features#:~:text=C,type%20Named%20and%20optional%20arguments">DotNetPattern.com: C# Versions and Features</a></li><li><a href="https://functionalprogrammingcsharp.com/new-features#:~:text=C,public%20struct%20Math">Functional Programming in C#: What’s new in C# 8.0 to C# 10.0</a></li><li><a href="https://www.geeksforgeeks.org/c-sharp-version-history/">GeeksforGeeks: C# | Version History</a></li><li><a href="https://github.com/dotnet/csharplang/blob/main/Language-Version-History.md">GitHub: Features Added in C# Language Versions​​.</a></li><li><a href="https://www.howtogeek.com/devops/whats-new-in-c-10/#:~:text=File,more%20convenient%20to%20work%20with">How-To Geek: What’s New In C# 10?</a></li><li><a href="https://www.ifourtechnolab.com/blog/everything-you-need-to-know-about-c-version-8-0#:~:text=After%20a%20long%20period%20of,streams%20&amp;%20Range%20and%20indices">iFour: Everything You Need to Know About C# Version 8.0</a></li><li><a href="https://devblogs.microsoft.com/dotnet/csharp-11-preview-august-update">Microsoft Dev Blogs: C# 11 Preview August Update​​.</a></li><li><a href="https://devblogs.microsoft.com/dotnet/csharp-12-preview-features">Microsoft Dev Blogs: Check out new C# 12 preview features!​​.</a></li><li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10">Microsoft Learn: What’s new in C# 10 </a>.</li><li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9">Microsoft Learn: What’s new in C# 9.0 </a>.</li><li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11">Microsoft Learn: What’s new in C# 11​.</a></li><li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12">Microsoft Learn: What’s new in C# 12​​.</a></li><li><a href="https://stackoverflow.com/questions/3174942/list-of-new-features-in-c-sharp-2-0-3-0-and-4-0#:~:text=The%20major%20features%20of%20C,related%20enhancements%20and%20iterator%20blocks">Stack Overflow: C# 3.0 — List of new features in C# 2.0, 3.0 and 4.0</a></li><li><a href="https://en.wikipedia.org/wiki/C_Sharp_4.0#:~:text=C,1">Wikipedia: C Sharp 4.0</a></li><li><a href="https://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29#:~:text=Some%20notable%20features%20of%20C,9:">Wikipedia: C Sharp (programming language)</a></li><li><a href="https://en.wikipedia.org/wiki/C_Sharp_3.0#:~:text=1C,integrated%20query%29%201.2Object%20initializers">Wikipedia: C Sharp 3.0</a></li><li><a href="https://zetcode.com/lang/csharp/csharp3/#:~:text=The%20C,expressions%20Lambda%20expressions%20Expression%20trees">ZetCode: C# 3.0 features</a></li><li><a href="https://zetcode.com/lang/csharp/csharp4/#:~:text=The%20C,a%20new%20type%20dynamic">ZetCode: C# 4.0 new features</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bbd0b120521" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>