ASP.NET Core 2 Fundamentals - Onur Gumus - E-Book

ASP.NET Core 2 Fundamentals E-Book

Onur Gumus

0,0
27,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

The book sets the stage with an introduction to web applications and helps you build an understanding of the tried-and-true MVC architecture. You learn all about views, from what is the Razor view engine to tagging helpers. You gain insight into what models are, how to bind them, and how to migrate database using the correct model. As you get comfortable with the world of ASP.NET, you learn about validation and routing. You also learn the advanced concepts, such as designing Rest Buy (a RESTful shopping cart application), creating entities for it, and creating EF context and migrations. By the time you are done reading the book, you will be able to optimally use ASP.NET to develop, unit test, and deploy applications like a pro.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 210

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



ASP.NET Core 2 Fundamentals

 

 

 

 

 

 

 

 

Build cross-platform apps and dynamic web services with this server-side web application framework

 

 

 

 

 

 

 

 

 

Onur Gumus
Mugilan T. S. Ragupathi

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

ASP.NET Core 2 Fundamentals

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Acquisitions Editor: Koushik SenContent Development Editors: Edwin Moses, Rutuja YerunkarProduction Coordinator: Ratan Pote

First published: August 2018

Production reference: 1300818

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78953-891-5

www.packtpub.com

 
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. 

Contributors

About the authors

Onur Gumus works as a lead software engineer in Dubai UAE. He has 15 years of experience in .NET and web development. He is a functional programming enthusiast and has completed many large projects with ASP.NET.

 

 

Mugilan T. S. Ragupathi has been working on building web-based applications using Microsoft technology for more than a decade. He is active in the ASP.NET community and is running a successful blog, “dotnetodyssey.com”, to help his fellow .NET developers. His free beginners' course for ASP.NET MVC 5 at the above blog was well received and is referred to as a concrete reference for beginners. He has also written two free micro e-books, The 7 Most Popular Recipes of jQuery with ASP.NET Web Forms and Value & Reference types in C#. His books have received a good response.

He can be seen on csharp subreddit/Stack Overflow and is also an active contributor to the ASP.NET community on Quora, going by the username “Mugil-Ragu”. He likes to help readers with queries regarding ASP.NET.

 

 

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

ASP.NET Core 2 Fundamentals

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the authors

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Conventions used

Get in touch

Reviews

Setting the Stage

Introduction to Web Applications

How Web Applications Work

What is the HTTP Protocol?

HTTP/2's Edge over HTTP/1.x

Request-Response Pattern

Stateless Nature of HTTP

Advantages to HTTP

Work with the Statelessness and the Request-Response Pattern

Client Side and Server Side

Programming Styles – RPC versus REST

Working with HTTP Methods

The GET Method

The POST Method

List of Important Methods

Other Methods

Activity: Working with the Request-Response Pattern

Introduction to ASP.NET

ASP.NET MVC

The Model-View-Controller Pattern

A File-Based Project

Creating Your First Project

Creating Your First Application

Summary

Controllers

Role of the Controller in ASP.NET MVC Applications

Ideal Flow of Data for a Layered Web Application

Introduction to Routing

Activity: Finding the Correct Method Invoked for a URL

Installing the ASP.NET Core NuGet Package in Your Application

Our First Controller

IActionResult

Activity: Implementing Your Own IActionResult

Adding Views

Adding Models

Passing Data from the Controller to the View

Filters

Activity: Writing a Custom Filter

Summary

Views

The View Engine and the Razor View Engine

The Razor View Engine

Programming in the Razor View Engine

Variables in the Razor View

Working with Razor View

Programming Constructs in the Razor View

Activity: Printing Prime Numbers from 1 to 100

Layout

Building our First Layout

Creating _ViewStart.cshtml

Creating _Layout.cshtml

Adding a Page-Specific View

Activity: Creating Another Layout and Changing the View to That Layout

Generating HTML

Generating HTML using a Simple Form

HTML Helpers

Generating a form using HTML Helpers

Activity: Making Use of a Checkbox

Partial View

Calling a Partial View

Activity: Working with Static Data

View Components

Creating a View Component

Creating a ViewComponent Attribute

Activity: Passing a String as Additional Data

Tag Helpers

Custom Tag Helpers

Creating a Custom Tag Helper

Activity: Replacing Email Tag Helpers

