Admin

Meet Dobariya

Experienced .NET developer proficient in various technologies with a passion for continuous learning. Over 2 years of hands-on experience in software development across multiple domains. Enthusiastic about technology and adept at adapting to new challenges.

Posts by this author

Serverless computing using Azure Function
Jul 17, 2024

Serverless computing is a widely adopted approach and an extension of the cloud computing model where customers can focus solely on building logic, with the server infrastructure being completely managed by third-party cloud service providers. In Microsoft Azure, serverless computing can be implemented in various ways, one of which is by using Azure Functions. In this blog, we will discuss how to use Azure Functions for serverless computing. Firstly, let us understand the following terms. What Is Serverless Computing? Serverless computing, also known as the Function-as-a-Service (FAAS) approach to building software applications, eliminates the need to manage the server hardware and software by the consumer and be taken care of by third-party vendors. What Are Azure Functions? Azure functions are the serverless solution that provides all the necessary resources to carry out the tasks with minimal lines of code, infrastructure, and cost. The Azure function are a combination of code and event allowing us to write the code in any language. A Step-by-Step Approach For Creating An Azure Function Go to the Azure portal, search for Function App, and select Function App. Create a new Function App and fill in the details accordingly. Basic tab You can select the Runtime stack and version based on your requirements. Here, I am selecting .NET with version 8 and the operating system Windows. Storage You may leave the default values or configure them according to your project requirements. The default values are configured as. Storage account: You may use the existing storage account or create a new account to store your function app. Monitoring Enable the Application insights to monitor the activity. Deployment tab To enable Continuous Integration and Continuous Deployment (CI/CD), you may connect your function app to a repository by authorizing it to GitHub. These are the important things to focus on while creating your function app, you may leave the remaining details as default or customize them according to your requirements. Once you finish configuring your app, you can click the “create” button at the bottom of the page.Now your app will start the process of deployment. Once deployment is done click on go to the resource tab and you will see your function app was created successfully. Now we need to create a function in our function app. As you can see We have various options to choose Visual Studio, VS code, and other editors or CLI. Choose an environment to create your function. I’ve chosen Visual Studio to create my function app. Create an Azure Functions with Visual Studio From the Visual Studio menu, select File > New > Project. In Create a new project, enter functions in the search box, choose the Azure Functions template, and then select Next. Here you can select the function based on your requirements. Here I am selecting Timer trigger function. Then click on the Create button to create a project. You will see that the default Timer trigger function is created. Here I have created one more function called "HTTPTrigger". Here, you can see two JSON files: host.json and local.settings.json. The local.settings.json file stores app settings and settings used by local development tools. Settings in the local.settings.json file are used only when you're running your project locally. When you publish your project to Azure, be sure to also add any required settings to the app settings for the function app. Publish to Azure Use the following steps to publish your project to a function app in Azure. In Solution Explorer, right-click the project and select Publish. In Target, select Azure then Next. Select Azure Function App (Windows) for the Specific target, which creates a function app that runs on Windows, and then select Next. In the Functions instance, You have to select the function that you created on the Azure portal and then click the finish button.  You can see that the publish profile has been added. Now, click on the Publish button to publish the function to Azure. Once the function is published, go to the Azure portal and search for Application Insights. You can find the Application Insights instance with the same name as the function. On the LHS, go to the Transaction search tab under Investigate and click on See all data in the last 24 hours. In the logs, you can see that your function is working properly. Conclusion In a nutshell, Azure functions provide a very precise environment for developers allowing them to more focus on coding rather than then managing infrastructure. This feature plays a key role in building scalable and responsive applications with low cost.

Comparison between Minimal APIs and Controllers
Jun 17, 2024

