Saturday 29 August 2020

Tag Helpers ASP.NET Core

 What are Tag Helpers

Tag Helpers are server side components. They are processed on the server to create and render HTML elements in Razor files. If you have any experience with previous version of ASP.NET MVC, then you may be familiar with HTML helpers. Tag Helpers are similar to HTML helpers. There are many built-in Tag Helpers for common tasks such as generating links, creating forms, loading assets etc.

Importing built-in Tag Helpers

To make the built-in tag helpers available for all the views in our entire application, import the tag helpers using _ViewImports.cshtml file. To import tag helpers we use @addTagHelper directive.

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

The wildcard * indicates that we want to import all the tag helpers.

Microsoft.AspNetCore.Mvc.TagHelpers is the assemly that contains the built-in tag helpers

Generating Links using Tag Helpers

Let's say we want to view a specific employee details. So we want to generate the following hyperlink. The number 5 is the ID of the employee whose details we want to view.

/home/details/5

There are several ways we could do this in a razor view

Option 1 : Manually generating the links

@foreach (var employee in Model)
{
    <a href="/home/details/@employee.Id">View</a>
}


Option 2 :
Using HTML helpers

@Html.ActionLink("View""details"new { id = employee.Id })


generates an anchor element

<a href="/hom/details/5">View</a>

@Url.Action("details""home"new { id = employee.Id })


generates a string

/hom/details/5

Option 3 : Using Tag Helpers

<a asp-controller="home" asp-action="details" asp-route-id="@employee.Id">View</a>

generates

<a href="/Home/details/5">View</a>


Anchor Tag Helper

The Anchor Tag Helper enhances the standard HTML anchor (<a ... ></a>) tag by adding new attributes such as 

asp-controller
asp-action
asp-route-{value}

The rendered anchor element's href attribute value is determined by the values of these asp- attributes. 

As the names imply asp-controller specifies the controller name and asp-action specifies the action name to include in the generated href attribute value. asp-route-{value} attribute is used to include route data in the generated href attribute value. {value} can be replaced with the route parameters such as id for example.

<a asp-controller="home" asp-action="details" asp-route-id="@employee.Id">View</a>

Advantage of using Tag helpers
Tag helpers generate links based on the application routing templates. This means if we later change routing templates, the links generated by tag helpers will automatically reflect those changes made to the routing templates. The generated links just work. 

Where as if we have hard-coded the URL paths manually, we would have to change the code in lot of places when the application routing templates change. Click here

ASP.NET Core Image tag helper
Image Tag Helper can help us achieve this. To use the Image tag helper, include asp-append-version attribute and set it to true.

<img src="~/images/noimage.jpg" asp-append-version="true" />

Image Tag Helper enhances the <img> tag to provide cache-busting behavior for static image files. Based on the content of the image, a unique hash value is calculated and is appended to image URL. This unique string prompts the browser to reload the image from the server and not from the browser cache.

<img class="card-img-top"
src="/images/noimage.jpg?v=IqNLbsazJ7ijEbbyzWPke-xWxkOFaVcgzpQ4SsQKBqY" />

Each time the image on the server changes a new hash value is calculated and cached. If the image has not changed the hash isn't recalculated. Using this unique hash value, the browser keeps track of whether the image content on the server has changed. Click here

ASP.NET Core Environment Tag Helper
Environment tag helper supports rendering different content depending on the application environment. The application environment name is set using using ASPNETCORE_ENVIRONMENT variable.

This example loads the non-minified bootstrap css file, if the application environment is "Development"

<environment include="Development">
    <link href="~/lib/bootstrap/css/bootstrap.css" rel="stylesheet" />
</environment>

This example loads the minified bootstrap css file from the CDN (Content Delivery Network), if the application environment is "Staging" or "Production".

<environment include="Staging,Production">
    <link rel="stylesheet"
            href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
            integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
            crossorigin="anonymous">
</environment>

"include" attribute accepts a single hosting environment name or a comma-separated list of hosting environment names. On the <environment> tag helper, we also have "exclude" attribute. The content of the <environment> tag is rendered when the hosting environment doesn't match an environment listed in the exclude attribute value.

The "integrity" attribute on the <link> element is used for Subresource Integrity check. Subresource Integrity (SRI for short), is a security feature that allows a browser to check if the file being retrieved has been maliciously altered. When the browser downloads the file, it recalculates the hash and compares it against the "integrity" attribute hash value. If the hash values match, the browser allows the file to be downloaded otherwise it is blocked. Click here

Form tag helpers in asp.net core

We use the following common tag helpers to create a form in ASP.NET Core.  Click here for more
  • Form Tag Helper
  • Label Tag Helper
  • Input Tag Helper
  • Select Tag Helper
  • Textarea Tag Helper
