ASP.NET Core 3.0 Flashcards

1
Q

ConfigureServices method in startup.cs

A
we define our interface and the class that implements the interface here; 
we are adding that to IServiceCollection 
   public void ConfigureServices(IServiceCollection services)
        {
services.AddTransient();

        services.AddSingleton(); } if some ask you for Icontent, then provider them with ContentDAL class
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

To inject a service in cshtml

A

@model Employee
@inject IEmployeeRepository _empRepository

<div>
Total Employee Count= @_empRepository.GetAllEmployee().count() -switching to code
</div>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

with singleton Service

A
There is only a single instance. An instance is created, when the service is first requested and that single instance is used by all http requests throughout the application
-usually the  first created when the first dependency injection happens in the controller or any class constructor

in startup.cs:
services.AddSingleton();

//NOTE: register service

        services. AddTransient();
        services. AddTransient();
        services. AddTransient();
        services. AddTransient();
        services. AddTransient();
        services. AddTransient();
        services. AddTransient();
in Alert Controller constructor:
 public AlertController(ILogger logger, IMapper mapper, IAlert alertDal, IOptions customOptions)
        {
            _logger = logger;
            _mapper = mapper;
            _alertDal = alertDal;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

with Scoped service

A

we get the same instance within the scope of a given http request but a new instance across different http request
if we issue post and in the action method we have dependency injection and we have cshtml associated with it then we get the same instance for both of them but we issue another post request; again a new instance is created and calls the class constructors sets to default values and operates on that method
in startup.cs:
services.AddScoped();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

with a transient service

A

with a transient service, a new instance is provided every time an instance is requested whether it is in the scope of the same HTTP request or across different http request

Even with in the same post action method. the method has separate service instance and the view has separate service instance
if it is different action methods then both of them have different services instances

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

ObjectResult Class

A
Namespace:
Microsoft.AspNetCore.Mvc
Assembly:
Microsoft.AspNetCore.Mvc.Core.dll
Inheritance
Object--
ActionResult--
ObjectResult
Property: Value
Method:
ExecuteResult(ActionContext)	
Executes the result operation of the action method synchronously. This method is called by MVC to process the result of an action method.

(Inherited from ActionResult)
–Usage
// execute
var result = await _alertController.ListActiveAlerts(userId.ToString()) as ObjectResult;
var resultList = result.Value as List;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

using IOptions for reading configurations

A

How to use the IOptions pattern for configuration in ASP.NET Core RC2
Share on:
Almost every project will have some settings that need to be configured and changed depending on the environment, or secrets that you don’t want to hard code into your repository. The classic example is connection strings and passwords etc which in ASP.NET 4 were often stored in the section of web.config.

In ASP.NET Core this model of configuration has been significantly extended and enhanced. Application settings can be stored in multiple places - environment variables, appsettings.json, user secrets etc - and easily accessed through the same interface in your application. Further to this, the new configuration system in ASP.NET allows (actually, enforces) strongly typed settings using the IOptions<> pattern.

While working on an RC2 project the other day, I was trying to use this facility to bind a custom Configuration class, but for the life of me I couldn’t get it to bind my properties. Partly that was down to the documentation being somewhat out of date since the launch of RC2, and partly down to the way binding works using reflection. In this post I’m going to go into demonstrate the power of the IOptions<> pattern, and describe a few of the problems I ran in to and how to solve them.

Strongly typed configuration
In ASP.NET Core, there is now no default AppSettings["MySettingKey"] way to get settings. Instead, the recommended approach is to create a strongly typed configuration class with a structure that matches a section in your configuration file (or wherever your configuration is being loaded from):
public class MySettings
{
    public string StringSetting { get; set; }
    public int IntSetting { get; set; }
}
Would map to the lower section in the appsettings.json below.
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "MySettings": {
    "StringSetting": "My Value",
    "IntSetting": 23 
  }
}
Binding the configuration to your classes
In order to ensure your appsettings.json file is bound to the MySettings class, you need to do 2 things.
Setup the ConfigurationBuilder to load your file
Bind your settings class to a configuration section
When you create a new ASP.NET Core application from the default templates, the ConfigurationBuilder is already configured in Startup.cs to load settings from environment variables, appsettings.json, and in development environments, from user secrets:
public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
    builder.AddUserSecrets();
}

builder.AddEnvironmentVariables();
Configuration = builder.Build(); } If you need to load your configuration from another source then this is the place to do it, but for most common situations this setup should suffice. There are a number of additional configuration providers that can be used to bind other sources, such as xml files for example.

In order to bind a settings class to your configuration you need to configure this in the ConfigureServices method of Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
services.Configure(options => Configuration.GetSection(“MySettings”).Bind(options));
}
Note: The syntax for model binding has changed from RC1 to RC2 and was one of the issues I was battling with. The previous method, using services.Configure(Configuration.GetSection(“MySettings”)), is no longer available

You may also need to add the configuration binder package to the dependencies section of your project.json:

“dependencies”: {

“Microsoft.Extensions.Configuration.Binder”: “1.0.0-rc2-final”

}
Update: As mentioned by Larry Ruckman, you can now use the old binding syntax if you add the package Microsoft.Extensions.Options.ConfigurationExtensions with version 1.0.0-rc2-final to your project.json

Using your configuration class
When you need to access the values of MySettings you just need to inject an instance of an IOptions<> class into the constructor of your consuming class, and let dependency injection handle the rest:
public class HomeController : Controller
{
    private MySettings _settings;
    public HomeController(IOptions settings)
    {
        _settings = settings.Value
        // _settings.StringSetting == "My Value";
    }
}