Introduction  In the ever-evolving landscape of web development, simplicity is key. Enter Minimal APIs in ASP.NET Core, a lightweight and streamlined approach to building web applications. In this detailed blog, we'll explore the concept of Minimal APIs, understand why they matter, and walk through their implementation in ASP.NET Core.    When to Use Minimal APIs?  Minimal APIs are well-suited for small to medium-sized projects, microservices, or scenarios where a lightweight and focused API is sufficient. They shine in cases where rapid development and minimal ceremony are top priorities.  You can find in this blog <link> how to create minimal api.  I am directly showing the comparison between MinimalAPI and controller.    Controllers: Structured and Versatile  Controllers, deeply rooted in the MVC pattern, have been a cornerstone of ASP.NET API development for years. They provide a structured way to organize endpoints, models, and business logic within dedicated controller classes.  Let's consider an example using Microsoft.AspNetCore.Mvc; namespace MinimalAPI.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } } } Advantages of Controllers in Action  Structure and Organization: Controllers offer a clear structure, separating concerns and enhancing maintainability.  Flexibility: They enable custom routes, complex request handling, and support various HTTP verbs.  Testing: Controllers facilitate unit testing of individual actions, promoting a test-driven approach   Minimal APIs: Concise and Swift  With the advent of .NET 6, Minimal APIs emerged as a lightweight alternative, aiming to minimize boilerplate code and simplify API creation.  Here's an example showcasing Minimal APIs.  using MinimalAPI; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); app.MapGet("/GetWeatherForecast", () => { var rng = new Random(); var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; var weatherForecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index).Date, TemperatureC = rng.Next(-20, 55), Summary = summaries[rng.Next(summaries.Length)] }).ToArray(); return Results.Ok(weatherForecasts); }); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); Advantages of Minimal APIs in Focus  Simplicity: Minimal APIs drastically reduce code complexity, ideal for smaller projects or rapid prototyping.  Ease of Use: They enable quick API creation with fewer dependencies, accelerating development cycles.  Potential Performance Boost: The reduced overhead might lead to improved performance, especially in smaller applications.    What you choose between MinimalAPI and Controller?  Choosing between Controllers and Minimal APIs hinges on various factors.  Project Scale: Controllers offer better organization and structure for larger projects with intricate architectures.  Development Speed: Minimal APIs shine when speed is crucial, suitable for rapid prototyping or smaller projects.  Team Expertise: Consider your team's familiarity with MVC patterns versus readiness to adopt Minimal APIs.    Conclusion  The decision between Controllers and Minimal APIs for .NET APIs isn't about one being superior to the other. Rather, it's about aligning the choice with the project's specific needs and constraints. Controllers offer robustness and versatility, perfect for larger, complex projects. On the other hand, Minimal APIs prioritize simplicity and rapid development, ideal for smaller, more straightforward endeavours. 

Role based Authorization in ASP .NET core
Jun 14, 2024