Summary

Models

Introduction to Models

Creating an ASP.NET Core Application

Models Specific to a View Component

ViewModels

Data Flow with Respect to a Model

Activity: Revising the Code to Show Discount in the Total

Model Binding

Entity Framework

Creating Console Applications with Entity Framework

Installing Entity Framework Core NuGet Package

Using the NuGet Package Manager

Installing Entity Framework Commands

Creating Model Classes

Creating the DbContext Class

Creating a Migration

How the SaveChanges Method Works

Updating the Record

Deleting the Record

Activity: Controlling the Transaction Manually

Using Entity Framework in ASP.NET MVC Applications

Database Migration

Summary

Validation

Introduction to Validation

Client-Side and Server-Side Validation

Server-Side Validation

Updating ViewModels with the Data Annotation Attribute

Updating the ViewModel to Display the Validation Error Message

Updating the Controller Action Method to Verify the Model State

Activity: Adding a New Validation Rule for Designation

Client-Side Validation

Performing Client-Side Validation

Activity: Adding a New Validation Rule to a JavaScript Function

Implementation

Activity: Adding a New Validation Rule for Designation by Extending ValidationAttribute

Summary

Routing

Convention-Based Routing

Attribute-Based Routing

Working on an Example of Attribute-Based Routing

Route Attribute at the Controller Level

Token Replacement in Route Templates

Activity: Combining Route Templates that Begin with /

Passing Routing Values in HTTP Action Verbs in the Controller

Activity: Defining Two Actions with the Same Name with Different Verbs

Route Constraints

Activity: Creating an Attribute that Implements IActionConstraintFactory

Summary

Rest Buy

Designing Rest Buy

Features and Stories

Layout and Pages

Main Page

Product Detail

Checkout

Checkout Success

Previous Orders

Defining our Domain and Model

Creating a RestBuy Project

Activity: Preparing Features and Stories for a Website

Activity: Preparing Wireframe Diagrams for a Website

Activity: Designing a Domain Model for a Website

Creating the Entities

Create EF Context and Migrations

Create migrations

Activity: Adding a Supplier Entity that Denotes the Supplier of a Product

Summary

Adding Features, Testing, and Deployment

Adding the Registration Feature

Sign In and Sign Out Mechanism

Creating the Application Layer

Performing Implementations in the Infrastructure Project

Defining our ViewModel for Registration

Defining our Controllers

Creating the Post-Registration Landing Page

Creating a Query for the Registration Service

Validating the Registration

Creating a Unit Test

Writing a Unit Test

Running the Unit Test

Activity: Writing a Unit Test for Deletion

Upgrading Our Project to Bootstrap 4

Activity: Adding a EULA Agreement

Deploying RestBuy to Azure

Signing up to Microsoft Azure

Prerequisites to Azure Deployment

Deploying Rest Buy to Azure

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

The book sets the stage with an introduction to web applications and helps you to build an understanding of the tried-and-true MVC architecture. You learn all about views, from what is the Razor view engine to tagging helpers. You gain insight into what models are, how to bind them, and how to migrate databases using the correct model. As you get comfortable in the world of ASP.NET, you learn about validation and routing. You also learn advanced concepts, such as designing a RESTful application, creating entities for it, and creating EF context and migrations. 

This book balances theory and exercises, and contains multiple open-ended activities that use real-life business scenarios for you to practice and apply your newly acquired skills in a highly relevant context. We have included over 60 practical activities and exercises across 38 topics to reinforce your learning. By the time you are done reading the book, you will be able to optimally use ASP.NET to develop, unit test, and deploy applications like a pro.

Who this book is for

If you are looking to build web applications using ASP.NET Core or you want to become a pro in building web applications using the Microsoft technology, this is the ideal book for you. Prior exposure and understanding of C#, JavaScript, HTML, and CSS syntax is assumed. This book is written at the time of .NET Core 2.0 preview.

What this book covers

Chapter 1, Setting the Stage, begins with explaining the fundamental concepts about web applications—HTTP, client side, and server side. It also discusses the three programming models of ASP.NET MVC. Finally, it provides simple and easy-to-follow step-by-step instructions to set up an ASP.NET Core Web Application project and project structure.

Chapter 2, Controllers, explains the role of the controller in ASP.NET MVC applications. It also details the procedure of creating a controller and action methods. It also describes how to make modifications to the controller, such that it uses the view. Finally, it describes how to add a model and pass that model data to your view.

