Tech Point Fundamentals

Sunday, October 30, 2022

.Net Core Interview Questions and Answers - Part 09

ASP.Net Core Interview Questions and Answers - Part 09

AspDotNetCoreInterviewQuestionsAndAnswers

Are you preparing for the .Net Core Interview? If yes, then you are at the right place. This is the ASP.Net Core Interview Questions and Answers article series. Here we will see the Top 150+ .Net Core Interview Questions with Answers. 

Please visit our YouTube Channel for Interviews and other videos by below link:




Please read the complete Design Pattern, C#, MVC, WebAPI, and .Net Framework Interview Questions and Answers article series here.




Introduction


This is the 9th part of the .Net Core Interview Questions and Answers article series. Each part contains ten .Net Core Interview Questions. Please read all the .Net Interview Questions list here.

I will highly recommend to please read the previous parts over here before continuing the current part:






ASP.Net Core Interview Questions and Answers - Part 09


Q084. How can you read values from JSON configuration files?

Before reading any JSON config file please note that the Order in which configuration files are loaded matters. If two configuration sources contain similar keys, the one which loads last wins.

To read the JSON configuration file, we need to add "Microsoft.Extensions.Configuration" and "Microsoft.Extensions.Configuration.Json" libraries as a dependency.

To access the configuration information within the Startup class, you need to use the IConfiguration service which is provided by the ASP.NET Core Framework. This IConfiguration interface belongs to Microsoft.Extensions.Configuration namespace.

Since the new version of ASP.NET has built-in support for dependency injection, just inject the IConfiguration service through the constructor of the Startup class. 



public class Startup 
private IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;
}       
 } 

We can also inject it into the constructor of the service class or controller class as well directly. 