What is Authorization?  Authorization verifies whether a user has permission to use specific applications or services. While authentication and authorization are distinct processes, authentication must precede authorization, ensuring the user's identity is confirmed before determining their access rights.    When logging into a system, a user must provide credentials like a username and password to authenticate. Next, the authorization process grants rights. For example, an administrative user can create a document library to add, edit, and delete documents, while a non-administrative user can only read documents in the library.  Types of Authorization:  Simple Authorization  Role-Based Authorization  Claim-Based Authorization  Policy-Based Authorization  I have implemented an example of role-based authorization in .NET. Step 1: Create one new MVC Web Application with the Authentication type “Individual Account”.  Step 2: Register Identity with DefaultTokenProvider in the program.cs file. builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = false) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); For better understanding, I have added one page to add a new role.  Create a new method in the controller and add the following code. [HttpGet] public IActionResult Admin() { return View(); } Create a new model Role.cs.   namespace Authorization.Models { public class Role { public string RoleName { get; set; } } } Create html page for add role.  @model Role @{ ViewData["Title"] = "Admin"; } <h1>Admin</h1> <div class="row"> <div class="col-md-12"> <form method="post" action="@Url.Action("Admin","Home")"> <div class="form-group"> <label>Role Name</label> <input type="text" class="form-control" style="width:30%;" asp-for="RoleName" placeholder="Role name" required> </div> <br /> <button class="btn btn-success" type="submit">Add</button> </form> </div> </div> I have created a simple page, You can modify the page as per your requirements.  Add a new method in the controller and add the following code. And declare RoleManager<IdentityRole> and inject in the constructor. private readonly RoleManager<IdentityRole> _roleManager; public HomeController(RoleManager<IdentityRole> roleManager) { _roleManager = roleManager; } [HttpPost] public async Task<IActionResult> Admin(Role role) { var result = _roleManager.RoleExistsAsync(role.RoleName).Result; if (!result) { await _roleManager.CreateAsync(new IdentityRole(role.RoleName)); } return RedirectToAction("Admin"); } Set a new tab in _Layout.cshtml file to redirect to the Add role page.  <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Admin">Add new role</a> </li> Run the project and you will see the output. Here, You can add a new role.  Add a new field in register.cshtml using the following code to assign a role to the user.  <div class="form-floating mb-3"> <select asp-for="Input.Role" class="form-control" aria-required="true"> <option value="">Select role</option> @foreach (var item in Model.RoleList) { <option value="@item.Name">@item.Name</option> } </select> <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span> </div> To get the list of roles you can add the following code in your register.cshtml.cs file. And Add  RoleList = _roleManager.Roles in OnPostAsync method also. public IQueryable<IdentityRole> RoleList { get; set; } public async Task OnGetAsync(string returnUrl = null) { ReturnUrl = returnUrl; RoleList = _roleManager.Roles; ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); } Run the project and see the output. Now, Assign the role to the user, and for that add the following code in OnPostAsync after the user is created. await _userManager.AddToRoleAsync(user, Input.Role); Full code of register.cshtml.cs file. using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; using System.ComponentModel.DataAnnotations; using System.Text; namespace Authorization.Areas.Identity.Pages.Account { public class RegisterModel : PageModel { private readonly SignInManager<IdentityUser> _signInManager; private readonly UserManager<IdentityUser> _userManager; private readonly RoleManager<IdentityRole> _roleManager; private readonly IUserStore<IdentityUser> _userStore; private readonly IUserEmailStore<IdentityUser> _emailStore; private readonly ILogger<RegisterModel> _logger; //private readonly IEmailSender _emailSender; public RegisterModel( UserManager<IdentityUser> userManager, IUserStore<IdentityUser> userStore, SignInManager<IdentityUser> signInManager, ILogger<RegisterModel> logger, RoleManager<IdentityRole> roleManager ) { _userManager = userManager; _userStore = userStore; _emailStore = GetEmailStore(); _signInManager = signInManager; _roleManager = roleManager; _logger = logger; } [BindProperty] public InputModel Input { get; set; } public IQueryable<IdentityRole> RoleList { get; set; } public string ReturnUrl { get; set; } public IList<AuthenticationScheme> ExternalLogins { get; set; } public class InputModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [Display(Name = "Role")] public string Role { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public async Task OnGetAsync(string returnUrl = null) { ReturnUrl = returnUrl; RoleList = _roleManager.Roles; ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl ??= Url.Content("~/"); RoleList = _roleManager.Roles; ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = CreateUser(); await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None); await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None); var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); await _userManager.AddToRoleAsync(user, Input.Role); var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }); } else { await _signInManager.SignInAsync(user, isPersistent: false); return LocalRedirect(returnUrl); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return Page(); } private IdentityUser CreateUser() { try { return Activator.CreateInstance<IdentityUser>(); } catch { throw new InvalidOperationException($"Can't create an instance of '{nameof(IdentityUser)}'. " + $"Ensure that '{nameof(IdentityUser)}' is not an abstract class and has a parameterless constructor, or alternatively " + $"override the register page in /Areas/Identity/Pages/Account/Register.cshtml"); } } private IUserEmailStore<IdentityUser> GetEmailStore() { if (!_userManager.SupportsUserEmail) { throw new NotSupportedException("The default UI requires a user store with email support."); } return (IUserEmailStore<IdentityUser>)_userStore; } } } Now, register one new user and assign a role to them. For example, I have created one user and assign “Admin” to them. I have added two new methods in the controller and added a default view for that.  [Authorize(Roles = "User")] public IActionResult UserRoleCheck() { return View(); } [Authorize(Roles = "Admin")] public IActionResult AdminRoleCheck() { return View(); } I have set the Authorize attribute with the role name on both authorization methods. Now, I am running the project and clicking on Admin Role, It will open the page of admin because the logged user role and method role both are the same.  If I click on User Role, It will give an Access denied error. Because logged user role and method role both are different. Here, I am using by default access denied page of identity. You can use custom page also, Just set this path to program.cs file. builder.Services.ConfigureApplicationCookie(options => { options.AccessDeniedPath = "/Identity/Account/AccessDenied"; // Customize this path as per your application's structure }); Using this way you will implement the role-based authorization in your application. Conclusion  By properly implementing authorization in your applications, you can ensure that resources and sensitive information are accessible only to authorized users. Remember to choose the appropriate authorization technique based on your application’s requirements and complexity.

