Tech Point Fundamentals

Sunday, October 23, 2022

.Net Core Interview Questions and Answers - Part 08

ASP.Net Core Interview Questions and Answers - Part 08

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 8th 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 to the current part:






ASP.Net Core Interview Questions and Answers - Part 08


Q073. What is the use of the launchSettings.json file in ASP.NET Core?

This JSON file contains project-specific settings associated with each profile Visual Studio is configured to use to launch the application, including any environment variables that should be used. 

We can define project-specific settings associated with each profile Visual Studio is configured to launch the application, including any environment variables that should be used. You can define the framework for your project for compilation and debugging for specific profiles. 



You can change settings for each profile via right-click on the Project and then selecting properties.

launch-setting-json

ASP.NET 5 ships with support for 3 different servers:

  1.                 Microsoft.AspNet.Server.IIS
  2. Microsoft.AspNet.Server.WebListener (WebListener)
  3. Microsoft.AspNet.Server.Kestrel (Kestrel)

So by default, there will be 3 different profiles. However, it also depends on the commands section of project.json




Q074. What is the use of a global.json file in ASP.NET Core?

We can define solution-level settings in the global.json file. The settings defined in global.json implies to all the projects in the solution. 

global-setting-json-file

Here the project property defines the locations of the solution’s source code. Visual Studio 2015, specifies two locations for projects in the solution src and test. 



The src contains the actual application and the test project contains any test. If you have selected the option of creating a test project while creating the solution for the first time.

The second property SDK specifies the version of the DNX (.Net Execution Environment) that Visual Studio will use when opening the solution. Specifying the version has an advantage as while working on multiple projects, you can target different versions of ASP.NET 5.

In traditional .Net projects when you build your application, then all your .dll are placed in the bin directory in the same path, where your project is. But now in .Net Core, it is moved to another location called "artifact". The build artifact is now placed in the “Artifact” folder which makes life easy while excluding things from source control.



Q075. What is the use of the appsettings.json file in ASP.NET Core? 

The appsettings.json file is used to define application-related settings like connection string, logging settings, or any other custom key which we used to define in the web.config file.

Traditional ASP.NET stores application configuration settings in web.config files but ASP.NET Core uses AppSettings.json to store custom application settings.

appsetting-jsonfile





Q076. What is the use of the bundleconfig.json file in ASP.NET Core?

This file is used to define the configuration for bundling and minification for the project. You can define the configuration for bundling and minification for the project by using the bundleconfig.json file. 

bundle-json-file





Q077. What is the use of the project.json file in ASP.NET Core? How it is different from the project.lock.json file?

Initially, this file is used to define project settings and server-side dependencies.  In ASP.NET Core project.json is used for project metadata, compilation information, and dependencies. 

It largely replaces the web.config file from previous versions of ASP.NET.  Asp.net Core uses the Project.JSON file for storing all project-level configuration settings.

project-config-json-file




But now in the new versions of the .Net code, Microsoft has decided to move .NET Core projects to .csproj/MSBuild so all .NET projects will use the same tooling and build system. Starting in .NET Core RTM/tooling preview 2, Visual Studio automatically renamed the .xproj files as .csproj.

project.lock.json:

The project.lock.json file is generated in the process of restoring the NuGet packages in projects that use project.json. It holds a snapshot of all the information that is generated as NuGet walks the graph of packages and includes the version, contents, and dependencies of all the packages in your project.

The build system uses this to choose packages from a global location that are relevant when building the project instead of depending on a local packages folder in the project itself. This results in faster build performance because it's necessary to read-only project.lock.json instead of many separate .nuspec files.

project.lock.json is automatically generated on package restore, so it can be omitted from source control by adding it to the .gitignore and .tfignore files.




Q078. What is the use of the bower.json file in ASP.NET Core?

The bower is a package manager for the web. Bower manages components that contain HTML, CSS, JavaScript, fonts, or even image files. Bower installs the right versions of the packages you need and their dependencies.

Bower doesn’t concatenate or minify code or do anything else – it just installs the right versions of the packages you need and their dependencies. With ASP.NET 5 web projects jQuery and bootstrap packages are already installed and bower, gulp, and NPM are already in place.

With ASP.NET core, jQuery and bootstrap packages are already installed and bower, gulp, and NPM are already in place. Client-side packages are listed in the bower.json file.




{
  "name": "ASP.NET",
  "private": true,
  "dependencies": {
    "bootstrap": "3.3.5",
    "jquery": "2.1.4",
    "jquery-validation": "1.14.0",
    "jquery-validation-unobtrusive": "3.2.4"
  }
}

Client-side packages are listed in the bower.json file.  Visual Studio watches the bower.json file for changes. Upon saving, the bower install command is executed. 

There is another file named “ .bowerrc” which defines the location at which the bower package needs to be installed. Open it, and notice that the directory property is set to “wwwroot/lib”.



Q079. What is the use of package.json in ASP.NET Core?

One of the JSON configuration files is Package.json and it is the place for npm modules. When you won’t find this file in solution explorer for your ASP.NET Core project, as by default, this file is hidden. 

So click on the “Show all files” option in solution explorer to view it. You can also see it by expanding Dependencies folder -> and right-click on the npm folder and selecting “Open Package.json”.

NPM is another package manager like bower. But npm is used for installing Node js modules whereas bower is used for managing front-end components like HTML, CSS, JS, etc. 



In ASP.NET 5 project template pre-configures NPM, Gulp, and bower.  Gulp is a JavaScript task runner which is used to automate various tasks like minification and bundling of js and CSS, checking errors in JS, etc. Since Gulp is a node.js module so npm is used. So node.js modules are listed in package.json.