The IOptions<> service exposes a Value property which contains your configured MySettings class.

It’s important to note that there doesn’t appear to be a way to access the raw IConfigurationRoot through dependency injection, so the strongly typed route is the only way to get to your settings.

You can expose the IConfigurationRoot directly to the DI container using services.AddSingleton(Configuration). (Thanks Saša Ćetković for pointing that out!)

Complex configuration classes
The example shown above is all very nice, but what if you have a very complex configuration, nested types, collections, the whole 9 yards?

public class MySettings
{
    public string StringSetting { get; set; }
    public int IntSetting { get; set; }
    public Dictionary Dict { get; set; }
    public List ListOfValues { get; set; }
    public MyEnum AnEnum { get; set; }
}
public class InnerClass
{
    public string Name { get; set; }
    public bool IsEnabled { get; set; } = true;
}
public enum MyEnum
{
    None = 0, 
    Lots = 1
}
Amazingly we can bind that using the same configure call to the following, and it all just works:
{
  "MySettings": {
    "StringSetting": "My Value",
    "IntSetting": 23,
    "AnEnum": "Lots",
    "ListOfValues": ["Value1", "Value2"],
    "Dict": {
      "FirstKey": {
        "Name": "First Class",
           "IsEnabled":  false 
      }, 
      "SecondKey": {
        "Name": "Second Class"
      } 
    }
  }
}

When values aren’t provided, they get their default values, (e.g. MySettings.Dict[“SecondKey].IsEnabled == true). Dictionaries, lists and enums are all bound correctly. That is until they aren’t…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

using IOptions for reading configurations - My example

A
Add Connection Strings to appsetting.json:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "PHODB": "server=MCPHOSQLTST01;user id=AppPHO;password=C0ff33M8;database=PHO"
  },
  "AllowedHosts": "*"
}
---------------
Add new folder to project name it may be "settings". add a class with the same name as the object in appsettings.json for which you would like to create a class. here it is ConnectionString. Create public property for data that needs to be accessed

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication5.Settings
{
    public class ConnectionStrings
    {
        public string PHODB { get; set; }
    }
}

in program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingcontex,config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile(“appsettings.json”, optional: true, reloadOnChange: false);
}

            )
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup();
            })        
        ;

add a method to add the json appsettings file; to read the connection string; using system.IO for Directory class

in start up.cs
include the configuration with the class that we created
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.Configure(options => Configuration.GetSection(“ConnectionStrings”).Bind(options));
}

use the Dependency injection for IOptions and use it in our api controller:
[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 _logger;
        private readonly ConnectionStrings _connectionStrings;
        private readonly string _PHODB_ConnectionString;
        public WeatherForecastController(ILogger logger,IOptions options)
        {
            _logger = logger;
            _connectionStrings = options.Value;
            _PHODB_ConnectionString = _connectionStrings.PHODB;
        }

Make sure that the class name created for IOptions and the object in the appsettings.json are the same. The property names also should be the same

https://andrewlock.net/how-to-use-the-ioptions-pattern-for-configuration-in-asp-net-core-rc2/

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

custom options

A

CustomOptions object is part of an example of how you can use the appsettings to embed custom app settings into various parts of the app. To use the Alerts example, your current rule is to show 3 active alerts at a time. However, if you wanted to make that more configurable without changing code, you could put a property in the CustomOptions section of the appsettings and a corresponding property in the CustomOptions object and then float that around to various DALs or controllers by putting IOptions in the constructor. In the Alert example, you could pick that up in the DAL constructor and set it as a private member in the class and use it in the sproc call to retrieve 3 items. If you wanted to change it to 5, you could change the appsettings property and restart the application to use 5 instead, without any code changes (of course, also changing the appsettings in source control should you wish to keep the change).

As to whether or not you need it from class to class, that’s up to you to decide.

This feels like a smaller app with fewer options, so it might be safe in this instance to just have one CustomOptions object. In the bigger picture, you can nest objects in CustomOptions and read them into the app individually by JSON path, so you could have CustomOptions.AlertOptions, and CustomOptions.PatientOptions, but I don’t know off the top of my head if you’ll even have any custom options in this app just yet.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Adding custom options example

A

in appsettings.json define custom options
{
“Logging”: {
“LogLevel”: {
“Default”: “Information”,
“Microsoft”: “Warning”,
“Microsoft.Hosting.Lifetime”: “Information”
}
},
“ConnectionStrings”: {
“PHODB”: “server=MCPHOSQLTST01;user id=AppPHO;password=C0ff33M8;database=PHO”
},
“CustomOptions”: {
“Message”: “this is data from appsettings.json, custom options”,
“CustomOptionValue”: “test”
},
“AllowedHosts”: “*”
}
———–
in program.cs, we are already reading the appsettings.json file for connectionstring;so we do not need to put it again
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingcontex, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile(“appsettings.json”, optional: true, reloadOnChange: false);
}

            )
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup();
            });
}
---
Create a new class for CustomOptions with the properties similar to appsettings.json file:
namespace WebApplication5.Settings
{
    public class CustomOptions
    {
        public string Message { get; set; }
        public string CustomOptionValue { get; set; }
    }
}

in startup.cs
add the mapping
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.Configure(options => Configuration.GetSection(“ConnectionStrings”).Bind(options));
services.Configure(options => Configuration.GetSection(“CustomOptions”).Bind(options));
}