How to create MinimalAPI in .NET
May 27, 2024

What is MinimalAPI?  Minimal APIs are a simplified way of building web APIs in ASP.NET Core. They are designed for scenarios where you need a quick and minimalistic approach to expose endpoints without the overhead of a full-fledged MVC application.    Why Minimal APIs?  Efficiency: Write less, do more. A mantra for the modern developer.  Performance: They’re lean, mean, and fast, perfect for high-performance scenarios.  Ease of Use: New to .NET? No problem! Minimal APIs are accessible and easy to grasp.  Flexibility: Simplicity doesn’t mean limited. From microservices to large-scale applications, they’ve got you covered.    How Minimal APIs Work?  Minimal APIs leverage the WebApplication class to define routes and handle HTTP requests. They rely on a functional approach, allowing developers to define endpoints using lambda expressions.    Limitations of Minimal API  No support for filters: For example, no support for IAsyncAuthorizationFilter, IAsyncActionFilter, IAsyncExceptionFilter, IAsyncResultFilter, and IAsyncResourceFilter.  No support for model binding, i.e. IModelBinderProvider, IModelBinder. Support can be added with a custom binding shim.  No support for binding from forms. This includes binding IFormFile. We plan to add support for IFormFile in the future.  No built-in support for validation, i.e. IModelValidator  No support for application parts or the application model. There's no way to apply or build your own conventions.  No built-in view rendering support. We recommend using Razor Pages for rendering views.  No support for JsonPatch  No support for OData    How to create a Minimal API?  Creating a Minimal API closely mirrors the traditional approach, so you should encounter no significant challenges. It is a straightforward procedure that can be accomplished in just a few easy steps.  Let's get started:  Step 1:   Open Visual Studio and select the ASP.NET Core Web API.  Provide a preferred name for your project and select the location where you wish to store it.  For the final step, choose the targeted framework, ensure that the "Configure for HTTPS" and "Enable OpenAPI support" checkboxes are checked, and, most importantly, leave the checkbox "Use controllers (uncheck to use Minimal API)" unchecked. Then, click the "Create" button.  Step 2:  Create one class with two fields and create one list class with some static values.  namespace MinimalAPI { public class Student { public int Id { get; init; } public string Name { get; set; } } public static class StudentList { public static List<Student> student = new List<Student>() { new Student() { Id = 1, Name = "Test1", }, new Student() { Id = 2, Name = "Test2", }, new Student() { Id = 3, Name = "Test3", } }; } } Now add register new endpoint in Program.cs file.  app.MapGet("GetAllStudent", () => StudentList.student); Run the project and see the output.  I have added Create, Update and Delete student endpoint. See the full code below.  using MinimalAPI; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // GetAll app.MapGet("GetAllStudent", () => StudentList.student); // GetById app.MapGet("GetByStudentId/{id}", (int id) => StudentList.student.FirstOrDefault(user => user.Id == id)); // Create app.MapPost("CreateStudent", (Student student) => StudentList.student.Add(student)); // Update app.MapPut("UpdateStudent/{id}", (int id, Student student) => { Student currentStudent = StudentList.student.FirstOrDefault(user => user.Id == id); currentStudent.Name = student.Name; }); // Delete app.MapDelete("DeleteStudent/{id}", (int id) => { var student = StudentList.student.FirstOrDefault(user => user.Id == id); StudentList.student.Remove(student!); }); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); Run the code and see the output. Conclusion:  Minimal APIs in ASP.NET Core, introduced in .NET 6, offer a simplified and concise approach to building lightweight HTTP services, reducing boilerplate and emphasizing convention-based routing. While ideal for rapid development of small to medium-sized APIs, they lack advanced features found in traditional ASP.NET Core applications and may not be suitable for complex scenarios. 

ASP .NET Core Two-Factor Authentication
Feb 21, 2024