Chapter 3, Views, is more hands-on in nature as it teaches how to program in the Razor view engine and use different programming constructs. It also explains in depth how to create and call partial views, create a view component, and create custom Tag Helpers.

Chapter 4, Models, explains how models in ASP.NET MVC are used to represent the business domain data. It begins by explaining how to create a simple model and a model specific to ViewModel. It then provides the step-by-step guidance on how to use Entity Framework in ASP.NET MVC applications. 

Chapter 5, Validation, describes the importance of validating the input data before storing the data for further processing. It begins with a brief explanation of the different types of validation. Moves on to explain how to perform both client-side and server-side validations by using an example. Finally, it covers how to use jQuery libraries to perform unobtrusive JavaScript validation.

Chapter 6, Routing, discusses routing along with several options available for customizing it in ASP.NET. Firstly, it teaches how to configure routing using MapRoute. It then, through examples, teaches how to work with different types of routing.

Chapter 7, Rest Buy, details the development of a simple shopping cart application called Rest Buy. As with how most projects begin, it discusses the design of Rest Buy. Then, it moves on to discuss the entities for the application. Finally, it deals with EF context and migrations.

Chapter 8, Adding Features, Testing, and Deployment, is built around adding the registration feature to our application and testing and deploying it to the cloud. It, therefore, deals with writing unit tests and upgrading it to Bootstrap 4. It also details how to deploy our application to Azure.

To get the most out of this book

You need to have a computer system equipped with the following hardware and software:

For an optimal experience, we recommend the following hardware configuration:

Processor: 3.2 GHz or faster processor (Dual core with multi-threading)

Memory: 4 GB of RAM (1.5 GB if running on a virtual machine)

Storage: Installations require 20-50 GB of free Hard disk space (depending on features installed the requirement can go up to 130 GB of available space)

You must also install in advance the following software:

Operating System: Windows Server 2008 R2 SP1 (and above) or Windows 7 SP1 (and above)

Visual Studio Community 2017 IDE (

https://www.visualstudio.com/downloads/

)

Packages and frameworks, such as NuGet, Bootstrap, and project.json

Fiddler (

https://www.telerik.com/download/fiddler

)

Download the example code files

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

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

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 Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/TrainingByPackt/Beginning-ASP_DOT_NET. In case there's an update to the code, it will be updated on the existing GitHub repository.

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

 

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