update the dependency injection in api controller action method
private readonly ILogger _logger;
private readonly ConnectionStrings _connectionStrings;
private readonly string _PHODB_ConnectionString;

        //For custom options
        private readonly CustomOptions _customOptions;
        private readonly string _message;
        public WeatherForecastController(ILogger logger,IOptions options, IOptions customoptions)
        {
            _logger = logger;
            _connectionStrings = options.Value;
            _PHODB_ConnectionString = _connectionStrings.PHODB;
            _customOptions = customoptions.Value;
            _message = _customOptions.Message;
        }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to using AutoMapper on ASP.NET Core 3.0 via Dependency Injection

A
Step 1. Install AutoMapper extension from Package Manager in your project
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -Version 7.0.0
Step 2. Register a service in CinfigureServices on Startup.cs
// Startup.cs
using AutoMapper;
public void ConfigureServices(IServiceCollection services){
    services.AddAutoMapper(typeof(Startup));
}
Step 3. Create a model and a data transfer object
// User.cs
// The model you want to map from
public class User{
    public string Name {get;set;}
    public string Email {get;set;}
    public string Phone {get;set;}
// Constructor to initialize User
    public User(){
        Name = "Nicky";
        Email = "myemail@gmail.com";
        Phone = "+81234588";
    }
}
// UserDTO.cs
// The data transfer object you want to map to
public class UserDTO{
    public string Name{get;set;}
    public string Email{get;set;}
    public string Phone{get;set;}
}
Step 4. Create an AutoMapping class file to register a mapping relation
// AutoMapping.cs
using AutoMapper;
public class AutoMapping : Profile
{
    public AutoMapping()
    {
        CreateMap(); // means you want to map from User to UserDTO
    }
}
Step 5. Map User to UserDTO in code
// HomeController.cs
using AutoMapper;
public class HomeController : Controller
{
    private readonly IMapper _mapper;
    public HomeController(IMapper mapper)
    {
        _mapper = mapper;
    }
    public IActionResult GetUser()
    {
        User user = new User();
        var userDTO = _mapper.Map(user);
        return View(userDTO);
    }
}
Finally, you got a dto object:
var name = userDTO.Name; // name = "Nicky"
var email = userDTO.Email; // email = "myemail@gmail.com"
var phone = userDTO.Phone; // phone = "+81234588"

https://www.codementor.io/@zedotech/how-to-using-automapper-on-asp-net-core-3-0-via-dependencyinjection-zq497lzsq

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is Middleware?

A

Middleware was firstly introduced in ASP.NET Core 1.0 (Q1 2016). Middleware is components of an application that examine the requests responses coming into and coming out from an ASP.NET Core application. In other words, it’s the layer that every request and response have to go through.

ASP.NET Core version 1.1 (Q4 2016) brought some new features, performance improvements, and also addressed many bugs and compatibility issues affecting to the former one. The new features include the ability to configure Middleware as Filters.

Typically, there will be multiple Middleware in ASP.NET Core web application. It can be either framework provided middleware, added via NuGet or your own custom middleware. We can set the order of middleware execution in the request pipeline.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How middleware works

A