What is Authentication?  Authentication is the process of validating the identity of a user or system attempting to access a protected resource. In C# programming, authentication is commonly implemented in various scenarios, including web applications, desktop applications, and services.  Types of Authentications  Basic Authentication  Password-based Authentication  Multi-Factor Authentication  Token-based Authentication  Let’s understand authentication with example. Here I am taking one example of MFA (Two-factor authentication).  Step 1: Create the MVC Web Application  Open Visual Studio and select File >> New >> Project. After selecting the project, a “New Project” dialog will open. Select ASP.NET Core web app (Model-View-Controller) and press Next and enter project name and click Next.      Choose 'Individual Account' as the authentication type and click 'Create' to generate the project.      Step 2: Adding QR Codes to configure two-factor authentication  We will be using a QR code to configure and sync the Google authenticator app with our web app. Download the qrcode.js JavaScript library from https://davidshimjs.github.io/qrcodejs/ and put it into the “wwwroot\lib” folder in your application. Now, your “wwwroot” folder will have the following structure.      Now, Add new scaffolded item in your project by right click on Area folder and select New scaffolded Item under Add section.  Select Identity section on left sidebar and click on Add.      Now, Select the identity files that you have to add to your project but select file “Account/Manage/EnableAuthenticator” is compulsory for 2FA.  Select the DbContext Class of your project and click on add.   Open the “Views\Manage\EnableAuthenticator.cshtml” file. You will find @section Scripts at the end of the file. Put the following code in it.  @section Scripts { @await Html.PartialAsync("_ValidationScriptsPartial") <script src="~/lib/qrcode/qrcode.js"></script> <script type="text/javascript"> new QRCode(document.getElementById("qrCode"), { text: "@Html.Raw(Model.AuthenticatorUri)", width: 200, height: 200 }); </script> }   Note: Change your script path as per your folder structure.  This “EnableAuthenticator.cshtml” file already has a div with the id “qrCode” (see the code snippet below). We are generating a QR code inside that div using the qrcode.js library. We are also defining the dimensions of the QR code in terms of width and height.  So finally, your “EnableAuthenticator.cshtml” file will look like this. @page @model EnableAuthenticatorModel @{ ViewData["Title"] = "Configure authenticator app"; ViewData["ActivePage"] = ManageNavPages.TwoFactorAuthentication; } <partial name="_StatusMessage" for="StatusMessage" /> <h3>@ViewData["Title"]</h3> <div> <p>To use an authenticator app go through the following steps:</p> <ol class="list"> <li> <p> Download a two-factor authenticator app like Microsoft Authenticator for <a href="https://go.microsoft.com/fwlink/?Linkid=825072">Android</a> and <a href="https://go.microsoft.com/fwlink/?Linkid=825073">iOS</a> or Google Authenticator for <a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&amp;hl=en">Android</a> and <a href="https://itunes.apple.com/us/app/google-authenticator/id388497605?mt=8">iOS</a>. </p> </li> <li> <p>Scan the QR Code or enter this key <kbd>@Model.SharedKey</kbd> into your two factor authenticator app. Spaces and casing do not matter.</p> <div class="alert alert-info">Learn how to <a href="https://go.microsoft.com/fwlink/?Linkid=852423">enable QR code generation</a>.</div> <div id="qrCode"></div> <div id="qrCodeData" data-url="@Model.AuthenticatorUri"></div> </li> <li> <p> Once you have scanned the QR code or input the key above, your two factor authentication app will provide you with a unique code. Enter the code in the confirmation box below. </p> <div class="row"> <div class="col-md-6"> <form id="send-code" method="post"> <div class="form-floating mb-3"> <input asp-for="Input.Code" class="form-control" autocomplete="off" placeholder="Please enter the code."/> <label asp-for="Input.Code" class="control-label form-label">Verification Code</label> <span asp-validation-for="Input.Code" class="text-danger"></span> </div> <button type="submit" class="w-100 btn btn-lg btn-primary">Verify</button> <div asp-validation-summary="ModelOnly" class="text-danger" role="alert"></div> </form> </div> </div> </li> </ol> </div> @section Scripts { @await Html.PartialAsync("_ValidationScriptsPartial") <script src="~/lib/qrcode/qrcode.js"></script> <script type="text/javascript"> new QRCode(document.getElementById("qrCode"), { text: "@Html.Raw(Model.AuthenticatorUri)", width: 200, height: 200 }); </script> } When we execute the program, a QR code will be generated in this View. Then you can set up two factor authentication using the Google authenticator with the help of this QR code.  Step 3: Configure two-factor authentication  Before running the application, we need to apply migrations to our app. Navigate to Tools >> NuGet Package Manager >> Package Manager Console. It will open the Package Manager Console. Put in the “Update-Database” command and hit Enter. This will update the database using Entity Framework Code First Migrations. Run the application and click on “Register” in the top right corner of the homepage. You can see a user registration page. Fill in the details and click on the “Register” button as shown in the image below.  Upon successful registration, you will be logged into the application and navigated to the home page. Here, you can see your registered Email id at the top right corner of the page. Click on it to navigate to the “Manage your account” page. Select “TwoFactorAuthentication” from the left menu. You will see a page similar to that shown below.       Click on the “Set up authenticator app” button. You can see a QR code generated on your screen — it is asking for a “Verification Code”, also as shown in the image below.    You need to install the Google Authenticator/Microsoft Authenticator app on your smartphone. It will allow you to scan this QR code in order to generate a Verification Code and complete a two-factor authentication setup.  Open Microsoft Authenticator and click on verified IDs at the bottom. Click on “Scan a barcode” and scan the QR code generated by the web app. This will add a new account to Microsoft authenticator and generate a six-digit pin on your mobile screen. This is our two-factor authentication code. This is a TOTP ( time-based one-time password). You can observe that it keeps on changing frequently (life span of 30 seconds).  Put this pin in the Verification Code textbox and click on verify. Upon successful verification, you will see a screen similar to the one shown below. This will give you the recovery codes for your account that will help to recover your account in case you are locked out. Take a note of these codes and keep them somewhere safe.    Logout of the application and click on login again. Enter your registered email id and password and click on login.    Now you can see a the two-factor authentication screen asking for the Authenticator code. Put in the code that is generated in your Google Authenticator app and click on Login. You will be successfully logged into the application and navigated to the home page. 