Form Tag Helper:
<form asp-controller="home" asp-action="create" method="post">
</form>

Input Tag Helper:
The Input Tag Helper binds an HTML <input> element to a model expression in your razor view.

@model Employee

<input asp-for="Name">

Label Tag Helper:
The Label Tag Helper generates a label with for attribute. The for attribute links the label with it's associated input element. Consider the following example.

<label asp-for="Name"></label>
<input asp-for="Name">

//The above code generates the following HTML. 

<label for="Name">Name</label>
<input type="text" id="Name" name="Name" value="">

Select Tag Helper:
Generates select element and it's associated option elements.

namespace EmployeeManagement.Models
{
    public enum Dept
    {
        None,
        HR,
        Payroll,
        IT
    }
}

<label asp-for="Department"></label>
<select asp-for="Department"
        asp-items="Html.GetEnumSelectList<Dept>()"></select>

Notice, we are using asp-items tag helper and Html.GetEnumSelectList<Dept>() to get the options for the select element.

Create.cshtml - Complete Code without Bootstrap
@model Employee

@{
    ViewBag.Title = "Create Employee";
}

<form asp-controller="home" asp-action="create" method="post">
    <div>
        <label asp-for="Name"></label>
        <input asp-for="Name" />
    </div>

    <div>
        <label asp-for="Email"></label>
        <input asp-for="Email">
    </div>

    <div>
        <label asp-for="Department"></label>
        <select asp-for="Department"
                asp-items="Html.GetEnumSelectList<Dept>()"></select>
    </div>
    <button type="submit">Create</button>
</form>



Continue Reading →

Tuesday 25 August 2020

ASP NET Core appsettings json file

 ASP.NET Core appsettings.json file

Configuration Sources in ASP.NET Core