How it works?
When an HTTP request comes in, the first request delegate handles that request. It chooses either passing the request on to the next component in the pipeline or performing certain actions before and after the next component is invoked in the pipeline. It allows unnecessary work to be avoided. This is very useful in some scenarios like handling exceptions before anything else or serving static files.
The returned response travels back in the reverse direction back through the pipeline. This allows each component to run code both times: when the request arrives and also when the response is on its way out. (see figure 2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Middleware :What are Run, Map and Use?
Run, Map and Use are three methods that you will need to use to configure HTTP Pipeline.
Run method

A

Run method
The Run method is an extension method on IApplicationBuilder and accepts a parameter of RequestDelegate that handles the request. “Run” method enables short-circuiting with a terminal middleware delegate.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Middle ware “Use” method

A

This method allows you to call the next desired middleware delegate. The call to app.Use() can be used to trigger the next middleware component with a call to next.Invoke() as shown below:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Middleware “Map” method

A

This method is used to match request delegates based on a request’s path. This method allows branching of the pipeline path. In other words, this method creates separate forked paths/branches for your middleware pipeline and multiple terminating ends.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Built-In Middleware

A

I will show you, how the built-in middleware works and why the order is important.
Note: We should use the “Use” prefix naming convention when we create new custom Middleware. For example: UseFileUploadErrorPage, UseDebugErrorPage,…

Exception Handling:
UseDeveloperExceptionPage() & UseDatabaseErrorPage(): used in development phase to catch run-time exceptions.
UseExceptionHandler(): used in production for run-time exceptions
Calling these methods first ensures that exceptions are caught.

  1. HSTS & HTTPS Redirection:
    UseHsts(): used in production to enable HSTS (HTTP Strict Transport Security Protocol) and enforce HTTPS.
    UseHttpsRedirection(): forces HTTP calls to automatically redirect to equivalent HTTPS addresses.
    Calling these methods next ensure that HTTPS can be enforced before resources are served from a web browser.
  2. Static files:
    UseStaticFiles(): used to enable static files, such as HTML, JavaScript, CSS and graphics files.
    This Middleware is called early on to avoid the need for authentication, session or MVC middleware.
  3. Cookie Policy:
    UseCookiePolicy(): used to enforce cookie policy and display GDPR-friendly messaging
  4. Authentication, Authorization & Sessions:
    UseAuthentication(): used to enable authentication and then subsequently allow authorization.
    UserSession(): manually added to the Startup file to enable the Session middleware.
    Calling these after cookie authentication (but before the MVC middleware) ensures that cookies can be issued as necessary and that the user can be authenticated before the MVC engine kicks in.
  5. MVC & Routing:
    UseMvc(): enables the use of MVC in your web application, with the ability to customize routes for your MVC application and set other options.
    routes.MapRoute(): set the default route and any custom routes when using MVC.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Custom Middleware

A

https://medium.com/swlh/what-is-middleware-in-asp-net-core-and-how-important-is-it-3021d4fb90d2

We can use some custom Middleware on NuGet. For example: Diagnostic Middleware.
Note: If you want to create your custom Middleware, please read again section: “What are Run, Map and Use?” above.

Diagnostics middleware is used for reporting and handling exceptions and errors in ASP.NET Core, and diagnosing Entity Framework Core migrations errors.
This package includes following middleware and extension methods for it.

DeveloperExceptionPageMiddleware — UseDeveloperExceptionPage(): Captures synchronous and asynchronous exceptions from the pipeline and generates HTML error responses.

ExceptionHandlerMiddleware — UseExceptionHandler(): Catch exceptions, log them and re-execute in an alternate pipeline.

StatusCodePagesMiddleware — UseStatusCodePages(): Check for responses with status codes between 400 and 599.

WelcomePageMiddleware — UseWelcomePage(): Display Welcome page for the root path.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

order of the middle ware is important, as they get executed in sequence

A

The below diagram illustrates the typical order of middleware layers in an ASP .NET Core web application. The order is very important, so it is necessary to understand the placement of each request delegate in the pipeline.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Middleware is like interceptor in angular

A

Middleware is like interceptor in angular

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

configuration options and their sequence of preferrence

A

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

CreateDefaultBuilder provides default configuration for the app in the following order:

ChainedConfigurationProvider : Adds an existing IConfiguration as a source. In the default configuration case, adds the host configuration and setting it as the first source for the app configuration.
appsettings.json using the JSON configuration provider.
appsettings.Environment.json using the JSON configuration provider. For example, appsettings.Production.json and appsettings.Development.json.
App secrets when the app runs in the Development environment.
Environment variables using the Environment Variables configuration provider.
Command-line arguments using the Command-line configuration provider.
Configuration providers that are added later override previous key settings. For example, if MyKey is set in both appsettings.json and the environment, the environment value is used. Using the default configuration providers, the Command-line configuration provider overrides all other providers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

adding json config file

A

The JsonConfigurationProvider loads configuration from JSON file key-value pairs.

Overloads can specify:

Whether the file is optional.
Whether the configuration is reloaded if the file changes.

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.AddJsonFile("MyConfig.json", 
                optional: true, 
                reloadOnChange: true);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup();
        }); } The preceding code:

Configures the JSON configuration provider to load the MyConfig.json file with the following options:
optional: true: The file is optional.
reloadOnChange: true : The file is reloaded when changes are saved.
Reads the default configuration providers before the MyConfig.json file. Settings in the MyConfig.json file override setting in the default configuration providers, including the Environment variables configuration provider and the Command-line configuration provider.
You typically don’t want a custom JSON file overriding values set in the Environment variables configuration provider and the Command-line configuration provider.

The following code clears all the configuration providers and adds several configuration providers:

C#

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

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.Sources.Clear();

            var env = hostingContext.HostingEnvironment;

            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", 
                                 optional: true, reloadOnChange: true);

            config.AddJsonFile("MyConfig.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"MyConfig.{env.EnvironmentName}.json",
                                 optional: true, reloadOnChange: true);

            config.AddEnvironmentVariables();

            if (args != null)
            {
                config.AddCommandLine(args);
            }
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup();
        }); } In the preceding code, settings in the MyConfig.json and MyConfig.Environment.json files:

Override settings in the appsettings.json and appsettings.Environment.json files.
Are overridden by settings in the Environment variables configuration provider and the Command-line configuration provider.

23
Q

Host

A

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/?view=aspnetcore-3.1&tabs=windows#host

On startup, an ASP.NET Core app builds a host. The host encapsulates all of the app’s resources, such as:

An HTTP server implementation
Middleware components
Logging
Dependency injection (DI) services
Configuration
There are two different hosts:

.NET Generic Host
ASP.NET Core Web Host
The .NET Generic Host is recommended. The ASP.NET Core Web Host is available only for backwards compatibility.

The following example creates a .NET Generic Host:

C#

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

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup();
        }); } The CreateDefaultBuilder and ConfigureWebHostDefaults methods configure a host with a set of default options, such as:

Use Kestrel as the web server and enable IIS integration.
Load configuration from appsettings.json, appsettings.{Environment Name}.json, environment variables, command line arguments, and other configuration sources.
Send logging output to the console and debug providers.

24
Q

Host versus app configuration

A

Before the app is configured and started, a host is configured and launched. The host is responsible for app startup and lifetime management. Both the app and the host are configured using the configuration providers described in this topic. Host configuration key-value pairs are also included in the app’s configuration. For more information on how the configuration providers are used when the host is built and how configuration sources affect host configuration, see ASP.NET Core fundamentals.

Default host configuration
For details on the default configuration when using the Web Host, see the ASP.NET Core 2.2 version of this topic.