public void ConfigureServices(IServiceCollection services)  
{             
services.AddMvc();  
services.AddSingleton<IConfiguration>(Configuration);  

Now you can access it from the controller:

IConfiguration _configuration;  
public HomeController(IConfiguration configuration)  
{  
_configuration = configuration;  
var configVal = _configuration["key"]; // Reading Direct Value
var name = _configuration["Employee:Name"]; // Reading Complex values
}  







Q085. What is the difference between GetSection(),  GetValue() and Value in ASP.NET Core?

Generally, the configuration remains in a simple key-value structure or might be in a hierarchical structure when using external files.
We can get a simple configuration value by using the key name. 

var configVal = _config["key"];

If the configuration value is in a hierarchical structure, it can be retrieved using a ":" separated key, starting from root of the hierarchy. The Configuration API reads hierarchical configuration data by flattening the hierarchical data with the use of a delimiter in the configuration keys.

var name = _config["Role:Name"]; 
var defaultLogLevel = _config["Logging:LogLevel:Default"];

But apart from this, you can also use GetSection, Value, and GetValue methods as well to read the config values. You can use the GetSection & Value method to read a setting. You need to use the colon (:) to separate each section.



GetValue() Method:

ConfigurationBinder.GetValue extracts a single value from the configuration with a specified key and converts it to the specified type:

strValue = _config.GetValue<string>("customOptions:complexOption:Option1");

You can also specify the default value if the config value is not found. In the below code, if NumberKey isn't found in the configuration, the default value of 99 is used.

var number = _config.GetValue<int>("NumberKey", 99);



GetSection() Method:

getsection



IConfiguration.GetSection returns a configuration subsection with the specified subsection key. 

var sec1Config = _config.GetSection("section1");
var sec2 = _config.GetSection("section2:subsection0");

You can also chain the getSection:

strValue = _config.GetSection("customOptions").GetSection("complexOption").GetSection("Option1").Value;

GetSection never returns null. If a matching section isn't found, an empty IConfigurationSection is returned. When GetSection returns a matching section, Value isn't populated. A Key and Path are returned when the section exists.



GetChildren() and Exists() Method:

You can check the existence of a section by using the Exists method. The GetChildren method is used to get the subSection of a section.

var currentSection = Config.GetSection("section2");

if (currentSection.Exists())
{
var children = currentSection.GetChildren();
}



Parsing values in GetSection:

You can use the parse method to get the correct type of config value:

boolVal = bool.Parse(_config.GetSection("customOptions:BoolOption").Value);

You can also use the built-in GetValue method to parse the type:

boolVal = _config.GetValue<bool>("customOptions:BoolOption");
strVal = _config.GetSection("customOptions").GetSection("complexOption").GetValue<String>("Option1");




Q086. What is the Options Pattern in ASP.NET Core? What is Option Class?

Options Pattern is another way by which we can read the configurations. This helps us to bind it to a class instance & also use DI to inject it into the class constructor. The preferred way to read hierarchical configuration data is using the options pattern.

 The Options Pattern enables us to use custom option classes to represent a group of related settings. Options Pattern allows you to access related configuration settings in a Strongly typed way using some classes.  

One of the key advantages of using the .NET configuration abstractions is the ability to bind configuration values to instances of .NET objects. This enables the options pattern, which uses classes to provide strongly typed access to groups of related settings. .NET configuration provides various abstractions. 

The “Microsoft.Extensions.Options.ConfigurationExtensions” dependency contains the extension method for IServiceCollection.Configure. We need to add this dependency in the project.json file. 



Option Class:

"Position": {
    "Title": "Editor",
    "Name": "Joe Smith"
  }

For reading the above JSON config, first, you have to create the options class whose properties match the configuration options. The Options class must have a public read-write property that is defined for each setting and the class must not take any parameters.

OptionClass



The Options class must follow the following:

  1. Must be non-abstract with a public parameterless constructor.
  2. All public read-write properties of the type are bound.
  3. Fields are not bound. In the above example Position is not bound. The Position field is used so the string "Position" doesn't need to be hard coded in the app when binding the class to a configuration provider.

After that Import the namespace Microsoft.Extensions.Options and you can inject the configuration where you want either in any service class, controller, or ConfigureServices of the startup class.



Using IOptions<TOptions> accessor service, we can inject Options into our application. To set up the IOptions<TOptions> service, we need to call the "AddOptions" extension method during startup in our ConfigureServices method of the Startup class.

public void ConfigureServices(IServiceCollection services)  
{             
services.AddOptions();    
services.Configure<PositionOptions>(Configuration.GetSection("Position"));
services.AddSingleton<IConfiguration>(Configuration);  
services.AddMvc();  
}

After that, you can use the config values in the controller as well:

private readonly positionOptionsConfiguration _positionOptions;
public HomeController(IOptions<PositionOptions> options)
{
_positionOptions = options.Value;
}



Inject the IOptions<T> where T is the configuration class (PositionOptions.) that we want to inject. IOptions<T> does not load the configuration data after the app has started. It is also registered as Singleton and hence can be injected into any service.

You can also use the Bind() method to use that in any class or method without injecting into the startup class.

var positionOptions = new PositionOptions();
Configuration.GetSection(PositionOptions.Position).Bind(positionOptions);   
var result = Content($"Title: {positionOptions.Title} " +  $"Name: {positionOptions.Name}");

In this case by default, changes to the JSON configuration file after the app has started are read. But in the previous case when you have injected in the startup class, changes to the JSON configuration file after the app has started are not read. To read changes after the app has started, use IOptionsSnapshot.



Q087. What is the Bind() method in ASP.NET Core? How you can read an array configuration file in .Net Core?

Reading each & every single config setting is a little time-consuming. Instead, we can read the entire section of values using the bind method. This also gives us a strongly typed configuration object.

For example, if we have an array in that case it will be very difficult to read one by one, SO in that case, we can bind the complete array configs into a compatible class object.

customOptionsConfiguration _customSettings = new customOptionsConfiguration();
_config.GetSection("customOptionsClass").Bind(_customSettings);

You can use the get method:

var _customSettings= _config.GetSection("customOptions").Get<customOptionsConfiguration>();



Reading Array JSON Configs:

The ConfigurationBinder.Bind supports binding arrays to objects using array indices in configuration keys. Any array format that exposes a numeric key segment is capable of array binding to a POCO class array.

"wizards": [   
{      
"Name": "Alex",
"Age": "30"    
},    
{      
"Name": "Thomas",
         "Age": "27"    
}
]



The ASP.NET Core adds the keys based on the number to each flattened element. It looks like this:

        wizards:0:Name= "Alex"
wizards:0:Age= "30"
wizards:1:Name= "Thomas"
wizards:1:Age= "27"


The bound array indices are continuous and not bound to the configuration key index. The configuration binder isn't capable of binding null values or creating null entries in the bound objects.

So you can read them easily:

strVal = _config.GetValue<string>("wizards:0:Name");

You can also use the options pattern to read the array JSON as well.




Q088. How you can read an XML configuration file in .Net Core? What is XMLConfiguration Provider in .Net Core?

The default loader in ASP.NET Core does not load the XML files. The XmlConfigurationProvider loads configuration from XML file key-value pairs at runtime.

XML-File



You need to use the AddXmlFile extension method to load it into the program.cs file. You can also clear all the configuration providers and only adds several required configuration providers only.

xml-builder

Now you can access the values:

var myKeyValue = _config["MyKey"];
var title = _config["Position:Title"];
var name = _config["Position:Name"];
var defaultLogLevel = _config["Logging:LogLevel:Default"];




Q089. How you can read the JSON configuration file in .Net Core? What is JSON Configuration Provider in .Net Core?

The JsonConfigurationProvider load the configuration from JSON file key-value pairs. It provides some additional options like whether the file is optional and whether the configuration is reloaded if the file changes or not.

builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("MyConfig.json",
   optional: true,
   reloadOnChange: true);
});