In previous versions of ASP.NET, we store application configuration settings, like database connection strings for example, in web.config file. In ASP.NET Core application configuration settings can come from the following different configurations sources.

  1. Files (appsettings.json, appsettings.{Environment}.json, where {Environment} is the app's current hosting environment)
  2. User secrets
  3. Environment variables
  4. Command-line argument

appsettings.json file : In the asp.net core project that is generated by the "Empty" project template we already have a file with name appsettings.json. I have modified this file to include a new setting with the key - MyKey.

{
    "Logging": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "AllowedHosts""*",
    "MyKey""Value of MyKey from appsettings.json"
  }


Accessing configuration information 

To access configuration information in the Startup class, inject the IConfiguration service provided by the Framework. Startup class is in Startup.cs file.

public class Startup
{
    private IConfiguration _configuration;

    // Notice we are using Dependency Injection here
    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void Configure(IApplicationBuilder appIHostingEnvironment env)
    {
        app.Run(async (context=>
        {
            await context.Response.WriteAsync(_configuration["MyKey"]);
        });
    }

    var ResLogConfiguration.GetSection("ResponseLogging").Value ;
    var CorsHeaderConfiguration.GetValue<string>("Cors:Headers");
}


ASP.NET Core IConfiguration service

  1. IConfiguration service is setup to read configuration information from all the various configuration sources in asp.net core
  2. If you have a configuration setting with the same key in multiple configuration sources, the later configuration sources override the earlier configuration sources 
  3. CreateDefaultBuilder() method of the WebHost class which is automatically invoked when the application starts, reads the configuration sources in a specific order.
  4. To see the order in which the configuration sources are read, please check out ConfigureAppConfiguration() method on the following link github.com

Upon inspecting the file, you will see, the following is the default order in which the various configuration sources are read

  1. appsettings.json, 
  2. appsettings.{Environment}.json
  3. User secrets
  4. Environment variables
  5. Command-line arguments

You can change this order if you want to or even add your own custom configuration sources in addition to all the existing configuration sources. 


Continue Reading →

ASP.NET Core InProcess/OutOfProcess hosting

InProcess Hosting in ASP.NET Core

When an ASP.NET core application is executed, the .NET runtime looks for Main() method which is the entry point for the application. The Main() method then calls CreateDefaultBuilder() static method of the WebHost class. 

This CreateDefaultBuilder() method performs several tasks like 

  1. Setting up the web server 
  2. Loading the host and application configuration from various configuration sources and 
  3. Configuring logging

An ASP.NET core application can be hosted InProcess or OutOfProcess. here we will discuss only InProcess.

With InProcess hosting, the application is hosted in the IIS worker process (w3wp.exe or iisexpress.exe). With InProcess hosting, there is only one web server and that is the IIS server that hosts our application.

InProcess hosting in ASP.NET Core

To configure InProcess hosting, add <AspNetCoreHostingModel> element to the app's project file with a value of InProcess

<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>

When we create a new ASP.NET Core project using one of the available project templates, the project defaults to the in-process hosting model for all IIS and IIS Express scenarios.

In case of InProcess hosting, CreateDefaultBuilder() method calls UseIIS() method and host the app inside of the IIS worker process (w3wp.exe or iisexpress.exe). 

  1. From a performance standpoint, InProcess hosting delivers significantly higher request throughput than OutOfProcess hosting
  2. In the case of IIS, the process name that executes the app is w3wp and in the case of IIS Express it is iisexpress
  3. To get the process name executing the app, use System.Diagnostics.Process.GetCurrentProcess().ProcessName
  4. When we are run the project from Visual Studio it uses IISExpress by default. 
  5. IIS Express is a lightweight, self-contained version of IIS, optimized for application development. We do not use it for production. In production we use IIS.

Out of Process Hosting in ASP.NET Core

To configure an app for out-of-process hosting, set the value of the <AspNetCoreHostingModel> property to OutOfProcess in the project file (.csproj):

<PropertyGroup>
  <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
</PropertyGroup>

In-process hosting is set with InProcess, which is the default value.

The value of <AspNetCoreHostingModel> is case insensitive, so inprocess and outofprocess are valid values.

Kestrel server is used instead of IIS HTTP Server (IISHttpServer).
For out-of-process, CreateDefaultBuilder calls UseIISIntegration to:

  1. Configure the port and base path the server should listen on when running behind the ASP.NET Core Module.
  2. Configure the host to capture startup errors.

There are 2 web servers - An internal web server and an external web server

  • The internal web server is Kestrel and the external web server can be IIS, Nginx or Apache.
  • With InProcess hosting, there is only one web server i.e the IIS that hosts the asp.net core application. 

Depending on how you are running the asp.net core application, the external web server may or may not be used. 

What is Kestrel

Kestrel is a cross-platform web server for ASP.NET Core. When we run a .NET Core application using the .NET Core CLI (Command-Line Interface), the application uses Kestrel as the web server. 

The .NET Core CLI is a cross-platform tool for developing .NET core applications. Using the CLI we can

  1. Create a new project, configuration file, or solution based on the specified template
  2. Restore the dependencies and tools required for a .net core project
  3. Build a project and all of its dependencies
  4. Run a project etc...

Reference: Click here

Continue Reading →

Main method in asp.net core

 In an ASP.NET Core project we have seen a file with named Program.cs. In this file we have a public static void Main() method.

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

If you have any experience with previous versions of .NET, a console application has a Main() method and it is the entry point for that console application.

But here, we are creating an asp.net core web application and not a console application. So the obvious question that comes to our mind is why do we have a Main() method.

Well, the important point to keep in mind is that, an asp.net core application initially starts as a console application and the Main() method in Program.cs file is the entry point. 

So, when the runtime executes our application it looks for this Main() method and execution starts.

This Main() method configures asp.net core and starts it and at that point it becomes an asp.net core web application.

So, if you take a look at the Main() method, it calls CreateWebHostBuilder() method passing it the command line arguments. https://github.com/WebHost.cs

As you can see, CreateWebHostBuilder() method returns an object that implements IWebHostBuilder.

On this object, Build() method is called which builds a web host that hosts our asp.net core web application.

On the web host Run() method is called, which runs the web application and it begins listening for incoming HTTP requests.

CreateWebHostBuilder() method calls CreateDefaultBuilder() static method of the WebHost class.

CreateDefaultBuilder() method creates a web host with pre-configured defaults. CreateDefaultBuilder() method does several things to create a web host. 

As part of setting up a web host, Startup class is also configured using the UseStartup() extension method of IWebHostBuilder class.

By convention, the startup class in ASP.NET Core is named Startup. This class has 2 methods.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    { }

    public void Configure(IApplicationBuilder appIHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.Run(async (context=>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

Startup class does the following 2 very important things

  • ConfigureServices() method configures services required by the application
  • Configure() method sets up the application's request processing pipeline


Continue Reading →

Saturday 1 August 2020

async and await in C#

  1.  The async keyword turns a method into an async method, which allows you to use the await keyword in its body. 
  2. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete.
  3. await can only be used inside an async method.
private readonly HttpClient _httpClient = new HttpClient();

[HttpGetRoute("DotNetCount")]
public async Task<intGetDotNetCount()
{
    // Suspends GetDotNetCount() to allow the caller (the web server)
    // to accept another request, rather than blocking on this one.
    var html = await _httpClient.GetStringAsync("https://dotnetfoundation.org");

    return Regex.Matches(html, @"\.NET").Count;
}

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives