Fundamentals of .NET Application Structure
Before we get to configuring the application, let’s take a quick look at the fundamentals of how a .NET application is structured. A .NET application’s architecture is separated into four discrete layers, as shown in Figure 4.1.
FIGURE 4.1 ASP.NET Core application architecture.
At the lowest level, a .NET application has a runtime that is specific to the operating system it runs on. In previous versions of .NET, the runtime was installed with Windows or from Windows Update, and .NET developers were able to rely on a runtime being available on a Windows machine they were targeting. Starting with .NET Core, you can deploy a version of the runtime with your application or use the runtime that is already installed on a server. The runtime includes low-level things like the just-in-time (JIT) compiler, native interop instructions for various operating systems, and the garbage collector.
Building on top of the runtime are the .NET frameworks. These frameworks enable .NET development by adding the basic implementations of .NET objects, such as collections, diagnostics, I/O management, network interactions, and thread management. In prior versions of .NET, these elements are called the Base Class Library (BCL).
Understanding the Development Options
Determining the initial set of options to configure for a web project is important to help get your filesystem configured properly, with designated folders for server-side and client-side development. In this case, you can start by initializing your project inside the empty AspTravlerz folder with the dotnet command-line tool, as follows:
dotnet new empty
This command generates a base web application in the current folder with some initial configuration options set to enable building an application with the new .NET Core framework that works on Mac, Linux, and Windows.
To inspect the AspTravlerz.csproj file that was generated for you, review the contents in Listing 4.1.
Listing 4.1 AspTravlerz.csproj File Generated for an Empty Web Project
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp1.1</TargetFramework> </PropertyGroup> <ItemGroup> <Folder Include="wwwroot\" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" /> </ItemGroup> </Project>
This XML file is based on the long-standard MSBuild project format, but it has been greatly enhanced to make it more human readable and with sensible defaults. In addition, the nonsense that you don’t need has been removed.
The first entry, the Sdk attribute on the Project element, is a pointer for MSBuild to know what type of project you are creating and instructs MSBuild to include additional tasks and properties necessary to build a web project. You can also set this value to Microsoft.NET.Sdk to build with the .NET Core SDK and not include any web-specific features.
The next entries instruct MSBuild to build this application targeting the .NET Core 1.1 runtime version, using the latest patch update available: PropertyGroup with TargetFramework referencing the netcoreapp1.1 metapackage. On Windows machines, you can find this shared framework installed at c:\Program Files\DotNet\Shared\ with a folder bearing the name Microsoft.NETCore.App (the full name of the .NET Core framework) that contains a folder with the same base version number as referenced here: 1.1.x. This metareference to the NETCore.App framework indicates that the highest version with the 1.1 base version number should be used, and that may be 1.1.0, 1.1.1, 1.1.2, or some other patch version starting with 1.1.
If you want to lock down to a specific, explicitly defined version of the framework, you can choose to add a RuntimeFrameworkVersion element with a specific version number, as shown in Listing 4.2:
Listing 4.2 Specifying an Explicit Runtime Framework Version
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp1.1</TargetFramework> <RuntimeFrameworkVersion>1.1.0</RuntimeFrameworkVersion> </PropertyGroup>
The next section of the file is ItemGroup, which contains a single Folder element with the value wwwroot. This element defines the wwwroot content folder that is designed to contain static web content. You should include it here so that the dotnet tool knows about the folder when it comes time to compile and publish the content.
The last group in the .csproj file is the most important entry for you to understand: the collection of dependencies declared as PackageReference elements. ASP.NET Core parses this as a collection of NuGet packages to be used in the project, and the values of those attributes are the name and version numbers of the packages to include. ASP.NET Core delivers all parts of its framework as packages, and the packages’ resolution process dynamically includes the packages that those framework packages depend on. Consequently, you can reference just the Microsoft.AspNetCore package, and all the features it depends on from other packages will automatically be downloaded and made available to your project without cluttering up your project file.
Extending the Project with CLI Tools
The project file and the dotnet command-line tool are extensible, and you can enhance them by adding another section to your project file. So add a new ItemGroup element at the bottom of the file, just above the closing Project tag. Inside ItemGroup, you should add a reference to the Microsoft.DotNet.Watcher.Tools package, using a new element called DotNetCliReference.
DotNetCliReference instructs the dotnet CLI to fetch and reference a NuGet package for use at the command line when in development mode only. The .NET command-line tool will not include these tools when it compiles or when you publish your application to another folder. Listing 4.3 shows the full syntax of this feature you are adding to the project.
Listing 4.3 DotNetCliReference for dotnet watch
<ItemGroup> <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="1.0.0" /> </ItemGroup> </Project>
With this snippet inside your project file, you can run the project in watch mode, in which the Watcher tool automatically restarts the application when any of the project files change. Use the following command from the same folder as the .csproj file in order to start your application in watch mode:
dotnet watch run
Try inserting some spaces or making other changes to a file in the project, save the file, and watch the application restart for you with your changes applied.
Interesting Settings to Consider
There are a number of other settings that you may want to apply to your project file in order to tweak it to behave just right for you. Besides configuring the way that your application is going to be built, you can add a number of automation capabilities to make your development process a breeze.
Specifying a Project Version
By default, the dotnet compiler assigns the 1.0.0 version to your application and embeds that version number in the binary files you create. You can force a version on your project by using the Version element inside PropertyGroup, just like the one that contains the TargetFramework information. In this case, you can specify version 0.4.0 (a reference to Chapter 4) for your project, as shown in Listing 4.4.
Listing 4.4 Assigning Version 0.4.0 to the Sample Project
<PropertyGroup> <TargetFramework>netcoreapp1.1</TargetFramework> <Version>0.4.0</Version> </PropertyGroup>
Targeting Multiple Frameworks
By default, a TargetFramework element instructs the compiler to build for a specific framework and version of the .NET frameworks. Perhaps you have a project or library that you want to reference that only works with a specific version of the .NET Framework. If you needed to reference a .NET 4.6.1 Framework to work with this library, you can use this feature to help enable that.
You can configure an application for multiple frameworks by using the TargetFrameworks element with a semicolon-separated list of frameworks that you would like your project built for, as shown in Listing 4.5.
Listing 4.5 Configuring a Project to Build for .NET Framework 4.6.1 and .NET Core 1.1
<PropertyGroup> <!--<TargetFramework>netcoreapp1.1</TargetFramework>--> <Version>0.4.0</Version> <TargetFrameworks>net461;netcoreapp1.1</TargetFrameworks> </PropertyGroup>
Notice that Listing 4.5 leaves the TargetFramework element in place but commented out. The TargetFramework element takes precedence over the TargetFrameworks element, so you need to remove it in order to ensure that your project will be built for the two frameworks listed in the TargetFrameworks element.
If you build the application with this configuration by using the dotnet build command, two folders are created under the bin/Debug folder, each named after the appropriate framework name. Table 4.1 lists some of the framework monikers that you can use in your ASP.NET Core application.
Table 4.1 Available Target Frameworks for ASP.NET Core Projects
|.NET Framework 4.5.1
|.NET Framework 4.5.2
|.NET Framework 4.6
|.NET Framework 4.6.1
|.NET Framework 4.6.2
|.NET Framework 4.7
|.NET Core 1.0
|.NET Core 1.1
For a maintained list of all available target framework monikers, see the MSDN page https://docs.microsoft.com/en-us/nuget/schema/target-frameworks.
Optimizing for Specific Runtimes
With previous iterations of .NET Framework, you could be assured that your application would work great on any version of Windows that had the same version of .NET Framework for which your application was built. With the cross-platform features of .NET Core, you can have similar confidence that your application will run great on any platform that has a .NET Core framework installed on it. However, there may be scenarios in which you want to optimize an application to run on specific operating system runtimes. To support such a scenario, you can add the RuntimeIdentifiers element to your project file with a semicolon-separated list of the runtime identifiers your project supports. Table 4.2 lists some common runtime identifiers that you can use in your ASP.NET Core applications.
Table 4.2 Some of the Available Runtime Identifiers for ASP.NET Core Projects
|Operating System(s) Supported
|Windows 7, Windows Server 2008 R2 32bit
|Windows 7, Windows Server 2008 R2 64bit
|Windows 10, Windows Server 2016 32bit
|Windows 10, Windows Server 2016 64bit
|Mac OSX Yosemite
|Mac OSX El Capitan
|Mac OS Sierra
|Ubuntu Linux 16.4 (Xenial Xerus)
|Ubuntu Linux 16.10 (Yakkety Yak)
Microsoft maintains a complete list of available runtime identifiers on MSDN, at https://docs.microsoft.com/en-us/dotnet/core/rid-catalog.
Listing 4.6 shows how you can add a simple list of runtime identifiers to your project for Windows 7, OSX 10.11 (El Capitan), and Ubuntu 16.04.
Listing 4.6 Defining Compatible Runtimes in Your Project
<PropertyGroup> <!--<TargetFramework>netcoreapp1.1</TargetFramework>--> <Version>0.4.0</Version> <TargetFrameworks>net461;netcoreapp1.1</TargetFrameworks> <RuntimeIdentifiers>win7-x64;osx.10.11-x64;ubuntu.16.04-x64</RuntimeIdentifiers> </PropertyGroup>
You can now build your application with the dotnet build command, and your output will be created in a portable configuration. This is a set of libraries and executables that will run wherever a specified version of the .NET Core or .NET Framework is available.
However, if you want to be able to deploy your application to an environment where the version of the .NET framework does not exist, you can build a self-contained deployment that will include all the necessary references to run the application on the target runtime with the framework of your choosing. Given your current configuration that supports Mac OSX El Capitan and .NET Core 1.1, you can create a distribution of your application appropriate to run on that environment by executing the following commands:
dotnet restore dotnet publish -c Release -f netcoreapp1.1 -r osx.10.11-x64
The restore command acquires any runtime libraries needed to build for the extra runtimes listed in the project file. The publish command first builds the application in the Release configuration for the netcoreapp1.1 framework, targeting the osx.10.11-x64 runtime. Inside your project’s bin folder, you will now find a Release folder with a netcoreapp1.1 subfolder that contains a single osx.10.11-x64 folder. Inside that folder, you’ll find the binaries necessary to run the application on a Mac, and you’ll also find a publish folder. The publish folder contains all the files and the wwwroot folder necessary to deploy and run your application on a Mac that does not already have the .NET Core framework installed. You can just copy the entire contents of the publish folder to a Mac and start the ASPTravlerz application to have it begin hosting the web application for you.
Executing Scripts as Part of the Build Process
The MSBuild format already provides a mechanism for you to connect and execute scripts and external tools as part of the build process for a project. You will use this feature in later chapters when you begin adding components from the npm repository to your project.
You can execute these external scripts by writing them into an Exec element and wrapping that element in a Target. In order to specify the order in which the Target executes, you can use BeforeTargets and AfterTargets attributes. Listing 4.7 shows a sample Target that runs npm install.
Listing 4.7 Running npm restore Before the Application Is Published
<Target Name="InstallNpm" BeforeTargets="Build"> <Exec Command="npm install" /> </Target>
This code block can appear anywhere as a child of the Project element in your .csproj file. The Target element takes a required name attribute, and in this case it is given the very descriptive InstallNpm name. The next attribute, BeforeTargets, indicates that the content of this target should be executed before the application is built. If you choose to use the AfterTargets attribute with the Build argument, the contents are executed after the project is built. Finally, you can also replace the Build target with Publish and trigger the actions Before or After with the Publish action as well. Both Build and Publish targets are triggered in Visual Studio as well as at the command line, so you can get the same automation behavior when compiling your application by hand.
The Exec element inside the Target declares the command-line executable and options that should be executed when this Target is triggered. In this example, the simple npm install command will be triggered before the Build operation takes place.
For a complete reference on MSBuild syntax and options, see https://docs.microsoft.com/en-us/visualstudio/msbuild/msbuild.