An Enthusiastic Programmer

Project structure

|

In this episode, we are going to introduce the basic project structures. It’s essential to know the basic web project structure. To better illustrate the structure of the web project, I created an empty ASP.NET CORE project in visual studio 2019.

Alt

Dependencies

You can add references or packages in here.

launchSettings.json

In the properties menu, you will see a launchSettings.json file, which describes how to launch the project. It includes startup options, command, whether to open a browser, environment variables, etc..

Alt

According to this project’s configuration, if you are using the IISExpress to launch this project, then two URLs will be matched, they are https://localhost:44326 and http://localhost:63489. You can use either https://localhost:44326 or http://localhost:63489 to access your website. The difference is that one is HTTPS and the other one is HTTP. the HTTP address is specified explicitly in the "applicationUrl": "http://localhost:63489" field. HTTPS specified in this "sslPort":44326 field. By default, Visual Studio launches the HTTPS one in the browser.

Alt

Looking at your application icons in your desktop, you will find out that the IIS server launched.

Alt

The IIS server is currently hosting your website.

As we can see from the launchSettings.json file that has two profiles, we already introduced the IISExpress one. Another is the WebApplication1, which is similar to the IISExpress. WebApplication1 has two URLs that configured in one line "applicationUrl": "https://localhost:5001;http://localhost:5000".

Because WebApplication1 has nothing to do with the IIS, so WebApplication1 wouldn’t use the IIS as its server, an internal web server hosting instead.

Program.cs

Project.cs is an entry point of the entire application. Essentially, ASP.NET Core is a console project, which executing from the public static void Main(string[] args), where we can create a web host application.

Set Host in ASP.NET Core 3.x

the following is the Program.cs file

    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<Startup>();
                });
    }

The Main() method calls the CreateHostBuilder() static methods with the pre-configured defaults. The CreateHostBuilder() returns an IHostBuilder instance, which can produce an IHost instance by calling the Build() method. When you get the IHost instance, start the web application through the Run() method.

CreateDefaultBuilder

the CreateDefaultBuilder() method in Host.cs returns an IHostBuilder instance, which initialized some default settings, for example, load the content root path, load environment variables, load settings file contents, configure ILoggerFactory, etc..

The following is the source code from dotnet/runtime github:

public static IHostBuilder CreateDefaultBuilder(string[] args)
{
    var builder = new HostBuilder();

    builder.UseContentRoot(Directory.GetCurrentDirectory());
    builder.ConfigureHostConfiguration(config =>
    {
        config.AddEnvironmentVariables(prefix: "DOTNET_");
        if (args != null)
        {
            config.AddCommandLine(args);
        }
    });

    builder.ConfigureAppConfiguration((hostingContext, config) =>
    {
        var env = hostingContext.HostingEnvironment;

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

        if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
        {
            var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
            if (appAssembly != null)
            {
                config.AddUserSecrets(appAssembly, optional: true);
            }
        }

        config.AddEnvironmentVariables();

        if (args != null)
        {
            config.AddCommandLine(args);
        }
    })
    .ConfigureLogging((hostingContext, logging) =>
    {
        var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

        // IMPORTANT: This needs to be added *before* configuration is loaded, this lets
        // the defaults be overridden by the configuration.
        if (isWindows)
        {
            // Default the EventLogLoggerProvider to warning or above
            logging.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Warning);
        }

        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
        logging.AddConsole();
        logging.AddDebug();
        logging.AddEventSourceLogger();

        if (isWindows)
        {
            // Add the EventLogLoggerProvider on windows machines
            logging.AddEventLog();
        }
    })
    .UseDefaultServiceProvider((context, options) =>
    {
        var isDevelopment = context.HostingEnvironment.IsDevelopment();
        options.ValidateScopes = isDevelopment;
        options.ValidateOnBuild = isDevelopment;
    });

    return builder;
}

Startup.cs

An ASP.NET Core application must specify a Startup class, which needs to register in the Program class by using the generic UseStartup<T> method.

webBuilder.UseStartup<Startup>();

Open the Startup.cs file:

Alt

ConfigureServices

The Configureservices method is a place where you can register your dependent classes with the built-in IoC container (ASP.NET Core refers dependent class as a Service). After registering services, you can use it anywhere in the application. The IoC container will inject them automatically.

Configure

The Configure method is a place where you can configure your pipeline by adding middlewares. The pipeline middlewares specify how the app responds to the HTTP request. The middlewares added to the IApplicationBuilder, but it’s not registered in the service container. Hosting creates an IApplicationBuilder and passes it directly to the Configure method.

This is the end of the article. In this article, we have learned the basic web structure. In the next articles, I am going dig into it.

ASP.NET Core

|

ASP.NET Core is an open-source(link), cross-platform, and free platform, which mainly targets run on .NET Core.

ASP.NET Core 3.x only runs on the .NET Core 3.x, whereas ASP.NET Core 2.x runs on .NET Core 2.x as well as .NET Core Framework. more information looks .NET standard.

Run the first ASP.NET Core 3.x Application.

You can run an ASP.NET Core application on Visual Studio as well as on CLI.

On Visual Studio

Download the Visual Studio 2019 editor. If you want to build a different .Net core application, you need to choose a different version. Bellow is the minimum required version of Visual Studio based on the target visual studio version. more

.NET Core SDK version Visual Studio version
3.1 Visual Studio 2019 version 16.4 or higher.
3.0 Visual Studio 2019 version 16.3 or higher.
2.2 Visual Studio 2017 version 15.9 or higher.
2.1 Visual Studio 2017 version 15.7 or higher.

Open Visual Studio 2019, choose create a new project Alt

Choose ASP.NET Core Web Application Alt

Enter your project name and choose the project location Alt

Choose a version and a project template Alt

Here, we chose the ASP.NET Core MVC Views as our template.

Press F5, Start debugging. Alt

On CLI

You can also run this project through CLI, open a command prompt and enter the following code.

dotnet new webapp -o aspnetcoreapp

Trust the development certificate

dotnet dev-certs https --trust

Run the App

cd aspnetcoreapp
dotnet watch run

Then, open https://localhost:5001/ in your browser. Alt

The above code creates a MVC Project, However, there are two project examples, one is MVC, another is Razor. Both are a complete ASP.NET Core project, they are good projects for a newbie. MVC booklist project and Razor Booklist project.

.NET Core

|

.NET Core is an open-source, cross-platform framework. It’s a new version of the .NET Framework(pronounced as dot net).

.NET Framework was developing in the late 1990s by Microsoft. By late 2000, Microsoft released the first beta version of .NET 1.0. The latest version is .NET 4.8 that was released on 18 April 2019 today, and it is also the last version of the .NET branch. Microsoft announced that they are going to stop developing further .NET version in the future.

Alt

Today, the concept of Write once, run everywhere. is very popular. However, the .NET Framework is just permitted to run on windows. So, the .NET Core was born. The .NET Core absorbed almost all advantages of the .NET Framework, and it also adds a lot of new features. The .Net Core 1.0 was released in June 2016 by Microsoft. In 2017, the .NET Core 2.0 was born. In 2019, .NET Core 3.0 was born. Microsoft is planning to release .NET 5 in 2020.

Alt

Below are some of the .NET Core advantages:

Cross-platform

You can run .NET Core project on Windows, Linux, and Mac, etc.

Open-source

.NET Core is Open-Source(link).

Supports a wide range of application types

You can build multiple application types on .NET Core. such as Desktop, Web, Mobile.

CLI

.NET Core includes CIL(common-line interface) for development,

Compatibility

Compatibility with .NET Framework by using .NET started.

ASP.NET Core Tutorial

|

ASP.NET Core is a new version of Microsoft, it’s a open-source web framework which can be run on Windows, Mac, Or Linux.

From Existing Database

|

How to generate context class and entity classes from existing database in Entity Framework Core

Execute Raw SQL

|

entity framework core supports object-oriented operations, also supports raw sql operations, query, insert, delete, update etc…

Fluent API

|

the fluent api is another data annotation implemention which applied more functions.

Fluent API Tutorial

|

Data Annotation - ConcurrencyCheck Attribute

|

the property that applied the ConcurrencyCheck will setup a optimistic concurrency control.

Data Annotation - DatabaseGenerated Attribute

|

DatabaseGeneratedAttribute specifies how the database generates values for a property, to override the default conventions.