{
  "name": "ASP.NET",
  "version": "0.0.0",
  "devDependencies": {
"gulp": "3.8.11",
"gulp-concat": "2.5.2",
"gulp-cssmin": "0.1.7",
"gulp-uglify": "1.2.0",
"rimraf": "2.2.8"
  }
}




Q080. What is the appsettings.Environment.json file in .Net Core?

By default, an appsettings.json file and appsettings.development.json file are created in the .NET Core project.

We can create multiple app settings files based on the environment in .Net Core like appsettings.Development.json, appsettings.Prod.json, etc based on different environments.

The environment version of the file is loaded based on the IHostingEnvironment.EnvironmentName. The appsettings.{Environment}.json values override keys in appsettings.json.

In development, appsettings.Development.json configuration overwrites values found in appsettings.json. In production, appsettings.Production.json configuration overwrites values found in appsettings.json. For example, when deploying the app to Azure.

Using the default configuration, the appsettings.json and appsettings.{Environment}.json files are enabled with reloadOnChange: true. Changes made to the appsettings.json and appsettings.{Environment}.json files after the app starts are read by the JSON configuration provider.



Q081. What is the Environment Variable in ASP.NET Core? How can you read the Environment Variables?

Environment variables are a set of dynamic named values that can affect the way running processes will behave on a computer. There are various environment variables present in ASP.NET 5 which can be set that will affect various parts of the runtime.  The ASPNET_ENV variable actually defines the environment the application is currently running in.

ASP.NET Core uses an environment variable called ASPNETCORE_ENVIRONMENT to indicate the runtime environment. The value of this variable can be anything as per the requirement but typically it can be Dev, Staging, or Prod. 

Please note that the value is case-insensitive in Windows and Mac OS but it is case-sensitive on Linux. Though the value for ENV is case insensitive when you try to define the same key again for a different value, you will get the duplicate key error.

You can multiple environments by using the environment variables. ASP.NET Core uses environment variables to configure application behavior based on the runtime environment.



In Visual Studio, we can set ASPNETCORE_ENVIRONMENT in the debug tab of project properties. Open project properties by right-clicking on the project in the solution explorer and selecting Properties:

Project Right Click Context Menu => Debug => Environment Variables.

EnvironmentVariable

This value will be saved in the launchSettings.json file as well. So You may also change the environment variable directly in launchSettings.json as well.



Reading Environment Variable at Runtime:

We can use the value of an environment variable in our code to execute some additional code based on its value. The Startup class is used for bootstrapping the application and loading all your configurations. You can retrieve your environment variable which you can set in launchSettings.json:

static void ConfigConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder config)
{
var env = ctx.HostingEnvironment;
config.SetBasePath(env.ContentRootPath)
.AddEnvironmentVariables()
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true);
config.Build();
}

The IHostingEnvironment service includes the EnvironmentName property which contains the value of the ASPNETCORE_ENVIRONMENT variable. The IHostingEnvironment service is provided by the ASP.NET hosting layer and can be used anywhere in your application via Dependency Injection.



ASP.NET Core also includes extension methods to check the environment such as IsDevelopment(), IsStating(), IsEnvironment() and IsProduction().

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsEnvironment("Development"))
{
            // Use Dev connection string
}
// OR 
if (env.IsDevelopment())
{
}
if (env.IsProduction())
{
              // Use Prod connection string
}




Q082. How to use multiple startup files based on environments in ASP.NET Core?

In ASP.NET 5, the Startup class is used for bootstrapping the application and loading all your configuration including environment variables as well. So there is also a convention that exists for Startup.cs and ASPNET_ENV values. 

You are allowed to create a Startup class with an environment variable name like Startup{EnvironmentName} for example StartupDev, StartupProd, etc. 

So you can have StartupDevelopment, StartupStaging, and StartupProduction, and based on the ASPNET_ENV environment variable value, that Startup class is used. Thus, it gives you the flexibility to configure Startup settings for different environments.



Q083. What is DbContext in .Net Core? How can you define the database connection string in ASP.Net Core?

DbContext class act as middleware or gateway to the database. It comes under Microsoft.EntityFrameworkCore namespace.

public partial class MyAppDBContext : DbContext
{  
public MyAppDBContext(DbContextOptions<MyAppDBContext> options) :  base(options)
{             
}
}

Defining a database connection string in .Net Core and reading back into C# code is a little different from the traditional ASP.Net framework.  



In .Net core, we don’t have web.config like ASP.Net framework. In ASP.Net Core we have JSON-based files to manage database connection strings. We define the connection string in the appsetting.json file:

{
  "ConnectionStrings": {
"DefaultConnection": "Server=localhost\SQLEXPRESS;Database=Test;Trusted_Connection=Yes;Integrated Security=SSPI;"
  },
  "Logging": {
"LogLevel": {
  "Default": "Warning"
}
  },
  "AllowedHosts": "*"
}



If you are using entity framework core then, get the connection name in ConfigureServices() method defined in the startup.cs file:

services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

After that, use the below code to read and use the database connection string defined in the appsettings.json file:

var dbconfig = new ConfigurationBuilder()
   .SetBasePath(Directory.GetCurrentDirectory())
   .AddJsonFile("appsettings.json").Build();

if (!string.IsNullOrEmpty(dbconfig.ToString()))
{
string dbconnectionStr = dbconfig["ConnectionStrings:DefaultConnection"];
}


To Be Continued Part-09...


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.