Easy Guide to Cancellation Tokens in .NET
Jan 31, 2024

In this blog I'll show how you can use a CancellationToken in your ASP.NET Core action method to stop execution when a user cancels a request from their browser. This can be useful if you have long running requests that you don't want to continue using up resources when a user clicks "stop" or "refresh" in their browser. What is Cancellation Token in c#?  Cancellation tokens in C# are used to signal that a task or operation should be cancelled. They allow for the cooperative cancellation of a task or operation, rather than aborting it forcibly.  Why Use Cancellation Tokens? Here are some benefits of using cancellation tokens:  Avoid resource leaks by freeing up un-managed resources linked to the task  Stop further processing when a task is no longer needed  Improve responsiveness by quickly responding to cancellations  Easy propagation of cancel requests in child tasks  Without cancellation logic, long-running tasks will continue processing in the background even if no longer needed.  You can use cancellaiontoken in any action method or project. Here I am taking one example of .NET web API.  Here, I have created a web API project in .NET, and the above image shows the default controller for the web API, which includes the WeatherForecastController. In that, I have added some log information and added one 10-second task delay that means when this line is executed it will wait for 10 seconds after the next line is executed.  I have added task delay because it is better to understand CancellationToken.  If we hit the URL /GetWeatherForecast then the request will run for 10s, and eventually will return the message. So now, what happens if the user refreshes the browser, halfway through the request? The browser never receives the response from the first request, but as you can see from the logs, the action method executes to completion twice - once for the first (canceled) request, and once for the second (refresh) request.  Whether this is correct behavior will depend on your application.    ASP.NET Core provides a mechanism for the webserver to signal when a request has been canceled using a CancellationToken. This is exposed as HttpContext.RequestAborted, but you can also inject it automatically into your actions using model binding.  Using CancellationToken in your method  CancellationTokens are lightweight objects that are created by a CancellationTokenSource. When a CancellationTokenSource is cancelled, it notifies all the consumers of the CancellationToken. This allows one central location to notify all of the code paths in your app that cancellation was requested.  When cancelled, the IsCancellationRequested property of the cancellation token will be set to True, to indicate that the CancellationTokenSource has been cancelled.  Lets consider the previous example again. We have a long-running action method . As it as an expensive method, we want to stop executing the action as soon as possible if the request is cancelled by the user.  The following code shows how we can hook into the central CancellationTokenSource for the request, by injecting a CancellationToken into the action method, and passing the parameter to the Task.Delay call.  MVC will automatically bind any CancellationToken parameters in an action method to the HttpContext.RequestAborted token, using the CancellationTokenModelBinder.    This model binder is registered automatically when you call services.AddMvc() (or services.AddMvcCore()) in Startup.ConfigureServices().  With this small change, we can test out our scenario again. We'll make an initial request, which starts the long-running action, and then we'll reload the page. As you can see from the logs below, the first request never completes. Instead the Task.Delay call throws a TaskCancelledException when it detects that the CancellationToken.IsCancellationRequested property is true, immediately halting execution.  Summary Users can cancel requests to your web app at any point, by hitting the stop or reload button on your browser. Typically, your app will continue to generate a response anyway, even though Kestrel won't send it to the user. If you have a long-running action method, then you may want to detect when a request is canceled, and stop execution.  You can do this by injecting a CancellationToken into your action method, which will be automatically bound to the HttpContext.RequestAborted token for the request. You can check this token for cancellation as usual, and pass it to any asynchronous methods that support it. If the request is canceled, an OperationCanceledException or TaskCanceledException will be thrown. 

Hosting a .NET Application on IIS Server
Jan 29, 2024

Hosting your .NET application on an IIS (Internet Information Services) server allows it to be accessed and consumed over the internet by users. IIS is commonly used to host .NET applications and web APIs.  Before you can host the application, ensure you have the following:  A .NET web application or API built (for example using ASP.NET Core)  A Windows Server machine with IIS installed and configured  Permissions to remotely access the server over a network    Follow this step-by-step guide to deploy your .NET Application on the IIS Server seamlessly.  Step 1: Open your .NET Application in Visual Studio  Open your application or project in Visual Studio and build the application.    Step 2 : Publish the Application or project.  Now, Right-click on your project and select the publish option.  Here, select the folder and then click on next, and finish the publish setup.  Now, Click on the publish button to publish your code to one folder.  After, publishing is succeeded click on the open folder. You will see your published code in this folder.    Step 3: Configure IIS on the Server  Carry out these steps to prepare IIS for hosting the application. If IIS is not installed in your system, then first install the IIS on your machine.  Open IIS Manager on the Windows Server  Right-click on the Sites folder and click Add Website                    3. Provide a name for the website, Set the physical path to the app folder, and select a port where you want to host the application.                    4. Click OK to create the new IIS website.   Step 4: Publish code to IIS Server.  Now stop the website and open the folder that you have given in the Physical path while configuring it, by right-clicking on your website and selecting explore.  Now, copy all the published files into your server folder.  Once all the files are copied into the publish folder Start the website and click on Browse*: {Your port} (http) under browse website.  you will see the output of your code on the server.  If your project is based on MVC then Recycle Application pool is required. You can find your Application pool under the Application Pool section. Right-click on your website app pool and click on recycle. Conclusion: Hosting the application on IIS allows it to be reached by users from over the network and the internet. It handles request routing and security layers for serving the application.

GitHub CI/CD Tutorial for Pipelines
Jan 12, 2024