Host configuration is provided from:
Environment variables prefixed with DOTNET_ (for example, DOTNET_ENVIRONMENT) using the Environment Variables configuration provider. The prefix (DOTNET_) is stripped when the configuration key-value pairs are loaded.
Command-line arguments using the Command-line configuration provider.
Web Host default configuration is established (ConfigureWebHostDefaults):
Kestrel is used as the web server and configured using the app’s configuration providers.
Add Host Filtering Middleware.
Add Forwarded Headers Middleware if the ASPNETCORE_FORWARDEDHEADERS_ENABLED environment variable is set to true.
Enable IIS integration.
Other configuration
This topic only pertains to app configuration. Other aspects of running and hosting ASP.NET Core apps are configured using configuration files not covered in this topic:

launch.json/launchSettings.json are tooling configuration files for the Development environment, described:
In Use multiple environments in ASP.NET Core.
Across the documentation set where the files are used to configure ASP.NET Core apps for Development scenarios.
web.config is a server configuration file, described in the following topics:
Host ASP.NET Core on Windows with IIS
ASP.NET Core Module
Environment variables set in launchSettings.json override those set in the system environment.

For more information on migrating app configuration from earlier versions of ASP.NET, see Migrate from ASP.NET to ASP.NET Core.

25
Q

options patterns is recomended for reading configuration files

A

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1

we could have Dependency injection or use configuration to access the settings

26
Q

Repository pattern for database calls

A

Repository pattern is an abstraction of the dataaccess layer
it hides the details of how the data is exactly saved or retrieved from the underlying datasouce
the details of how it stores or retrieved data is in repository

you may have a repository that save data from xml file

you may have a repository that saves data from sql server database

27
Q
Repository interface IemployeeRepository
Repository class that implemetns repository interface
A
Repository interface IemployeeRepository
public interface IEmployeeRepository
{
    Employee GetEmployee(int Id);
    IEnumerable GetAllEmployee();
    Employee Add(Employee employee);
    Employee Update(Employee employeeChanges);
    Employee Delete(int Id);
}
this interface does not have details about the implementation, the repository class provides it implementation

Repository class that implemetns repository interface

28
Q

Repository Pattern - In-memory Implementation

A

Repository Pattern - In-memory Implementation

The following MockEmployeeRepository class provides an implementation for IEmployeeRepository. This specific implementation stores and retrieves employees from an in-memory collection.

public class MockEmployeeRepository : IEmployeeRepository
{
    private List _employeeList;
    public MockEmployeeRepository()
    {
        _employeeList = new List()
        {
            new Employee() { Id = 1, Name = "Mary", Department = Dept.HR, Email = "mary@pragimtech.com" },
            new Employee() { Id = 2, Name = "John", Department = Dept.IT, Email = "john@pragimtech.com" },
            new Employee() { Id = 3, Name = "Sam", Department = Dept.IT, Email = "sam@pragimtech.com" },
        };
    }
public Employee Add(Employee employee)
{
    employee.Id = _employeeList.Max(e => e.Id) + 1;
    _employeeList.Add(employee);
    return employee;
}
    public Employee Delete(int Id)
    {
        Employee employee = _employeeList.FirstOrDefault(e => e.Id == Id);
        if (employee != null)
        {
            _employeeList.Remove(employee);
        }
        return employee;
    }
public IEnumerable GetAllEmployee()
{
    return _employeeList;
}

public Employee GetEmployee(int Id)
{
    return this._employeeList.FirstOrDefault(e => e.Id == Id);
}

public Employee Update(Employee employeeChanges)
{
    Employee employee = _employeeList.FirstOrDefault(e => e.Id == employeeChanges.Id);
    if (employee != null)
    {
        employee.Name = employeeChanges.Name;
        employee.Email = employeeChanges.Email;
        employee.Department = employeeChanges.Department;
    }
    return employee;
} }
29
Q

Repository Pattern - SQL Server Implementation

A

The following SQLEmployeeRepository class provides another implementation for IEmployeeRepository. This specific implementation stores and retrieves employees from a sql server database using entity framework core.

public class SQLEmployeeRepository : IEmployeeRepository
{
    private readonly AppDbContext context;
    public SQLEmployeeRepository(AppDbContext context)
    {
        this.context = context;
    }
    public Employee Add(Employee employee)
    {
        context.Employees.Add(employee);
        context.SaveChanges();
        return employee;
    }
    public Employee Delete(int Id)
    {
        Employee employee = context.Employees.Find(Id);
        if (employee != null)
        {
            context.Employees.Remove(employee);
            context.SaveChanges();
        }
        return employee;
    }
public IEnumerable GetAllEmployee()
{
    return context.Employees;
}

public Employee GetEmployee(int Id)
{
    return context.Employees.Find(Id);
}
    public Employee Update(Employee employeeChanges)
    {
        var employee = context.Employees.Attach(employeeChanges);
        employee.State = Microsoft.EntityFrameworkCore.EntityState.Modified;
        context.SaveChanges();
        return employeeChanges;
    }
}
30
Q

Defining which repository pattern implementation to use

A

Take a look at the following HomeController in our application. ASP.NET Core Dependency injection system injects an instance of IEmployeeRepository.

public class HomeController : Controller
{
    private IEmployeeRepository _employeeRepository;
    public HomeController(IEmployeeRepository employeeRepository)
    {
        _employeeRepository = employeeRepository;
    }
    public ViewResult Index()
    {
        var model = _employeeRepository.GetAllEmployee();
        return View(model);
    }
    // Rest of the code
}