public class ValuesController : Controller{ // GET api/<controller> public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[default]exten => s,1,Dial(Zap/1|30)exten => s,2,Voicemail(u100)

exten => s,102,Voicemail(b100)

exten => i,1,Voicemail(s0)

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Open up Visual Studio 2017. Navigate to File | New Project | Web."

Warnings or important notes appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Setting the Stage

ASP.NET Core—the redesign of ASP.NET from Microsoft—is the server-side web application development framework which helps you to build web applications effectively. This runs on top of the .NET Core platform, which enables your application to be run on a wide variety of platforms, including Linux and macOS. This opens up heaps of opportunities and it is exciting to be a .NET developer in these times.

By the end of this chapter, you will be able to:

Explain the fundamental concepts about web applications—HTTP, client side, and server side

Explain the three programming models of ASP.NET MVC

Get to grips with the philosophy of ASP.NET MVC

Create your first ASP.NET Core Web Application project and project structure

Introduction to Web Applications

Before discussing the ASP.NET Core and its features, let us understand the fundamentals of web application development.

Remember this principle: If you want to be an expert at something, you need to be very good at the fundamentals.

How Web Applications Work

All web applications, irrespective of whether they are built using ASP.NET MVC (MVC stands for Model-View-Controller), which is actually inspired by the success of Ruby on Rails, or any other new shiny technology, work on the HTTP protocol. Some applications use HTTPS (a secure version of HTTP), where data is encrypted before passing through the wire. But HTTPS still uses HTTP.

Symmetric encryption is the conventional method to ensure the integrity of the data transferred. It makes use of only one secret key, called a symmetric key, for both encryption and decryption. Both the sender and receiver possess this key. The sender uses it for encryption, while the receiver uses it for decryption. Caesar's Cipher is a good example of symmetric encryption.

Asymmetric encryption makes use of two cryptographic keys. These keys are known as public and private keys. The information to be sent is encrypted by the public key. The private key is used to decrypt the information received. The same algorithm is behind both of these processes. The RSA algorithm is a popular algorithm used in asymmetric encryption.

Encryption ensures the integrity of the data transferred by making use of cryptographic keys. These keys are known only by the sender and the receiver of the data being transferred. This means that the data won't be tampered by anyone else. This prevents man-in-the-middle attacks.

 

What is the HTTP Protocol?

A protocol is nothing but a set of rules that govern communication. The HTTP protocol is a stateless protocol that follows the request-response pattern.

HTTP stands for HyperText Transfer Protocol and is an application protocol which is designed for distributed hypermedia systems. HyperText in HyperText Transfer Protocol refers to the structured text that uses hyperlinks for traversing between the documents. Standards for HTTP were developed by the Internet Engineering Task Force (IETF) and the World Wide Web Consortium (W3C). The current version of HTTP is HTTP/2 and was standardized in 2015. It is supported by the majority of web browsers, such as Microsoft Edge, Google Chrome, and Mozilla Firefox.

HTTP/2's Edge over HTTP/1.x

At a high level, HTTP/2:

Is binary, instead of textual

Is fully multiplexed, instead of ordered and blocking

Uses one connection for parallelism

Uses header compression to reduce overhead

Allows servers to push responses proactively into client caches

Request-Response Pattern

Before talking about the request-response pattern, let's discuss a couple of terms: client and server. A server is a computing resource that receives the requests from the clients and serves them. A server, typically, is a high-powered machine with huge memory to process many requests. A client is a computing resource that sends a request and receives the response. A client could typically be any application that sends the requests.

Coming back to the request-response pattern, when you request a resource from a server, the server responds to you with the requested resource. A resource could be anything—a web page, text file, image, or another data format.

You fire a request. The server responds with the resource. This is called a request-response pattern.

Stateless Nature of HTTP

When you request for the same resource again, the server responds to you with the requested resource again without having any knowledge of the fact that the same was requested and served earlier. The HTTP protocol inherently does not have any knowledge of the state of any of the previous requests received and served. There are several mechanisms available that maintain the state, but the HTTP protocol does not maintain the state by itself. We will explain the mechanisms to maintain the state later.

Advantages to HTTP

Here are the few advantages of using HTTP protocol:

HTTP is a text-based protocol that runs on top of TCP/IP

HTTP is firewall-friendly

HTTP is easier to debug since it is text based

All browsers know about HTTP. Thus, it is extremely portable on any device or any platform

It standardizes the application-level protocol into a proper request–response cycle

With TCP/IP, everybody has to invent their own application protocol. HTTP is traditionally not full duplex, but with HTML5 we can use Web Sockets to upgrade HTTP connections to a full duplex connection.

Work with the Statelessness and the Request-Response Pattern

With the help of a simple practical example, let's work with the statelessness and the request-response pattern. Here are the steps:

Type this URL:

https://en.wikipedia.org/wiki/ASP.NET_Core

. This is a Wikipedia web page about ASP.NET Core.

We'll talk about ASP.NET later in this chapter.

From the preceding URL, the browser fires a request to the Wikipedia server.

The web server at Wikipedia serves you the ASP.NET Core web page.

Your browser receives that web page and presents it.

Now, request the same page again by typing the same URL again (

https://en.wikipedia.org/wiki/ASP.NET_Core

) and pressing

Enter

.

The browser again fires the request to the Wikipedia server.

Wikipedia serves you the same ASP.NET Core web page without being aware of the fact that the same resource was requested previously.

Here's a screenshot from the Wikipedia page showing requests and responses:

As mentioned earlier, there are several mechanisms to maintain the state. Let us assume, for the time being, that no such mechanism is implemented here.

Client Side and Server Side

It is necessary to understand the client side and server side of web applications and what can be done on either side. With respect to web applications, your client is the browser and your server could be the web server/application server.

The client side is whatever that happens in your browser. It is the place where your JavaScript code runs and your HTML elements reside.

The server side is whatever happens at the server at the other end of your computer. The request that you fire from your browser has to travel through the wire (probably across the network) to execute some server-side code and return the appropriate response. Your browser is oblivious to the server-side technology or the language your server-side code is written in. The server side is also the place where your C# code resides.