Home > Articles

This chapter is from the book

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

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

Framework Abbreviation
.NET Framework 4.5.1 net451
.NET Framework 4.5.2 net452
.NET Framework 4.6 net46
.NET Framework 4.6.1 net461
.NET Framework 4.6.2 net462
.NET Framework 4.7 net47
.NET Core 1.0 netcoreapp1.0
.NET Core 1.1 netcoreapp1.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 Abbreviation
Windows 7, Windows Server 2008 R2 32bit win7-x86
Windows 7, Windows Server 2008 R2 64bit win7-x64
Windows 10, Windows Server 2016 32bit win10-x86
Windows 10, Windows Server 2016 64bit win10-x64
Mac OSX Yosemite osx.10.10-x64
Mac OSX El Capitan osx.10.11-x64
Mac OS Sierra osx.10.12-x64
Ubuntu Linux 16.4 (Xenial Xerus) ubuntu.16.04-x64
Ubuntu Linux 16.10 (Yakkety Yak) ubuntu.16.10-x64

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020