There are 2 implementations for IEmployeeRepository interface. How does the application know which implementation to use. The answer to this is in Startup class in Startup.cs file. With the following line of code, ASP.NET Core provides an instance of SQLEmployeeRepository class when an instance of IEmployeeRepository is requested. We are using AddScoped() method because we want the instance to be alive and available for the entire scope of the given HTTP request. For another new HTTP request, a new instance of SQLEmployeeRepository class will be provided and it will be available throughout the entire scope of that HTTP request.

We discussed the difference between AddSingleton(), AddScoped() and AddTransient() methods in detail in Part 44 of ASP.NET Core Tutorial.

public void ConfigureServices(IServiceCollection services)
{
    // Rest of the code
    services.AddScoped();
}

Throughout our entire application, in all the places where IEmployeeRepository is injected an instance of SQLEmployeeRepository is provided. If you want your application to use a different implementation instead, all you need to change is the following one line of code.

services.AddScoped();

31
Q

We are using AddScoped() method because we want the instance to be alive and available for the entire scope of the given HTTP request. For another new HTTP request, a new instance of SQLEmployeeRepository class will be provided and it will be available throughout the entire scope of that HTTP request.

A

We are using AddScoped() method because we want the instance to be alive and available for the entire scope of the given HTTP request. For another new HTTP request, a new instance of SQLEmployeeRepository class will be provided and it will be available throughout the entire scope of that HTTP request.

32
Q

Benefits of Repository Pattern

A

The code is cleaner, and easier to reuse and maintain.

Enables us to create loosely coupled systems. For example, if we want our application to work with oracle instead of sql server, implement an OracleRepository that knows how to read and write to Oracle database and register OracleRepository with the dependency injection system.

In an unit testing project, it is easy to replace a real repository with a fake implementation for testing.

33
Q

startup.cs in asp.net core

A

This class is described by its name: startup. It is the entry point of the application. It configures the request pipeline which handles all requests made to the application. The inception of startup class is in OWIN (Open Web Interface for.NET) application that is specification to reduce dependency of application on server.

Is Startup Class mandatory?

Yes, this class is mandatory in ASP.net core application. It can have any access modifier (public, private, internal). This is the entry point of the ASP.net application. It contains application configuration related items.

Must the name of class be “Startup”?

No, it is not necessary that the class name be “Startup”. The ASP.net core application is a Console app and we have to configure a web host to start listening. The “Program” class does this configuration.

Following is sample code for Program class,

ollowing is sample code for Program class,
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup()
.Build();
host.Run();
}
}
The web host is created in the main method of the Program class and here we have configuration of startup class using method “UseStartup”. So it is not necessary that class name is “Startup”.

34
Q

startup class constructor

A
Following is a typical startup class example.
public class Startup   
{  
    public void Configure(IApplicationBuilder app)  
    {  
}  
public void ConfigureServices(IServiceCollection services)  
{  
     }       
}  
Startup Class Constructor 
We can also specify constructor of the startup class. The startup class has constructor with one or three parameters.
public Startup(IHostingEnvironment env)      
{   

}

public Startup(IApplicationBuilder appenv, IHostingEnvironment env,  ILoggerFactory loggerFactory)  
{  

}

IApplicationBuilder is an interface that contains properties and methods related to current environment. It is used to get the environment variables in application.
IHostingEnvironment is an interface that contains information related to the web hosting environment on which application is running. Using this interface method, we can change behavior of application.

IloggerFactory is an interface that provides configuration for the logging system in Asp.net Core. It also creates the instance of logging system.

The startup class contains two methods: ConfigureServices and Configure.

35
Q

ConfigureServices Method

A

Declaration of this method is not mandatory in startup class. This method is used to configure services that are used by the application. When the application is requested for the first time, it calls ConfigureServices method. This method must be declared with a public access modifier, so that environment will be able to read the content from metadata.

ASP.net core has built-in support for Dependency Injection. We can add services to DI container using this method. Following are ways to define ConfigureServices method in startup class.
public void ConfigureServices(IServiceCollection services)  
{  
        services.AddMvc();  
}   
In case of specific class or library of project that would like to add to DI container, we will use the IserviceCollection. In the above example, I have just add MVC service to the ConfigureServices method.
36
Q

Configure Method

A

his method is used to define how the application will respond on each HTTP request i.e. we can control the ASP.net pipeline. This method is also used to configure middleware in HTTP pipeline. This method accept IApplicationBuilder as a parameter. This method may accept some optional parameter such as IHostingEnvironment and ILoggerFactory. Whenever any service is added to ConfigureServices method, it is available to use in this method.
public void Configure(IApplicationBuilder app)
{
app.UseMvc();

app.Run(context => {  
    return context.Response.WriteAsync("Hello Readers!");  
});   }   In the above example, I have added "UseMvc" method, so system will know MVC framework need to use to handle user requests. With this method, we can also pass some additional option parameters.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
{  
    loggerFactory  
        .AddConsole()  
        .AddDebug();  
    app.UseMvc();  
    app.Run(context => {  
        var logger = loggerFactory.CreateLogger("TodoApi.Startup");  
        return context.Response.WriteAsync("Hello Readers!");  
    });  
} 

In the above example, I have added the logger console and the debug logger and MVC service. The app.Run method adds a terminal middleware delegate to the application’s request pipeline.
Summary