In this blog, I will guide you on the power of CI/CD in GitHub with a step-by-step guide. Learn to set up automated workflows, boost project efficiency, and streamline development processes for better code quality and faster deployments. Certainly! It seems that I've encountered a challenge in my current development workflow when deploying minor code changes. The existing process involves manually publishing code from Visual Studio, creating backups of the current code on the server, and then replacing it with the new code. To address this, it's advisable to transition to an automated solution utilizing a Continuous Integration/Continuous Deployment (CI/CD) pipeline.  By implementing a CI/CD pipeline, you can streamline and automate the deployment process, making it more efficient and reducing the risk of manual errors. The CI/CD pipeline will handle tasks such as code compilation, testing, and deployment automatically, ensuring that the latest changes are seamlessly deployed to the desired environment.  This transition will not only save time but also enhance the reliability of your deployment process, allowing your team to focus more on development and less on manual deployment tasks.  For additional information, refer to the steps outlined below for guidance.   Step 1:  Go to your repository and click on the Actions tab   Step 2:  Now, Select the workflow according to your development. Here I am using .NET workflow.   Step 3:  Now you can see the default pipeline as below. In that, you can change your branch as per your requirement. Step 4:  You can now incorporate three new sections as outlined below to build the code and publish the folder as an artifact.  - name: Build and publish      run: |        dotnet restore        dotnet build        dotnet publish -o publish    - name: Zip output      run: |        cd publish        zip -r ../output .  - name: Upload zip archive      uses: actions/upload-artifact@v2      with:        name: test        path: ./publish  Upon integrating this code, your YAML file will now appear as follows.  In the code above, you have the flexibility to rename the zip file or the publish folder according to your preferences.  Build and Publish : This step is responsible for building and publishing the code.  Commands:  dotnet restore: Restores the project's dependencies.  dotnet build: Compiles the project.  dotnet publish -o publish: Publishes the project output to the 'publish' folder.    Zip Output : This step involves compressing the contents of the 'publish' folder into a zip file.  Commands:  cd publish: Changes the working directory to the 'publish' folder.  zip -r ../output .: Creates a zip file named 'output' containing the contents of the 'publish' folder.    Upload Zip Archive :This step uploads the zip archive to the workflow run as an artifact.  Using: The actions/upload-artifact@v2 GitHub Action.  Configuration:  name: test: Specifies the name of the artifact as 'test'.  path: ./publish: Indicates the path of the folder to be archived and uploaded.  By using the given code, you receive a finalized published folder prepared for deployment on the server. However, the deployment process on the server requires manual intervention.  To access the published folder, navigate to the "Actions" tab. Click on the "test" workflow, and you can download the published folder from there.  Step 5:  In the steps mentioned above, you previously followed a manual process, but now you have transitioned to an automatic process.  To automate the process, you'll need to install a self-hosted runner on the virtual machine where your application is hosted.  What is Self-hosted runner?  self-hosted runner is a system that you deploy and manage to execute jobs from GitHub Actions on GitHub.com.  To install the self-hosted runner, follow the basic steps.  Under your repository name, click Settings. If you cannot see the "Settings" tab, select the dropdown menu, then click Settings. In the left sidebar, click Actions, then click Runners and then click on New self-hosted runner.  Select the operating system image and architecture of your self-hosted runner machine.  Open a shell on your self-hosted runner machine and run each shell command in the order shown. For more details you can visit https://docs.github.com/en/enterprise-cloud@latest/actions/hosting-your-own-runners/managing-self-hosted-runners/adding-self-hosted-runners  Step 6:  To automate the process, you can remove the last two sections, "Zip Output" and "Upload Zip Archive," and replace them with the following code.  - name: Backup & Deploy      run: |        $datestamp = Get-Date -Format "yyyyMMddHHmmss"        cd publish        Remove-Item web.config        Remove-Item appsettings.json        Remove-Item appsettings.Development.json        Stop-WebSite 'DemoGitHubPipeline'        Compress-Archive D:\Published\DemoGitHubPipeline         D:\Published\Backup\Backup_$datestamp.zip        Copy-Item * D:\Published\DemoGitHubPipeline -Recurse -Force        Start-WebSite 'DemoGitHubPipeline'  Backup & Deploy : This step is responsible for creating a backup, making necessary modifications, and deploying the application. Commands:  $datestamp = Get-Date -Format "yyyyMMddHHmmss": Retrieves the current date and time in the specified format.  cd publish: Changes the working directory to the 'publish' folder.  Remove-Item web.config: Deletes the 'web.config' file.  Remove-Item appsettings.json: Deletes the 'appsettings.json' file.  Remove-Item appsettings.Development.json: Deletes the 'appsettings.Development.json' file.  Stop-WebSite 'DemoGitHubPipeline': Stops the website with the specified name.  Compress-Archive D:\Published\DemoGitHubPipeline D:\Published\Backup\Backup_$datestamp.zip: Creates a compressed archive (zip) of the existing deployment with proper timestamp.  Copy-Item * D:\Published\DemoGitHubPipeline -Recurse -Force: Copies all contents from the 'publish' folder to the deployment directory.  Start-WebSite 'DemoGitHubPipeline': Restarts the website with the specified name.    Note:  Ensure that the paths and folder structures match the actual locations in your setup.  Adjust the website name and paths based on your specific configuration.  Conclusion: In summary, implementing a CI/CD pipeline in GitHub is a pivotal step towards achieving efficiency, reliability, and accelerated development cycles. The integration of CI/CD streamlines the software delivery process by automating testing, building, and deployment, leading to consistent and high-quality releases.  GitHub Actions, with its native CI/CD capabilities, provides a powerful and flexible platform for orchestrating workflows. Leveraging its features, development teams can not only automate repetitive tasks but also ensure rapid feedback on code changes, enabling early detection of issues and facilitating collaboration. 

magnusminds website loader