Here:
optional: true: specify that file is optional.
reloadOnChange: true: specify that the file is reloaded when changes are saved.

It 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.



Q090. How can you use the configuration in MVC View in .Net Core? 

You can use configurations by using the IConfiguration in the view file:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

Configuration value for 'MyKey': @Configuration["MyKey"]




Q091. What is an In-Memory configuration provider in .Net Core? 

The MemoryConfigurationProvider uses an in-memory collection as configuration key-value pairs. The new configuration framework of ASP.NET Core also supports in-memory configuration. 

In this type of configuration, the values are directly stored in the code and the later part of the application uses this configuration. 

public Startup()  
{  
var builder = new ConfigurationBuilder();  

var dic = new Dictionary<string, string>  
{  
{"Profile:Role1", "SuperAdmin"},  
{"Profile:Role2", "Admin"},  
{"Profile:Role3", "Annonymous"}  
};  
builder.AddInMemoryCollection(dic);  
Configuration = builder.Build();  
} 

Using Configuration["Profile: Role1"], we can get the value of Role1 of the profile configuration. We can also bind this value with a custom model-like option pattern.

 var Role1 = Configuration["Position:Role1"];
 var Role2 = Configuration["Position:Role2"];




Q092. How can you read config values from CLI in .Net Core? 

Using the default configuration, the CommandLineConfigurationProvider load configuration from command-line argument key-value pairs after the following configuration sources:

  1. appsettings.json and appsettings.{Environment}.json files.
  2. App secrets in the Development environment.
  3. Environment variables.

By default, configuration values set on the command-line override configuration values set with all the other configuration providers.



Reading from Command-line arguments:

dotnet run MyKey="Using =" Position:Title=Cmd Position:Name=Cmd_Rick
dotnet run /MyKey "Using /" /Position:Title=Cmd /Position:Name=Cmd_Rick
dotnet run --MyKey "Using --" --Position:Title=Cmd --Position:Name=Cmd_Rick

The key value must follow =, or the key must have a prefix of -- or / when the value follows a space. The key value is not required if = is used.

Within the same command, don't mix command-line argument key-value pairs that use = with key-value pairs that use space.




Q093. What is the difference between Host and App Configuration in ASP.NET Core?

  1. Before the app is configured and started, a host is configured and launched. 
  2. The host is responsible for app startup and lifetime management. 
  3. Both the app and the host are configured using the configuration providers described in this topic. 
  4. Host configuration key-value pairs are also included in the app's configuration. 
  5. Host configuration is provided from Environment variables and Command-line arguments.



To Be Continued Part-10...


Recommended Articles






Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK for regular updates.

    

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.