Book Image

Learning ASP.NET Core 2.0

By : Jason De Oliveira, Michel Bruchet
Book Image

Learning ASP.NET Core 2.0

By: Jason De Oliveira, Michel Bruchet

Overview of this book

The ability to develop web applications that are highly efficient but also easy to maintain has become imperative to many businesses. ASP.NET Core 2.0 is an open source framework from Microsoft, which makes it easy to build cross-platform web applications that are modern and dynamic. This book will take you through all of the essential concepts in ASP.NET Core 2.0, so you can learn how to build powerful web applications. The book starts with a brief introduction to the ASP.NET Core framework and the improvements made in the latest release, ASP.NET Core 2.0. You will then build, test, and debug your first web application very quickly. Once you understand the basic structure of ASP.NET Core 2.0 web applications, you'll dive deeper into more complex concepts and scenarios. Moving on, we'll explain how to take advantage of widely used frameworks such as Model View Controller and Entity Framework Core 2 and you'll learn how to secure your applications. Finally, we'll show you how to deploy and monitor your applications using Azure, AWS, and Docker. After reading the book, you'll be able to develop efficient and robust web applications in ASP.NET Core 2.0 that have high levels of customer satisfaction and adoption.
Table of Contents (19 chapters)
Title Page
Credits
Foreword
About the Authors
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Preface

Everyday, software developers, application architects, and IT project managers work on building applications as quickly as possible to be a leader in their respective markets: time to market is of utmost importance. Unfortunately, the quality and performance of those applications are often not as expected, since they have not been fully tested, optimized, and secured.

During the past few years, ASP.NET has evolved into becoming one of the most consistent, stable, and feature-rich frameworks available in the market for web application development. It provides all expected characteristics you can think of concerning performance, stability, and security out of the box.

For some time now, the IT market has been changing. Compliance with different standards is now required and customers expect industrialized, high-performing, and scalable applications, while developers ask for frameworks that allow higher productivity and extensibility to adapt to specific business needs. This has lead Microsoft to completely rethink their web technologies accordingly.

As a result, Microsoft has built ASP.NET Core, which gives developers the capacity to do the following:

  • Creating applications and compile them in a specific environment, but then run them in any environment (such as Linux, Windows, or macOS)
  • Using third-party libraries with additional functionalities
  • Working with various tools, frameworks, and libraries
  • Adopting the most up-to-date best practices for frontend development
  • Developing flexible, responsive web applications

ASP.NET Core 2.0, together with Microsoft Visual Studio 2017, includes several features to make your life as a web developer easier and more productive. For example, Visual Studio offers project templates, which you can use to develop your web applications. Visual Studio also supports several developments modes, including using Microsoft Internet Information Services (IIS) directly to test your web applications during development time and using a built-in web server and developing your web applications over FTP.

With the debugger in Visual Studio, you can run through your application and step through the critical areas of your code to find problems. With the Visual Studio Editor, you can effectively develop user interfaces.

And when you are ready to deploy your application, Visual Studio makes it easy to create a deployment package for deployment on Azure, Amazon Web Services, and Docker, or any other platform including Linux and macOS. These are but a few of the features built into the ASP.NET Core framework when paired with Visual Studio.

This book provides the latest best practices and ASP.NET Core guidance to get you up to speed quickly. Each section of this book presents specific ASP.NET Core 2.0 features in an easily readable format with detailed examples. The step-by-step instructions yield immediate working results. Most of the key features of ASP.NET Core are illustrated using succinct, easily understandable, and reusable examples. The examples are rich to illustrate features without being overbearing.

In addition to showing ASP.NET Core features by example, this book contains practical applications of each feature so that you can apply these techniques in the real world. After reading this book and applying the exercises, you will have a great head start into building efficient web applications that include modern features, such as MVC, Web APIs, custom view components, and tag helpers.

We hope this book will help you in your daily job as a developer and reading it will give you as much joy as writing it has given us.

Once upon a time, NGWS and the .NET Framework

The following is a little bit of history to explain how the .NET Framework has evolved over the years and why you have to consider the .NET Core Framework today:

Microsoft has started working on what we know now as the .NET Framework in the late 1990s and has released a first beta version of .NET Framework 1.0 in late 2001.

Originally, the framework was named NGWS for Next Generation Windows Services (internal codename Lightning/Project 42). In the beginning, developers could only use VB.NET as a programming language. More than 10 Framework versions later, a lot has been achieved. Today, you can choose between a large number of languages, frameworks, and technologies.

In the beginning, InterDev was the primary development environment to develop ASP Pages, and you had to use a command-line VBC compiler tool to compile your code.

The first version of our beloved Visual Studio development environment was published in February 2002, bringing with it a common runtime environment for the Windows client and Windows server family (NT 4, Windows 98, Windows ME, Windows XP, and then Windows 2000).

Around the same time, Microsoft provided a lighter framework, named Compact Framework, to execute Windows CE on Windows Mobile. The last version was published in January 2008 as Version 3.5 RTM before it was replaced by newer mobile technologies.

The first .NET SDK was published in April 2003 as .NET Framework 1.1 and was included in Visual Studio 2003. It was the first version to be included in the Windows Server OS and shipped together with Windows 2003.

.NET Framework 2.0 was released in January 2006 during the time of Windows 98 and Windows Me. It provided a major upgrade to the Common Language Runtime (CLR). It was the first version to fully support 64-bit computing and fully integrate with Microsoft SQL Server. It also introduced a new Web Pages Framework, providing features such as skins, templates, master pages, and style sheets.

.NET Framework 3.0 (WinFX) was released in November 2006. It included a new set of managed code APIs. This version added several new technologies to build new types of applications, such as Windows Presentation Foundation (WPF), Windows Communication Foundation (WCF), Windows Workflow Foundation (WWF), and Windows CardSpace (later integrated into Windows Identity Foundation).

.NET Framework 3.5 extended the WinFX features one year later in 2007. This version included key features such as Linq, ADO.NET, ADO.NET Entity Framework, and ADO.NET Data Services. Furthermore, it shipped with two new assemblies that would later be the foundation of the MVC framework: System.Web.Abstraction and System.Web.Routing.

.NET Framework 4.0 was published in May 2009; it provided some major upgrades to the Common Language Runtime (CLR) and added Parallel extension to improve support parallel computing, dynamic dispatch, named parameters, and optional parameters, as well as code contracts and the BigIntegerComplex numeric format.

After the release of .NET Framework 4.0, Microsoft released a set of improvements to build microservices in the form of the Windows Server AppFabric framework. Essentially, it provided an InMemory distributed cache and an application server farm.

.NET Framework 4.5 was released in August 2012; it added a so-called Metro style application (which later evolved into Universal Windows Platform applications), the Core features, and the Microsoft Extension Framework (MEF).

Concerning ASP.NET, this version was more compatible with HTML5, jQuery, and provided bundling and minification for improved web page performance. It was also the first to support WebSockets and asynchronous HTTP requests and responses.

.NET Framework 4.6.1 was released in November 2015; it required Windows 7 SP1 or later, and was an important version. Some of the new features and APIs included were support for SQL Connectivity for AlwaysOn, Always Encrypted, and improved connection resiliency when using Azure SQL Databases. It also added Azure SQL Database support for distributed transactions using the updated System.Transactions APIs and provided many other performance, stability, and reliability related fixes in RyuJIT, GC, and WPF.

.NET Framework 4.6.2 was released in March 2016; it added support for paths longer than 260 characters, FIPS 186-3 DSA in X.509 certificates, and localization of data annotations, and the resources files were moved to the App_LocalResources folder. Additionally, the ASP.NET session provider and local cache manager were made compatible with the asynchronous framework.

.NET Framework 4.7 was released in April 2017; it was included in the Windows 10 Creators update. Some of the new features included enhanced cryptography with elliptic curve cryptography and improved Transport Layer Security (TLS) support, especially for version 1.2. It also introduced the object cache store, which enabled developers to provide custom providers easily by implementing the ICacheStoreProvider interface.

There was also a better integration between the application and the memory monitor and the famous memory limits reactions, which enables developers to observe the CLR when it truncates objects cached in memory and overrides the default behavior.

Then, Microsoft developed a completely new .NET Framework with open source multi-platform in mind from the beginning. It was introduced as ASP.NET 5 and later renamed ASP.NET Core Framework.

The first release, 1.0, was announced by Richard Lander (MSFT) in June 2016; the ASP.NET MVC and Web API frameworks were merged into a single framework package that you could easily add to your projects via NuGet.

The second release, .NET Core Framework 1.1, was published in November 2017; it ran on more Linux distributions, its performance was improved, it was released with Kestrel, the deployment on Azure was simplified, and the productivity was improved. Entity Framework Core started to support SQL Server 2016.

Note that .NET Core Framework 1.0 and 1.1 will be supported by Microsoft until June 2019.

The latest release of the .NET Core Framework is 2.0. A first preview version was released in May 2017. A second preview version—published in June 2017 and the final version, on which this book is based—was released in August 2017.

Microsoft has vastly improved the .NET Core Framework. The improvements and extensions are the result of the vision for .NET Core 2.0; it enables you to use more of your code in more places.

The following improvements are included in .NET Core 2.0:

  • Massive API increase (>100%) relative to .NET Core 1.x
  • Support for .NET Standard 2.0
  • Support to reference .NET Framework libraries and NuGet packages
  • Support for Visual Basic

Furthermore, the .NET Standard 2.0 brings these new features:

  • Bigger API surface—it's extended to cover the intersection between .NET Framework and Xamarin. This also makes .NET Core 2.0 much bigger as it implements .NET Standard 2.0. The total number of APIs added to .NET Standard is ~20,000.
  • It can reference existing .NET Framework libraries. The best thing is—no recompile required, so this includes existing NuGet packages.
  • .NET Core supports more Linux distribution. Samsung is working to provide support for the mobile OS Tizen.
  • And, most importantly, .NET Core is the fastest application runtime available in the .NET world.

Also, note that most of the regular libraries are available on GitHub. They can be forked and rebuilt by anyone who wants to extend or change any standard behaviors.

What this book covers

This book is organized into multiple chapters that explain ASP.NET Core 2.0 features in an easy and understandable format with practical examples. Most of the key features of ASP.NET Core 2.0 are illustrated using succinct, efficient examples and step-by-step instructions yield immediate working results.

You don't have to read the chapters in any order to find the book useful. Each chapter stands on its own, except for the first chapter, which details the fundamentals of ASP.NET Core—you might want to read it first if you've never ventured beyond desktop application development.

The following topics will be covered throughout the book:

Chapter 1, What is ASP.NET Core 2.0?, describes the features and functionalities of ASP.NET Core 2.0, but also the technical restrictions, which should allow you to understand in which cases it could be a good fit for your own needs and what to expect.

Chapter 2, Setting Up the Environment, gives a detailed explanation of how to set up your development environment and how to create your first ASP.NET Core 2.0 application. You will learn how to either use Visual Studio 2017 or Visual Studio Code, how to install the runtime, and how to use Nuget to retrieve all necessary ASP.NET Core 2.0 dependencies.

Chapter 3, Creating a Continuous Integration Pipeline in VSTS, shows how to set up a complete Visual Studio Team Services (VSTS) Continuous Integration Pipeline. You will learn how to fully automate building, testing, and deploying your applications using VSTS in the cloud.

Chapter 4, Basic Concepts of ASP.NET Core 2.0 – Part 1, explains the basic structure and concepts of ASP.NET Core 2.0 applications. It shows how everything works internally and what classes and methods can be used to override basic behavior. It also provides the theoretical background for all the other chapters.