The Startup class is mandatory and it is the entry point of the application. With the help of this class we can configure the environment in our ASP.net Core application. We can use Constructor and two different methods: ConfigureServices and Configure for setting up the environment. This class creates services and injects services as dependencies so the rest of the application can use these dependencies. The ConfigureServices used to register the service and Configure method allow us to add middleware and services to the HTTP pipeline. This is the reason ConfigureServices method calls before Configure method.

37
Q

Configure() - Register Dependent Types (services/class) with the IOC Container here (Dependency Injection Container)
and
ConfigureServices()- Configure HTTP request pipeline (Middleware) here

A

https://www.tutorialsteacher.com/core/aspnet-
core-startup
https://www.c-sharpcorner.com/article
/understanding-startup-class-in-asp-net-core/#:~:text=It%20is%20the%20entry%20point,
dependency%20of%20application%20on%20server.
As you can see, the Configure method includes three parameters IApplicationBuilder, IHostingEnvironment, and ILoggerFactory by default. These services are framework services injected by built-in IoC container.

At run time, the ConfigureServices method is called before the Configure method. This is so that you can register your custom service with the IoC container which you may use in the Configure method.

The Startup class must include a Configure method and can optionally include ConfigureService method

38
Q

in output window we have lot logging dumped by dotnet.exe process and messages related

A

in project.csproj
we see that OutOfProcess

which mean dotnet.exe runs

for inProcess - you see IIS express.exe logs all this information

Tools - options - debugs- you could remove all the messages logging to output window

39
Q

HTML.Encode() - What/How does it prevent scripting security problems in ASP .NET?

Server.HTMLEncode Method

A

The HTMLEncode method applies HTML encoding to a specified string. This is useful as a quick method of encoding form data and other client request data before using it in your Web application. Encoding data converts potentially unsafe characters to their HTML-encoded equivalent.

If the string to be encoded is not DBCS, HTMLEncode converts characters as follows:

The less-than character () is converted to >.

The ampersand character (&) is converted to &.

The double-quote character (“) is converted to “.

Any ASCII code character whose code is greater-than or equal to 0x80 is converted to , where is the ASCII character value.

If the string to be encoded is DBCS, HTMLEncode converts characters as follows:

All extended characters are converted.

Any ASCII code character whose code is greater-than or equal to 0x80 is converted to , where is the ASCII character value.

Half-width Katakana characters in the Japanese code page are not converted.

40
Q

Denial of Service

A

https://docs.microsoft.com/en-us/windows-hardware/drivers/ifs/denial-of-service

A denial-of-service occurs when access to a particular service should have been granted, but in fact was improperly rejected. For example, any operation that an unprivileged application can perform that causes the system to become unusable is effectively a denial-of-service. This would include any operation or sequence of operations that:

Crashes the system.

Causes premature termination of threads or processes.

Creates a deadlock condition. A deadlock occurs when two or more threads are stopped waiting in a permanent state of stalemate. Each thread is waiting for a resource held by one of the other threads.

Creates a live lock condition. A live lock can occur when two or more processors cannot progress because they are waiting to acquire a resource (typically a lock on a queue) and the thread which owns that resource is in a similar non-progressing state.

Such problems often arise within drivers because they contain latent bugs that can be exploited by normal applications. Exploits of this type can be simple and are difficult to protect against. Common causes of such problems in drivers include:

Improper user buffer validation.

Buffer overflow or underflow.

41
Q

Buffer in general and for files

A
https://techterms.com/definition/buffer#:~:text=
The%20
purpose%20of%20a%20buffer,and%20
then%20begin%20to%20
play.&amp;text=Most%20hard%20disks
%20use%20a,
the%20data%20on%20the%20disk.

A buffer contains data that is stored for a short amount of time, typically in the computer’s memory (RAM). The purpose of a buffer is to hold data right before it is used. For example, when you download an audio or video file from the Internet, it may load the first 20% of it into a buffer and then begin to play. While the clip plays back, the computer continually downloads the rest of the clip and stores it in the buffer. Because the clip is being played from the buffer, not directly from the Internet, there is less of a chance that the audio or video will stall or skip when there is network congestion.

Buffering is used to improve several other areas of computer performance as well. Most hard disks use a buffer to enable more efficient access to the data on the disk. Video cards send images to a buffer before they are displayed on the screen (known as a screen buffer). Computer programs use buffers to store data while they are running. If it were not for buffers, computers would run a lot less efficiently and we would be waiting around a lot more.

42
Q

File signature

A

https://www.filesignatures.net/index.php?search=jpeg&mode=EXT

File Signature or Magic Number is a protocol set of constant numerical and text values used to identify file format. In other words, every file type requires a unique signature in order for an operating system to recognize it, classify it and show it to an end user.

43
Q

Difference between Buffer & Stream in C# [duplicate]

A

As I said in my comment, the nutshell difference between a buffer and a stream is that a stream is a sequence that transfers information from or to a specified source, whereas a buffer is a sequence of bytes that is stored in memory. For example:

FileStream stream = new FileStream("filepath.txt", FileMode.OpenOrCreate);
Opens a stream to a file. That stream can be read from, written to, or both. As it doesn't require any additional memory, it's lightweight and fast, but arbitrarily referencing a particular set of data in the source can be cumbersome. Streams also benefit from being a connection rather than a discrete set of data, so you don't need to know the size of the data beforehand.

Conversely:

byte[] fileContents = File.ReadAllBytes(“filepath.txt”);
Reads all the bytes of a file into memory. This is handy for when you need to manipulate the entire file at once, or keep a “local copy” for your program to hold onto so the file can be free for other uses. Depending on the size of the source and the amount of available memory, though, a buffer containing the entire file might not be an option.

This is just a barebones explanation, though. There are more thorough ones out there, For example, as Marc Gravell puts it:

Many data-structures (lists, collections, etc) act as containers - they hold a set of objects. But not a stream; if a list is a bucket, then a stream is a hose. You can pull data from a stream, or push data into a stream - but normally only once and only in one direction (there are exceptions of course). For example, TCP data over a network is a stream; you can send (or receive) chunks of data, but only in connection with the other computer, and usually only once - you can’t rewind the Internet.

Streams can also manipulate data passing through them; compression streams, encryption streams, etc. But again - the underlying metaphor here is a hose of data. A file is also generally accessed (at some level) as a stream; you can access blocks of sequential data. Of course, most file systems also provide random access, so streams do offer things like Seek, Position, Length etc - but not all implementations support such. It has no meaning to seek some streams, or get the length of an open socket.

44
Q

byte order mark (BOM)

A

A byte order mark (BOM) is a sequence of bytes used to indicate Unicode encoding of a text file. The underlying character code, U+FEFF, takes one of the following forms depending on the character encoding.[1]

Bytes	Encoding Form
EF BB BF	UTF-8
FE FF	UTF-16, big-endian
FF FE	UTF-16, little-endian
00 00 FE FF	UTF-32, big-endian
FF FE 00 00	UTF-32, little-endian
BOM use is optional. If used, it must be at the very beginning of the text. The BOM gives the producer of the text a way to describe the encoding such as UTF-8 or UTF-16, and in the case of UTF-16 and UTF-32, its endianness. The BOM is important for text interchange, when files move between systems that use different byte orders or different encodings, rather than in normal text handling in a closed environment.
45
Q

Kestrel web server implementation in ASP.NET Core

A

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-3.1

Kestrel is a cross-platform web server for ASP.NET Core. Kestrel is the web server that’s included by default in ASP.NET Core project templates.

Kestrel can be used by itself or with a reverse proxy server, such as Internet Information Services (IIS), Nginx, or Apache. A reverse proxy server receives HTTP requests from the network and forwards them to Kestrel.

46
Q

Proxy vs Reverse Proxy

A

Proxy:Server does not know who the client is connecting with the proxry
user sends requeset to Proxy - Proxy sends request to server
advantages:
anonymity of the client
Caching
Blocking unwanted sites
GeoFencing restricting based on country ip
your ISP - internet service provider is a proxy

Reverse Proxy: Client does not know which server it is connecting to
benefits:
load balancing
caching
Isolating Internal Traffic
Logging
Canary Deployment (release new features to only one of the server to who ever is directed to that server will see the feature)

47
Q

IFormFile Interface

A

Represents a file sent with the HttpRequest.

Properties
PROPERTIES
ContentDisposition
Gets the raw Content-Disposition header of the uploaded file.

ContentType
Gets the raw Content-Type header of the uploaded file.

FileName
Gets the file name from the Content-Disposition header.

Headers
Gets the header dictionary of the uploaded file.

Length
Gets the file length in bytes.

Name
Gets the form field name from the Content-Disposition header.

Methods
METHODS
CopyTo(Stream)
Copies the contents of the uploaded file to the target stream.

CopyToAsync(Stream, CancellationToken)
Asynchronously copies the contents of the uploaded file to the target stream.

OpenReadStream()
Opens the request stream for reading the uploaded file.

48
Q

For file loading

A

we could access the file with model binding the UI name should be same as the view Model property name
we nedd have enctype=”multipart/form-data”

if we specify the property type as IFormFile, then the razor views generated by asp.net core will automatically create file control in UI

49
Q

To get to wwwroot folder

A

private readonly IHostingEnvironment hostingEnvironment;

        public HomeController(IEmployeeRepository employeeRepository,
                              IHostingEnvironment hostingEnvironment)
        {
            _employeeRepository = employeeRepository;
            this.hostingEnvironment = hostingEnvironment;
        }
50
Q

combining paths for root and images using path class

A
// The image must be uploaded to the images folder in wwwroot
                    // To get the path of the wwwroot folder we are using the inject
                    // HostingEnvironment service provided by ASP.NET Core
                    string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
51
Q

To make sure the file name is unique

A
// To make sure the file name is unique we are appending a new
                    // GUID value and and an underscore to the file name
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);
52
Q

CopyTo() method provided by IFormFile interface to

A
// Use CopyTo() method provided by IFormFile interface to
                    // copy the file to wwwroot/images folder
                    model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));

open the file stream in create mode

53
Q

launchsettings.json file

A

https://www.youtube.com/watch?v=u2S4TkkACVc
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-5.0
each profile is to run

The value of commandName can specify the web server to launch. commandName can be any one of the following:

IISExpress : Launches IIS Express.
IIS : No web server launched. IIS is expected to be available.
Project : Launches Kestrel.

The launchSettings.json file:

Is only used on the local development machine.
Is not deployed.
contains profile settings.

54
Q

Identity Server

A

https://code-maze.com/identityserver-4-series/
OAuth 2.0 - PKCE:
https://www.youtube.com/watch?v=Gtbm5Fut-j8
OAuth Grant Types:
https://www.youtube.com/watch?v=1ZX7554l8hY&t=301s