Chapter 5, Basic Concepts of ASP.NET Core 2.0 – Part 2, following up on the concepts covered in Chapter 4Basic Concepts of ASP.NET Core 2.0 – Part 1, this chapter delves deeper into essential ASP.NET Core 2.0 concepts. You will learn about components and features offered by ASP.NET Core to build responsive web applications.

Chapter 6, Creating MVC Applications, provides all the concepts and everything necessary to create your first ASP.NET Core 2.0 MVC application. You will learn the specifics of MVC applications and how to implement them efficiently. Additionally, you will see how unit tests and integration tests will help you build better applications with fewer bugs, resulting in lower maintenance costs.

Chapter 7, Creating Web API Applications, covers the Web API Framework and provides everything essential to create your first ASP.NET Core 2.0 Web API. You will see different Web API styles, such as RPC, REST, and HATEOAS, and learn when to use them and how to implement them in an effective way.

Chapter 8, Accessing Data Using Entity Framework Core 2, shows how to access databases using Entity Framework Core 2, while using all the advanced features (Code First, Fluent API, Data Migrations, InMemory Databases, and more) it offers.

Chapter 9, Securing ASP.NET Core 2.0 Applications, explains how to use the built-in ASP.NET Core 2.0 features for user authentication and how to extend them by adding external providers. If you need to secure your applications, then this chapter is where you want to go.

Chapter 10, Hosting and Deploying ASP.NET Core 2.0 Applications, is about the various options you have when it comes to hosting and deploying your ASP.NET Core 2.0 web applications on premises and in the cloud. You will learn how to choose the appropriate solutions for a given use case, which will allow you to make better decisions for your own applications.

Chapter 11, Managing and Supervising ASP.NET Core 2.0 Applications, is finally going to be a chapter on how to manage and supervise your production-ready applications after deployment. It will greatly aid you in diagnosing problems for your ASP.NET Core 2.0 web applications during runtime and reduce the time to understand and fix bugs.

 

What you need for this book

You will either need Visual Studio 2017 Community Edition or Visual Studio Code, which are both free of charge for testing and learning purposes, to be able to follow the code examples found within this book. You could also use any other text editor of your choice and then use the dotnet command-line tool, but it would be advised to use one of the development environments mentioned earlier for better productivity.

Later in the book, we will work with databases, so you will also need a version of SQL Server (any version in any edition will work). We advise using SQL Server 2016 Express Edition, which is also free of charge for testing purposes.

There might be other tools or frameworks that will be introduced during the following chapters. We will explain how to retrieve them when they are used.

If you need to develop for Linux, then Visual Studio Code and SQL Server 2016 are your primary choices, since they are the only ones running on Linux.

Additionally, you will need an Azure Subscription and Amazon Web Services Subscription for some of the examples shown within the book. There are multiple chapters dedicated to show you how to take advantage of the cloud.

Who this book is for

This book is for developers who would like to build modern web applications with ASP.NET Core 2.0. No prior knowledge of ASP.NET or .NET Core is required. However, basic programming knowledge is assumed. Additionally, previous Visual Studio experience will be helpful but is not required, since detailed instructions will guide you through the samples of the book. This book can also help people who work in infrastructure engineering and operations to monitor and diagnose problems during the runtime of ASP.NET Core 2.0 web applications.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Start Visual Studio 2017, open the Tic-Tac-Toe ASP.NET Core 2.0 project you have created, create three new folders called ControllersServices, and Views, and create a subfolder called Shared in the Views folder."

A block of code is set as follows:

    [HttpGet] 
    public IActionResult EmailConfirmation (string email) 
    { 
      ViewBag.Email = email; 
      return View(); 
    } 

Any command-line input or output is written as follows. The input command might be broken into several lines to aid readability, but needs to be entered as one continuous line in the prompt:

sudo apt-get install code

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Open Visual Studio 2017, go to the Team Explorer tab, and click on the Branches button".

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your email address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box.
  5. Select the book for which you're looking to download the code files.
  6. Choose from the drop-down menu where you purchased this book from.
  7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows
  • Zipeg / iZip / UnRarX for macOS
  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at the following repositories:

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.