Web Programming - ASP - NET Core
Web Programming - ASP - NET Core
ASP.NET Core
Hans-Petter Halvorsen
https://www.halvorsen.blog
Web Programming
ASP.NET Core
Hans-Petter Halvorsen
2021
Preface
This textbook gives an overview of Web and Web programming in general and with focus on
ASP.NET and ASP.NET Core. ASP.NET and ASP.NET Core are web development frameworks
created by Microsoft.
The only way to learn programming is to do a lot of coding by yourself, and not only small
code snippets with a few lines of code. You need to make large Applications. It takes time
and may be demanding, but that’s the only way! The reward is knowledge that goes deep,
and you will gain skills that is highly desired by the industry.
Web Page:
ASP.NET: https://www.halvorsen.blog/documents/programming/web/aspnet/
Videos:
https://www.youtube.com/watch?v=lcQsWYgQXK4&list=PLdb-
TcK6Aqj34rTHSk6C1jZQgeALWS1qO
Here you will find videos that introduces the ASP.NET Core topics covered in this textbook.
Hans-Petter Halvorsen
The author currently works at the University of South-Eastern Norway. The author has been
working with Software Engineering and Industrial IT Projects for more than 20 years.
My Web Site:
https://www.halvorsen.blog/
https://www.youtube.com/IndustrialITandAutomation
https://www.halvorsen.blog
Table of Contents
Preface ............................................................................................................................. 2
Part 1 : Introduction ....................................................................................................... 12
1 Introduction............................................................................................................. 13
1.1 Applications...................................................................................................... 14
1.2 .NET.................................................................................................................. 15
1.3 Web ................................................................................................................. 16
2 ASP.NET................................................................................................................... 17
2.1 ASP.NET Web Forms ......................................................................................... 18
2.2 ASP.NET Core with Razor .................................................................................. 18
Part 2 : Visual Studio and C# ........................................................................................... 20
3 Visual Studio............................................................................................................ 21
3.1 Visual Studio macOS ......................................................................................... 22
4 Desktop Applications ............................................................................................... 25
4.1 Windows Forms App ......................................................................................... 25
4.2 WPF Application ............................................................................................... 25
4.3 Universal Applications ...................................................................................... 25
5 C# Programming Language ...................................................................................... 26
5.1 Introduction ..................................................................................................... 26
5.2 Classes .............................................................................................................. 27
5.3 Inheritance ....................................................................................................... 27
6.8.1 PHP.................................................................................................................................................. 42
6.8.2 ASP.NET........................................................................................................................................... 43
7 HTML....................................................................................................................... 46
7.1 HTML in Visual Studio ....................................................................................... 47
7.2 HTML Tags ........................................................................................................ 47
5
7.2.7 Comments ....................................................................................................................................... 49
6
12.6 Razor Pages ...................................................................................................... 79
12.6.1 Sending data from the Page Model to the Razor File ................................................................. 80
7
17.1.6 New Book ................................................................................................................................. 139
8
22.2 Final System ................................................................................................... 186
23 Web API ............................................................................................................. 188
Part 9 User Login and ASP.NET Core Identity ................................................................. 189
24 User Identity and Login ...................................................................................... 190
24.1 Password Security ........................................................................................... 190
25.2.1 Create Project in Visual Studio with Identity Enabled .............................................................. 200
9
Part 11 Deployment...................................................................................................... 218
27 Web Servers ....................................................................................................... 219
28 Deployment in Visual Studio ............................................................................... 222
29 Internet Information Services (IIS) ...................................................................... 223
29.1 Installation ..................................................................................................... 223
10
35.4.1 appSettings.json ....................................................................................................................... 242
11
Part 1 : Introduction
This part introduces the topics covered in this textbook and puts it into a proper context.
That’s why you need to know basic Web Programming, including HTML, CSS and JavaScript.
To create more powerful Web Sites and Web Applications you also need to know about
Web Servers, Database Systems and Web Frameworks like PHP, ASP.NET, etc.
It all started with Internet (1960s) and the World Wide Web - WWW (1991). The first Web
Browser, Netscape, came in 1994. This was the beginning of a new era, where everything is
connected on internet, the so-called Internet of Things (IoT).
• Part 1: Introduction
• Part 2: Visual Studio and C#
• Part 3: Web Fundamentals
• Part 4: ASP.NET Core
1.1 Applications
We can separate applications in different categories:
• Desktop Applications
• Web Applications
• Mobile Applications
These will shortly be described below. In this textbook we will focus on creating web
applications using ASP.NET Core.
Windows Forms Apps are the oldest but are still very popular.
We have:
14
1. Introduction
We have:
• iOS
• Android
• iPadOS
• etc.
The great thing about Web Applications is that they also work on Mobile platforms. Native
apps for Android phones and Apple devices typically need to be developed in a strict
environment and with specific programming languages and they only work for the platform
they are developed for. For Android development you typically will use the Kotlin
programming language in combination with Android Studio. While for development for the
Apple platform you will need a Mac computer and use the Swift programming language as
part of the Xcode development environment.
1.2 .NET
The .NET is a development platform from Microsoft.
.NET Framework was first introduces in 2002 and works only for the Windows operating
system, while .NET Core was introduced in 2016. .NET Core is cross-platform, meaning it will
work on Windows, Linux and macOS.
The newly released .NET 5 has merged .NET Framework and .NET Core into a more unified
package.
.NET Core and the newly released .NET 5 (that is built on .NET Core) will be the future of
.NET. Microsoft is still committed to support the previous .NET Framework for years to
come, but for new applications your choice should be .NET 5 either you want to develop
desktop applications (“Windows Forms App”) or web applications (“ASP.NET Core Web
App”).
15
1. Introduction
You can use many different programming languages with .NET, but the “default” language is
C#, which is the language we will use in this textbook.
1.3 Web
We have 2 types of web pages:
Static web pages are pure HTML web pages where the contents is written in manually and it
doesn’t change unless the user updates the contents.
Dynamic Web Pages typically get contents from a Database and have deeper interaction
with the user.
Dynamic Web Pages using e.g., ASP.NET or PHP Executes Code on the Server-side and
Generates HTML Code that is sent to the Client (Web Browser). This is known as Server-side
code.
You can also create Dynamic content on the Client using JavaScript.
Static Web Pages typically contains Text and Images that is not changing (unless a person
changes the page and upload a new version). Static Web Pages are Pure HTML pages
Video:
16
2 ASP.NET
ASP.NET is an open-source web framework, created by Microsoft, for building web apps and
services using the .NET Framework or the .NET Core. We have both ASP.NET and ASP.NET
Core. ASP.NET Core is the new approach built on .NET Core.
• ASP.NET Web Forms - The same programming model as WinForms. If you already
know WinForms, this is an easy access to the world of web programming.
• ASP.NET MVC (Model-View Controller). If you are familiar with the MVC approach,
this could be your choice.
• ASP.NET with Razor Pages - This is the latest and recommended way. This has
become the "default" approach for ASP.NET today. It mixes the best from all the
others combined with PHP like syntax (PHP is probably the most popular Web
Framework today)
Still, if you want to get an overview of ASP.NET Web Forms you may take a look at the
following:
This textbook will focus on Razor with Page Model (Code and Layout are separated in
different Files).
An ASP.NET Razor page has the “.cshtml” (e.g., “Index.cshtml”) file extension. This file
contains a mix of HTML and Razor syntax. The Razor syntax is actually C# code mixed
together with the HTML code.
The Razor parts of the file are executed on the web server before the page is sent to the
client (your web browser).
18
14. Database Systems
The Razor page may also have a C# code file linked to it, this file has the extension
“.cshtml.cs” (e.g., “Index.cshtml.cs”). The “.cshtml.cs” file is called the Page Model.
• A “.cshtml” file that contains HTML markup with C# code using Razor syntax.
• A “.cshtml.cs” (“code behind”) file that contains C# code that handles page events.
In this textbook we will go through ASP.NET Core in detail. In Part 3: Web Fundamentals we
go through the foundations for creating web applications in general, while in Part 4:
ASP.NET Core we start creating ASP.NET Core Web Applications. If you cannot wait to start
with ASP.NET Core, you take sneak peek at the introduction videos below.
Videos:
19
Part 2 : Visual Studio
and C#
This part gives an overview of Visual Studio and basic C# programming, which will be the
foundation for learning and development of ASP.NET Core Web Applications. If you already
are familiar with using Visual Studio and C# for development of Windows Forms Apps, you
can skip this part.
New projects are created from the “New Project” window (Figure 3-2).
Figure 3-3 shows the New Project window in Visual Studio for macOS.
22
3. Visual Studio
If you want to make Web Applications and you have a Mac, the Visual Studio for macOS has
become an excellent choice.
.NET Framework:
.NET Core:
• ASP.NET Core Web Application (Razor) – This is the default and recommended
option.
• ASP.NET Core Web Application (MVC)
• Angular Web Applications
• React.js Web Applications
• Web API
• etc.
23
3. Visual Studio
This means you have all the necessary tools available to create great web applications using
C# on your Mac.
24
4 Desktop Applications
In the latest version of Visual Studio 2019 we can develop WinForms Desktop Applications
and WPF Desktop Applications for both .NET Framework (4.x) and .NET Core (3.x).
.NET WinForms vs. .NET Core WinForms: Note that .NET Core is cross-platform, but .NET
Core WinForms Desktop Application will (of course) only work on Windows.
The first step in OOP is to identify all the objects you want to manipulate and how they
relate to each other, an exercise often known as data modeling. Once you've identified an
object, you generalize it as a class of objects and define the kind of data it contains and any
logic sequences that can manipulate it. Each distinct logic sequence is known as a method. A
real instance of a class is called an “object” or an “instance of a class”. The object or class
instance is what you run in the computer. Its methods provide computer instructions and
the class object characteristics provide relevant data. You communicate with objects - and
they communicate with each other.
Simula was the first object-oriented programming language. Simula was developed in the
1960s by Kristen Nygaard from Norway.
Java, Python, C++, Visual Basic .NET and C# are popular OOP languages today.
C# Documentation: https://docs.microsoft.com/en-us/dotnet/csharp/
5.2 Classes
Classes are the fundamental building blocks in C#.
5.3 Inheritance
Inheritance is a feature of object-oriented programming languages that allows you to define
a base class that provides specific functionality (data and behavior) and to define derived
classes that either inherit or override that functionality.
5.3.1 Example
Assume you have different types of sensors sharing some common features, then you can,
e.g., have a Base Class called Sensor() and then other derived Classes like
TemperatureSensor(), etc. that either inherit or override the functionality of the base class.
If you have different types of Temperature Sensor, you can make derived classes like
Thermistor() that inherit/ override functionality of TemperatureSensor(). See Figure 5-1.
27
5. C# Programming Language
28
5. C# Programming Language
5.4 Polymorphism
Polymorphism is an object-oriented feature that is part of all object-oriented programming
languages.
5.4.1 Example
5.5 Interfaces
Interfaces are used along with classes to define what is known as a contract. A contract is an
agreement on what the class will provide to an application.
An interface declares the properties and methods. It is up to the class to define exactly what
the method will do.
An interface is a completely "abstract class", which can only contain abstract methods and
properties (with empty bodies).
It is considered good practice to start with the letter "I" at the beginning of an interface, as
it makes it easier for yourself and others to remember that it is an interface and not a class.
Note: Interfaces can contain properties and methods, but not fields
29
5. C# Programming Language
5.5.1 Example
Assume you make this system as an open platform meaning other developers can use it to
add logging functionality from other sensors.
The system will not work if they don’t implement a Name for the Sensor and a ReadValue()
method.
To make sure that they follow this, you should implement Interfaces
To access the interface methods, the interface must be "implemented" (kinda like inherited)
by another class. To implement an interface, use the : symbol (just like with inheritance).
The body of the interface method is provided by the "implement" class. Note that you do
not have to use the override keyword when implementing an interface.
5.6 Generics
Generics allow you to define the specification of the data type of programming elements in
a class or a method, until it is actually used in the program. In other words, generics allow
you to write a class or method that can work with any data type.
You write the specifications for the class or the method, with substitute parameters for data
types. When the compiler encounters a constructor for the class or a function call for the
method, it generates code to handle the specific data type.
30
5. C# Programming Language
W3Schools: https://www.w3schools.com/cs/index.php
Videos:
Below you find some videos regarding Visual Studio and C# programming creating Windows
Forms Apps:
31
Part 3 : Web
Fundamentals
This part gives an overview of the fundamentals in web and web programming. ASP.NET
Core is a framework for creating Web Applications, this means you need to have basic
knowledge about the web and web programming in general before you can start creating
ASP.NET Core Web Applications.
If you already are familiar with the fundamentals of the web, familiar with creating HTML
web pages and have used, e.g., PHP for creating Web Applications, you can skip this part.
It all started with Internet (1960s) and the World Wide Web - WWW (1991). The first Web
Browser, Netscape, came in 1994. This was the beginning of a new era, where everything is
connected on internet, the so-called Internet of Things (IoT).
That’s why you need to know basic Web Programming, including HTML, CSS and JavaScript.
To create more powerful Web Sites and Web Applications you also need to know about
Web Servers, Database Systems and Web Frameworks like PHP, ASP.NET, etc.
Use HTML to define the content of web pages, CSS is used to specify the layout of web
pages, while JavaScript is used to program the behavior of web pages.
For creating more dynamic web pages, we typically also use a web framework like PHP or
ASP.NET, etc. With these frameworks you can communicate with a database for storing or
retrieving data.
34
6. The Web
• Internet (1960s)
• Google, 1998
• Facebook, 2004
• Smartphones, 2007
• Tablets, 2010
Microsoft:
Others:
• Eclipse
• Atom (free and open-source text and source code editor for macOS, Linux, and
Windows)
• Sublime
• Etc.
35
6. The Web
6.2 Client-Server
The basic principle of web is that it is a server and a client. The server hosts the web pages
and you request a web page from the client using a web browser.
36
6. The Web
37
6. The Web
The most common use of web servers is to host websites, but there are other uses such as
gaming, data storage or running enterprise applications.
38
6. The Web
Figure 6-9 shows some of the popular web browsers on the market today.
39
6. The Web
6.5 HTML
HTML, or HyperText Markup Language is the visual appearance of a web site. You could say
it is the language spoken by web browsers that makes it possible to see web contents in
your web browser. All web browser understands HTML. HTML 5 is the latest. HTML is
maintained by W3C - World Wide Web Consortium.
WYSIWYG – What You See Is What You Get. You don’t need to know HTML syntax - It’s just
like using MS Word.
40
6. The Web
Only possible to change the HTML source code and then select “Preview” in order to see
how it looks like in a Web Browser. You need to know HTML syntax.
• Visual Studio is not well suited for creating Static HTML Web Pages.
• Visual Studio is more optimized for creating Dynamic Web Pages and creating
ASP.NET Web Pages in special
Video:
HTML: https://youtu.be/DUEHx7l5a3Y
6.6 CSS
CSS – Cascading Style Sheets
CSS is used to control the style and layout of multiple web pages all at once
6.7 JavaScript
JavaScript is the de facto client-side programming language. Typically you want to use a
JavaScript Framework.
41
6. The Web
• JQuery
• TypeScript (Microsoft)
• PHP
6.8.1 PHP
PHP is a popular general-purpose scripting language that is especially suited to web
development.
PHP is a server-side scripting language for web development. It is used to make dynamic and
interactive web pages. PHP is an old and well-known technology, but it is still very popular
and easy to learn. PHP is open source (free) and cross-platform. Especially, the combination
of PHP and MySQL is a powerful combination used to create rich, dynamic web pages.
PHP is a server-side scripting language for web development. It is used to make dynamic
and interactive Web Pages
42
6. The Web
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain
HTML
LAMP is popular when it comes to Web Programming. LAMP consists of the following
components:
All of these 4 components are open source, which is one of the reasons for its popularity.
PHP example:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Additional Training:
6.8.2 ASP.NET
ASP.NET is an open-source web framework, created by Microsoft, for building web apps and
services using the .NET Framework or the .NET Core. We have both ASP.NET and ASP.NET
Core. ASP.NET Core is the new approach built on .NET Core.
6.8.3 Django
Django is based on the Python programming language.
43
6. The Web
Python: https://www.halvorsen.blog/documents/programming/python/
• XML
• JSON
Today, JSON has become the dominating standard for data exchange.
6.9.1 XML
XML stands for eXtensible Markup Language.
XML was the dominating format for storing and exchanging data between a browser and a
server, but today JSON has taken over.
Additional Resources:
6.9.2 JSON
JSON: JavaScript Object Notation.
44
6. The Web
JSON is a syntax for storing and exchanging data. When exchanging data between a browser
and a server, the data can only be text. JSON is text.
Example:
Additional Resources:
45
7 HTML
HTML, or HyperText Markup Language is the visual appearance of a web site. You could say
it is the language spoken by web browsers that makes it possible to see web contents in
your web browser. All web browser understands HTML. HTML 5 is the latest. HTML is
maintained by W3C - World Wide Web Consortium.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
Content of the document......
</body>
</html>
Video:
HTML: https://youtu.be/DUEHx7l5a3Y
We can use Visual Studio because we already use it in our Project – and basic HTML syntax is
something you should know about.
Visual Studio is more optimized for creating Dynamic Web Pages and creating ASP.NET Web
Pages in special
For pure HTML pages, I recommend that you use Visual Studio Code instead
47
7. HTML
7.2.1 Title
Title:
<title>This is my Title</title>
7.2.2 Headers
Headers 1:
<h1>This is my Header</h1>
Header 2:
<h2>This is my Header</h2>
Header 3:
<h3>This is my Header</h3>
7.2.3 Paragraphs
Paragraphs:
<p>My first paragraph.</p>
7.2.4 Hyperlinks
Hyperlinks:
<!DOCTYPE html>
<html>
<body>
<h1>This is a heading</h1>
<a href="http://www.google.com">This is a link to Google</a>
</body>
</html>
7.2.5 Images
Images:
<!DOCTYPE html>
<html>
<body>
<h1>This is a heading</h1>
<img src= "myimage.jpg" alt=”blabla" width="104" height="142">
</body>
</html>
48
7. HTML
7.2.6 Tables
Tables:
<table width="200" border="1">
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
<td>d</td>
</tr>
<tr>
<td>e</td>
<td>f</td>
<td>g</td>
<td>h</td>
</tr>
<tr>
<td>i</td>
<td>j</td>
<td>k</td>
<td>l</td>
</tr>
</table>
7.2.7 Comments
Comment:
<!-- Write your comments here -->
49
8 CSS
CSS is a stylesheet language that describes the presentation of an HTML page.
Use HTML to define the content of web pages, CSS is used to specify the layout of web
pages, while JavaScript is used to program the behavior of web pages.
CSS is used to control the style and layout of multiple web pages all at once
Basic Example:
body {
background-color: #d0e4fe;
}
h1 {
color: orange;
text-align: center;
}
p {
font-family: "Times New Roman";
font-size: 20px;
}
– An external style sheet is ideal when the style is applied to many pages. With
an external style sheet, you can change the look of an entire Web site by
changing just one file.
– An external style sheet can be written in any text editor. The file should not
contain any html tags.
– An internal style sheet should be used when a single document has a unique
style.
– You define internal styles in the head section of an HTML page, inside the
<style> tag
• Inline style
– An inline style loses many of the advantages of a style sheet (by mixing
content with presentation). Use this method sparingly!
myfile.html:
...
<head
...
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
..
</head>
...
8.2 Bootstrap
JavaScript/HTML, CSS Framework
Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing
responsive, mobile-first websites.
Home Page:
https://getbootstrap.com
Bootstrap is a popular HTML, CSS, and JavaScript framework for developing responsive,
mobile first projects on the web
Bootstrap is a free and open-source front-end web framework for designing websites and
web applications.
51
8. CSS
It contains HTML- and CSS-based design templates for typography, forms, buttons,
navigation and other interface components, as well as optional JavaScript extensions.
Additional Training:
To use the Free Font Awesome 5 icons, you can choose to download the Font Awesome
library, or you can sign up for an account at Font Awesome and get a code (called KIT CODE)
to use when you add Font Awesome to your web page.
Additional Training:
52
9 JavaScript
JavaScript is the de facto client-side programming language. Typically, you want to use a
JavaScript Framework.
• JQuery
• TypeScript (Microsoft)
JavaScript is the default scripting language in all modern browsers, and in HTML5.
It is the language for HTML, for the Web, for computers, servers, laptops, tablets, smart
phones, and more.
Note that JavaScript and Java are different languages, both in concept and design.
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello JavaScript!";
}
</script>
</body>
</html>
9.2 jQuery
jQuery is a JavaScript Library.
Additional Training:
54
9. JavaScript
9.3 AngularJS
JavaScript Framework developed by Google that has become very popular today.
55
10 Server-side Frameworks
We have many different so-called server-side frameworks for creating dynamic web pages:
• PHP
• Django
• ASP.NET
• Etc.
10.1 PHP
PHP is a server scripting language, and a powerful tool for making dynamic and interactive
Web pages.
10.2 Django
Django is based on the Python programming language.
Do you want to learn more about Python? Here you find lots of Python resources:
https://www.halvorsen.blog/documents/programming/python/
10.3 ASP.NET
ASP.NET is an open-source web framework, created by Microsoft, for building web apps and
services using the .NET Framework or the .NET Core. We have both ASP.NET and ASP.NET
Core. ASP.NET Core is the new approach built on .NET Core.
ASP.NET Core will be the main topic in this document. In this textbook we will go through
ASP.NET Core in detail. In Part 4: ASP.NET Core we start creating ASP.NET Core Web
Applications.
We have:
• ASP.NET Core MVC (Model-View Controller). If you are familiar with the MVC
approach, this could be your choice.
• ASP.NET Core with Razor Pages. This is the latest and recommended way. This has
become the "default" approach for ASP.NET today. It mixes the best from all the
others combined with PHP like syntax (PHP is probably the most popular Web
Framework today)
This textbook will focus on this latest and newest approach, namely ASP.NET Core with
Razor Pages.
• Program.cs – This file contains the entry point for the program.
• wwwroot folder - Contains static files, such as Images, HTML files, JavaScript files,
and CSS files.
• Pages folder – Here you are supposed to put your ASP.NET (".cshtml") web pages
In addition, it is standard to have a folder called “Models”. This folder contains C# classes
that takes care of the data. The data can, e.g., be a database or a file, e.g., a JSON file.
In addition, we have what we call Supporting files. Supporting files have names that begin
with an underscore (_).
• _Layout.cshtml file configures UI elements common to all pages. You can use this file
to set up the navigation menu at the top of the page
11.1 Resources
Here are some important ASP.NET Core resources:
59
11. Introduction to ASP.NET Core
60
11. Introduction to ASP.NET Core
61
11. Introduction to ASP.NET Core
62
11. Introduction to ASP.NET Core
63
11. Introduction to ASP.NET Core
Code:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<h1 class="display-4">Hello World</h1>
</div>
Video:
64
11. Introduction to ASP.NET Core
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor
Razor supports C# and uses the @ symbol to transition from HTML to C#. Razor evaluates C#
expressions and renders them in the HTML output.
This outputs the current date and time in the browser window.
65
11. Introduction to ASP.NET Core
Code:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<h1 class="display-4">Hello World</h1>
</div>
<div>
The current time is: @DateTime.Now
</div>
66
11. Introduction to ASP.NET Core
Index.cshtml.cs:
67
11. Introduction to ASP.NET Core
68
11. Introduction to ASP.NET Core
69
11. Introduction to ASP.NET Core
Example:
public void OnGet()
{
bookId = Convert.ToInt16(Request.Query["bookid"]);
connectionString =
_configuration.GetConnectionString("ConnectionString");
In this example the URL in the web browser could look something like this
https://BookApp/EditBook?bookid=4
70
11. Introduction to ASP.NET Core
If we want to send more than one variable, we use &, for example:
https://BookApp/EditBook?bookid=4&booktitle=Python&author=hamsun
Example
public void OnPost()
{
Book book = new Book();
book.BookId = Convert.ToInt16(Request.Form["bookId"]);
book.Title = Request.Form["bookTitle"];
book.Isbn = Request.Form["bookIsbn"];
book.PublisherName = Request.Form["bookPublisher"];
book.AuthorName = Request.Form["bookAuthor"];
book.CategoryName = Request.Form["bookCategory"];
connectionString =
_configuration.GetConnectionString("ConnectionString");
book.EditBook(connectionString, book);
Response.Redirect("./Books");
}
71
11. Introduction to ASP.NET Core
HTML Code:
<form name="bookForm" id="bookForm" method="post">
Title:
<br />
<input name="bookTitle" type="text" class="form-control
input-lg" autofocus required />
<br />
ISBN:
<br />
<input name="bookIsbn" type="text" class="form-control
input-lg" required />
<br />
Publisher:
<br />
<input name="bookPublisher" type="text" class="form-control
input-lg" required />
<br />
Author:
<br />
<input name="bookAuthor" type="text" class="form-control
input-lg" required />
<br />
Category:
<br />
<input name="bookCategory" type="text" class="form-control
input-lg" required />
72
11. Introduction to ASP.NET Core
<br />
</form>
73
12 ASP.NET Core
Fundamentals
Figure 12-1 shows a typical Solution Explorer in a ASP.NET Core Web Application.
• wwroot
• Models
• Pages
In the wwwroot you should put files like CSS files (in the css folder), JavaScript files (in your
js folder), Images in your images folder. Different libraries like Bootstrap, JQuery, etc. should
be put in the lib folder.
• appsettings.json
• Program.cs
• Startup.cs
• _Layout.cshtml
The web root is the base path to public, non-code, static resource files, such as:
• Stylesheets (.css) – Here you should put your CSS style sheets
• JavaScript (.js) – Here you should put your JavaScript code files
• Images (.png, .jpg, etc.) – This is the folder where you should put all your images
Static files are only served by default from the web root directory (and sub-directories).
In Razor (.cshtml) files, the tilde-slash (~/) points to the web root. A path beginning with ~/ is
referred to as a virtual path.
75
12. ASP.NET Core Fundamentals
12.3 appsettings.json
This file contains configuration data, such as connection strings.
"ConnectionStrings": {
"ConnectionString": "DATA SOURCE=xxx;UID=xxx;PWD=xxx;DATABASE=xxx"
}
Inside “ConnectionStrings” you can have one or more connection strings, let say you have a
development database, a test database and a customer database. This makes it easy to
switch between different connection strings.
"ConnectionStrings": {
"DevelopmentDB": "DATA SOURCE=xxx;UID=xxx;PWD=xxx;DATABASE=xxx"
"TestDB": "DATA SOURCE=xxx;UID=xxx;PWD=xxx;DATABASE=xxx"
}
76
12. ASP.NET Core Fundamentals
Folder: ./Pages/Shared
12.4.1 Layout
The default layout file in ASP.NET Core is “_Layout.cshtml”. You can modify this file so it fits
the ways you want to present your files. This layout will by default be added to al your web
pages (.cshtml files).
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
77
12. ASP.NET Core Fundamentals
A “clean” (removing “everything”, just leave the minimum) _Layout.cshtml may look like
this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - WebApplication</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
If you don’t want to use the _Layout.cshtml on a specific file, set the following on top of
your .cshtml web page:
@{
Layout = "";
}
You can also have multiple Layout files. If you want to use another Layout file than the
default for a specific web page (.cshtml file), you can do something like this:
@{
Layout = "~/Pages/Shared/_Layout2.cshtml";
}
12.5 Models
In the Models folder you suppose to put your C# Classes. You don’t need to name this folder
Models, but that is the recommended name. In that way it will be easier to understand and
modify programs made by others.
78
12. ASP.NET Core Fundamentals
An ASP.NET Razor page has the “.cshtml” (e.g., “Index.cshtml”) file extension. This file
contains a mix of HTML and Razor syntax. The Razor syntax is actually C# code mixed
together with the HTML code.
The Razor parts of the file are executed on the web server before the page is sent to the
client (your web browser).
The Razor page may also have a C# code file linked to it, this file has the extension
“.cshtml.cs” (e.g., “Index.cshtml.cs”). The “.cshtml.cs” file is called the Page Model.
• A “.cshtml” file that contains HTML markup with C# code using Razor syntax.
• A “.cshtml.cs” (“code behind” or “Page model” file) file that contains C# code that
handles page events.
The default Razor page is Index.cshtml. But this can of course be changed if you want to.
When we create a new Razor page (e.g., “Test”) it will look like something like this:
Test.cshtml
@page
@model TestModel
@{
ViewData["Title"] = "Test Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>This is a Razor Page</p>
</div>
The Page Model file (Test.cshtml.cs) or “code behind” file will look something like this:
using System.Collections.Generic;
79
12. ASP.NET Core Fundamentals
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace DemoApp.Pages
{
public class TestModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
}
}
}
namespace DemoApp.Pages
{
public class TestModel : PageModel
{
public string name;
}
}
}
In this example we have declared a public variable. Then later we want to display the value
in our web page (Razor Page (.cshtml)).
80
12. ASP.NET Core Fundamentals
You typically put code that needs to run before the web page is sent to the client in the
OnGet() method.
<div class="text-center">
<h1 class="display-4">Welcome</h1>
</div>
As you see we need to use @Model.xxx where xxx is the name of a public variable in the
Page Model file.
81
12. ASP.NET Core Fundamentals
82
13 Razor
Razor is a markup syntax for embedding server-based code into webpages. The Razor syntax
consists of Razor markup, C#, and HTML. Files containing Razor generally have a .cshtml file
extension.
The default Razor language is HTML. Rendering HTML from Razor markup is no different
than rendering HTML from an HTML file. HTML markup in .cshtml Razor files is rendered by
the server unchanged.
Example:
@{
var number = 1;
}
The value of variables is rendered into HTML by prefixing them with the @ sign.
Example:
The number is @number
Example:
Example:
@{
var numbers = Enumerable.Range(1, 10); //Get numbers from 1 - 10
foreach(var number in numbers)
{
@number
}
}
Comments can be used in different ways, either // for a single line or /* */ for multiple lines.
Example:
// This is a comment
…
/* … */
/*
Multiple Lines
…
…
*/
13.2 Model
Using Model inside a foreach:
Example:
@foreach (var measurement in Model.measurementParameterList)
{
<tr>
<td> @measurement.MeasurementId</td>
<td> @measurement.MeasurementName</td>
<td> @measurement.MeasurementUnit</td>
</tr>
84
13. Razor
85
Part 5 Database
Communication
All modern applications typically communicate with a Database System. Here we will
introduce Database Systems in general and especially Microsoft SQL Server. Then we will
cover Database Communication with C# and ASP.NET Core in combination with SQL Server
from Microsoft.
• SQL Server
• MySQL
• MariaDB
• Etc.
Figure 14-1: ER diagram with Primary Keys and Foreign Keys relationships
SQL Server consists of a Database Engine and a Management Studio (and lots of other stuff
which we will not mention here). The Database engine has no graphical interface - it is just a
service running in the background of your computer (preferable on the server). The
Management Studio is graphical tool for configuring and viewing the information in the
database. It can be installed on the server or on the client (or both).
Videos:
88
14. Database Systems
It is quite simple to create a new database in Microsoft SQL Server. Just right-click on the
“Databases” node and select “New Database…”
89
14. Database Systems
There are lots of settings you may set regarding your database, but the only information you
must fill in is the name of your database:
You may also use the SQL language to create a new database, but sometimes it is easier to
just use the built-in features in the Management Studio.
In order to make a new SQL query, select the “New Query” button from the Toolbar.
90
14. Database Systems
Here we can write any kind of queries that is supported by the SQL language.
• INSERT
• SELECT
• UPDATE
• DELETE
91
14. Database Systems
The Data Manipulation Language (DML) is the subset of SQL used to add, update and delete
data.
The acronym CRUD refers to all of the major functions that need to be implemented in a
relational database application to consider it complete. Each letter in the acronym can be
mapped to a standard SQL statement:
Additional Resources:
14.2.1 Tables
In Figure 14-7 we see an example of some tables for a university or a school. These tables
store information regarding the students, the teacher, the courses, the grades, etc.
92
14. Database Systems
Here are some “Best practice” recommendations for creating tables in a database system:
• Tables: Use upper case and singular form in table names – not plural, e.g.,
“STUDENT” (not students)
• Columns: Use Pascal notation, e.g., “StudentId”
• Primary Keys:
– If the table name is “COURSE”, name the Primary Key column “CourseId”, etc.
– “Always” use Integer and Identity(1,1) for Primary Keys
• Specify Required Columns (NOT NULL) – i.e., which columns that need to have data
or not
• Data Types: Standardize on these Data Types: int, float, varchar(x), datetime, bit
• Use English for table and column names
• Avoid abbreviations! (Use RoomNumber – not RoomNo, RoomNr, ...)
We want to create a table called “CUSTOMER” which has the following columns and data
types:
93
14. Database Systems
Typically, you also want to sue a tool for modelling the database, e.g., Erwin.
Primary keys:
As you see we use the “Primary Key” keyword to specify that a column should be the
Primary Key.
If you use the Designer tools in SQL Server, you can easily set the primary Key in a table just
by right-click and select “Set primary Key”.
94
14. Database Systems
The primary Key column will then have a small key in front to illustrate that this column is
a Primary Key.
Foreign Keys:
Example:
SCHOOL:
CREATE TABLE SCHOOL
(
SchoolId int IDENTITY(1,1) PRIMARY KEY,
SchoolName varchar(50) NOT NULL UNIQUE,
95
14. Database Systems
CLASS:
CREATE TABLE CLASS
(
ClassId int IDENTITY(1,1) PRIMARY KEY,
SchoolId int NOT NULL FOREIGN KEY REFERENCES SCHOOL (SchoolId),
ClassName varchar(50) NOT NULL UNIQUE,
Description varchar(1000) NULL,
)
GO
The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.
The FOREIGN KEY constraint also prevents that invalid data from being inserted into the
foreign key column, because it has to be one of the values contained in the table it points
to.
If you want to use the designer, right-click on the column that you want to be the Foreign
Key and select “Relationships…”:
96
14. Database Systems
Click on the “Add” button and then click on the small “…” button. Then the following
window pops up (Tables and Columns):
Here you specify the primary Key Column in the Primary Key table and the Foreign Key
Column in the Foreign Key table.
97
14. Database Systems
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This means that you
cannot insert a new record or update a record without adding a value to this field.
We see that “CustomerNumber”, “LastName” and “FirstName” is set to “NOT NULL”, this
means these columns needs to contain data. While “AreaCode”, “Address” and “Phone”
may be left empty, i.e, they don’t need to be filled out.
In the Table Designer you can easily set which columns that should allow NULL or not:
UNIQUE:
98
14. Database Systems
The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and
PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of
columns.
Note! You can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
We see that the “CustomerNumber” is set to UNIQUE, meaning each customer must have a
unique Customer Number. Example:
If you want to use the designer, right-click on the column that you want to be UNIQUE and
select “Indexes/Keys…”:
99
14. Database Systems
Then click “Add” and then set the “Is Unique” property to “Yes”:
Very often we would like the value of the primary key field to be created automatically
every time a new record is inserted.
Example:
CREATE TABLE CUSTOMER
(
CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE,
LastName varchar(50) NOT NULL,
FirstName varchar(50) NOT NULL,
AreaCode int NULL,
Address varchar(50) NULL,
100
14. Database Systems
As shown below, we use the IDENTITY() for this. IDENTITY(1,1) means the first value will be 1
and then it will increment by 1.
We can use the designer tools to specify that a Primary Key should be an identity column
that is automatically generated by the system when we insert data in to the table.
Click on the column in the designer and go into the Column Properties window:
14.2.2 Views
Views are virtual table for easier access to data stored in multiple tables.
101
14. Database Systems
Example:
We use the SCHOOL and CLASS tables as an example for our View. We want to create a View
that lists all the existing schools and the belonging classes.
102
14. Database Systems
SELECT
SCHOOL.SchoolName,
CLASS.ClassName
FROM
SCHOOL
INNER JOIN CLASS ON SCHOOL.SchoolId = CLASS.SchoolId
Note! In order to get information from more than one table, we need to link the tables
together using a JOIN.
103
14. Database Systems
14.2.4 Triggers
A database trigger is code that is automatically executed in response to certain events on a
particular table in a database.
104
15 ADO.NET
ADO.NET is the core data access technology for .NET languages.
The great thing about this is that you can use the same C# code either you are creating a
desktop application or a web application.
Typically, you put your C# database code in one or more classes, and those will then be the
same either you are creating a desktop application (which has direct access to the database)
or a web application. If your database does not have direct access to the database (the
database is e.g., located on the internet), you can create and use a so-called Web API (also
called Web Service or REST API). The Web API will then be the middleware between the
desktop application and the database server.
You install these packages using the NuGet Package Manager, see Figure 15-1.
There are many ways and methods we can use to retrieve data from a database. Here we
will focus on something called ADO.NET. ADO.NET can use different so-called Data
Providers. We will use “System.Data.SqlClient”. This will be demonstrated in the Demo
Application below.
The entire example can be downloaded from the home page of this textbook.
16.1.1 Database
In order to create this ASP.NET Core example we need to create a simple database that
consists of a single table called “MEASUREMENT”.
We start by creating the Database in SQL Server Management Studio (Figure 16-2).
Then we create necessary table. We can either create the tables directly using the Table
designer in the SQL Server Management Studio (not shown here) or we can open/create a
SQL script that inserts the table (Figure 16-3).
107
16. Data from Database
Next, we need to create some initial data into the table. We can either create the data
directly using the editor (right-click on the table in the Object Explorer and select “Edit Top
200 Rows”) in the SQL Server Management Studio (See Figure 16-4) or we can open/create a
SQL script that inserts the necessary data (not shown here).
Figure 16-4: Inserting Data manually from SQL Server Management Studio
108
16. Data from Database
Next you need to configure your Project (Figure 16-6) by writing the name. for the project,
where it should be located on your hard drive, etc.
109
16. Data from Database
In the next window (see Figure 16-7) you need to select the proper template. We select the
“Web Application” template.
110
16. Data from Database
Select “Create” in Figure 16-7 and the Visual studio Project will be created based on your
choices. See Figure 16-8.
As you see from Figure 16-8, the following Folders and Files have been created:
• Program.cs – This file contains the entry point for the program.
• wwwroot folder - Contains static files, such as HTML files, JavaScript files, and CSS
files.
• Pages folder – Here you are supposed to put your ASP.NET (".cshtml") web pages
In addition, it is standard to have a folder called “Models”. This folder contains C# classes
that takes care of the data. The data can, e.g., be a database or a file, e.g., a JSON file.
In addition, we have what we call Supporting files. Supporting files have names that begin
with an underscore (_).
111
16. Data from Database
• _Layout.cshtml file configures UI elements common to all pages. You can use this file
to set up the navigation menu at the top of the page
In the Pages folder some default Razor pages have been created, like “Index.cshtml”, etc.
The “Index.cshtml” file is typically the startup file for your web application, but if you want
you can configure this in the Startup.cs file.
Let’s run the application and see if the application can be run inside your web browser. See
Figure 16-9.
112
16. Data from Database
Now we need to start creating the necessary code for our application.
Let’s start to create a Models folder where we are making our Class that do the retrieving of
data from the database. See Figure 16-10. (In the example I have written Model instead of
Models, bit that’s the same)
113
16. Data from Database
Then we create a Class called, e.g., “Measurements.cs” in the Models (Model) folder. See
Figure 16-11.
114
16. Data from Database
namespace MeasurementApp.Model
{
public class Measurement
{
public int MeasurementId { get; set; }
public string MeasurementName { get; set; }
public string MeasurementUnit { get; set; }
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
115
16. Data from Database
if (dr != null)
{
while (dr.Read())
{
Measurement measurmentParameter = new Measurement();
measurmentParameter.MeasurementId =
Convert.ToInt32(dr["MeasurementId"]);
measurmentParameter.MeasurementName =
dr["MeasurementName"].ToString();
measurmentParameter.MeasurementUnit = dr["Unit"].ToString();
measurementParameterList.Add(measurmentParameter);
}
}
return measurementParameterList;
}
}
}
As you see the connection string to the database is hardcoded inside the
“Measurement”class:
string connectionString = "DATA SOURCE=xxx;UID=sa;PWD=xxx;DATABASE=MEASUREMENTDB";
Just replace the “xxx” with the settings for your database.
Make sure to install the necessary NuGet package(s). See Figure 16-13. We need the
System.Data.SqlClient.
Figure 16-13: Make sure the necessary NuGet packages are installed
Then we create our Razor File in the “Pages” folder. Let’s name the file
“Measurement.cshtml”. Make sure to select Razor Page (a Razor Page with a Page Model).
See Figure 16-14.
116
16. Data from Database
A code behind file, also called the Page Model will also be created automatically. See Figure
16-15.
117
16. Data from Database
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using MeasurementApp.Model;
namespace MeasurementApp.Pages
{
public class MeasurementModel : PageModel
{
measurementParameterList = measurement.GetMeasurmentParameters();
}
}
}
Then we can make the contents of the “Measurement.cshtml” file. See Figure 16-16.
<div>
118
16. Data from Database
<h1>Measurement Parameters</h1>
Below you see all the Measurement Names registered in the Database:
<table class="table">
<thead>
<tr>
<th>MeasurementId</th>
<th>Measurement Name</th>
<th>Unit</th>
</tr>
</thead>
<tbody>
@foreach (var measurement in Model.measurementParameterList)
{
<tr>
<td> @measurement.MeasurementId</td>
<td> @measurement.MeasurementName</td>
<td> @measurement.MeasurementUnit</td>
</tr>
}
</tbody>
</table>
</div>
@xxx is the Razor code. The Razor code is executed on the server before the web page is
sent to the client (web browser).
The “Model.” variable is used to retrieve data from the Page Model file
(“Measurement.cshtml.cs”). All public variables that are created in the Measurement.cshtml
.cs file are available in the Measurement.cshtml file by using @Model.<variablename>.
Now, our application should be finished. Let’s run the application in our web browser. See
Figure 16-17.
119
16. Data from Database
where you replaced the “xxx” with the settings for your database.
The user “sa” (System Administrator) is the default user. You can use that one for testing,
but for your final application you should setup and use another user.
16.2.1 appSettings.json
A better solution is to put the connection string inside the “appSettings.json” which is
meant for storing configuration data, such as connection strings, etc.
Let us start by putting the connection string into the “appSettings.json” file:
120
16. Data from Database
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ConnectionString": "DATA SOURCE=xxx;UID=sa;PWD=xxx;DATABASE=MEASUREMENTDB "
}
where you replace the “xxx” with the settings for your database.
namespace MeasurementApp.Model
{
public class Measurement
{
public int MeasurementId { get; set; }
public string MeasurementName { get; set; }
public string MeasurementUnit { get; set; }
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr != null)
{
while (dr.Read())
{
Measurement measurmentParameter = new Measurement();
measurmentParameter.MeasurementId =
Convert.ToInt32(dr["MeasurementId"]);
measurmentParameter.MeasurementName =
dr["MeasurementName"].ToString();
measurmentParameter.MeasurementUnit = dr["Unit"].ToString();
measurementParameterList.Add(measurmentParameter);
}
}
return measurementParameterList;
}
}
121
16. Data from Database
services.AddSingleton<IConfiguration>(Configuration);
}
We have added:
services.AddSingleton<IConfiguration>(Configuration);
namespace MeasurementApp.Pages
{
public class MeasurementModel : PageModel
{
readonly IConfiguration _configuration;
connectionString =
_configuration.GetConnectionString("ConnectionString");
measurementParameterList =
measurement.GetMeasurmentParameters(connectionString);
}
}
}
Now we can run the application. The result should be the same as before, see Figure 16-17.
122
17 CRUD Applications
CRUS is short for:
Create
Read
Update
Delete
The acronym CRUD refers to all the major functions that are implemented for
communication with a database.
We will show how we can use ASP.NET Core to get (read, retrieve, select) data from the
database, insert data into the database, update the data inside the database and deleting
data inside the database.
The entire example can be downloaded from the home page of this textbook.
This example can be the foundation for all types of applications. All web applications
typically show some data from the database in a list or table, then you will typically have
features for add new data, edit/update existing data or delete data.
When I start on a new development project, I just use this application as a template or as a
foundation for my new web application.
124
17 CRUD Applications
125
17 CRUD Applications
126
17 CRUD Applications
17.1.2 Database
We will use the following tables:
AUTHOR:
if not exists (select * from dbo.sysobjects where id =
object_id(N'[AUTHOR]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [AUTHOR]
(
[AuthorId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,
[AuthorName] [varchar](50) NOT NULL UNIQUE,
[Address] [varchar](50) NULL,
[Phone] [varchar](50) NULL,
[PostCode] [varchar](50) NULL,
[PostAddress] [varchar](50) NULL,
)
GO
PUBLISHER:
if not exists (select * from dbo.sysobjects where id =
object_id(N'[PUBLISHER]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [PUBLISHER]
(
[PublisherId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,
127
17 CRUD Applications
CATEGORY:
if not exists (select * from dbo.sysobjects where id =
object_id(N'[CATEGORY]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [CATEGORY]
(
[CategoryId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,
[CategoryName] [varchar](50) NOT NULL UNIQUE,
[Description] [varchar](1000) NULL,
)
GO
BOOK:
if not exists (select * from dbo.sysobjects where id = object_id(N'[BOOK]') and
OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [BOOK]
(
[BookId] [int] IDENTITY(1, 1) NOT NULL PRIMARY KEY,
[Title] [varchar](50) NOT NULL UNIQUE,
[ISBN] [varchar](20) NOT NULL,
[PublisherId] [int] NOT NULL FOREIGN KEY REFERENCES [PUBLISHER] ([PublisherId]),
[AuthorId] [int] NOT NULL FOREIGN KEY REFERENCES [AUTHOR] ([AuthorId]),
[CategoryId] [int] NOT NULL FOREIGN KEY REFERENCES [CATEGORY] ([CategoryId]),
[Description] [varchar](1000) NULL,
[Year] [date] NULL,
[Edition] [int] NULL,
[AverageRating] [float] NULL,
)
GO
128
17 CRUD Applications
“GetBookData” View:
CREATE VIEW GetBookData
AS
SELECT
BOOK.BookId,
BOOK.Title,
BOOK.ISBN,
PUBLISHER.PublisherName,
AUTHOR.AuthorName,
CATEGORY.CategoryName
FROM BOOK
INNER JOIN AUTHOR ON BOOK.AuthorId = AUTHOR.AuthorId
INNER JOIN PUBLISHER ON BOOK.PublisherId = PUBLISHER.PublisherId
INNER JOIN CATEGORY ON BOOK.CategoryId = CATEGORY.CategoryId
GO
129
17 CRUD Applications
130
17 CRUD Applications
We insert the Stored Procedures using SQL Server Management Studio in the same way as
for the tables.
17.1.4 Models
Then we create our models or classes.
131
17 CRUD Applications
Code:
132
17 CRUD Applications
Book Class:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace BookApp.Models
{
public class Book
{
…
public List<Book> GetBooks(string connectionString){}
133
17 CRUD Applications
}
}
GetBooks Method:
public List<Book> GetBooks(string connectionString)
{
List<Book> bookList = new List<Book>();
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr != null)
{
while (dr.Read())
{
Book book = new Book();
book.BookId = Convert.ToInt32(dr["BookId"]);
book.Title = dr["Title"].ToString();
book.Isbn = dr["ISBN"].ToString();
book.PublisherName = dr["PublisherName"].ToString();
book.AuthorName = dr["AuthorName"].ToString();
book.CategoryName = dr["CategoryName"].ToString();
bookList.Add(book);
}
}
return bookList;
}
GetBookData Method:
public Book GetBookData(string connectionString, int bookId)
{
SqlConnection con = new SqlConnection(connectionString);
SqlDataReader dr = cmd.ExecuteReader();
134
17 CRUD Applications
if (dr != null)
{
while (dr.Read())
{
book.BookId = Convert.ToInt32(dr["BookId"]);
book.Title = dr["Title"].ToString();
book.Isbn = dr["ISBN"].ToString();
book.PublisherName = dr["PublisherName"].ToString();
book.AuthorName = dr["AuthorName"].ToString();
book.CategoryName = dr["CategoryName"].ToString();
}
}
return book;
}
CreateBook Method:
public void CreateBook(string connectionString, Book book)
{
try
{
using (SqlConnection con = new
SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("CreateBook", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
EditBook Method:
public void EditBook(string connectionString, Book book)
{
try
{
using (SqlConnection con = new
SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("UpdateBook", con);
cmd.CommandType = CommandType.StoredProcedure;
135
17 CRUD Applications
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
DeleteBook Method:
public void DeleteBook(string connectionString, int bookId)
{
try
{
using (SqlConnection con = new
SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("DeleteBook", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@BookId", bookId));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
NuGet Packages:
136
17 CRUD Applications
137
17 CRUD Applications
Books.cshtml:
@page
@model BookApp.Pages.BooksModel
@{
ViewData["Title"] = "Books";
}
<div>
<h1>Books</h1>
Below you see all the Books in the Book Store:<br />
<table class="table">
<thead>
<tr>
<th>BookId</th>
<th>Title</th>
<th>ISBN</th>
<th>Publisher</th>
<th>Author</th>
<th>Category</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach (var book in Model.books)
{
<tr>
<td> @book.BookId </td>
<td>
<a href="./EditBook?bookid=@book.BookId">
@book.Title
</a> </td>
138
17 CRUD Applications
</div>
Books.cshtml.cs:
…
using BookApp.Models;
namespace BookApp.Pages
{
public class BooksModel : PageModel
{
readonly IConfiguration _configuration;
string connectionString;
books = GetBookList();
bookList = book.GetBooks(connectionString);
return bookList;
}
}
}
139
17 CRUD Applications
NewBook.cshtml:
@page
@model BookApp.Pages.NewBookModel
@{
ViewData["Title"] = "New Book";
}
<div>
<h1>New Book</h1>
Title:
<br />
<input name="bookTitle" type="text" class="form-control
input-lg" autofocus required />
<br />
ISBN:
<br />
<input name="bookIsbn" type="text" class="form-control
input-lg" required />
<br />
Publisher:
<br />
<input name="bookPublisher" type="text" class="form-control
input-lg" required />
<br />
Author:
<br />
140
17 CRUD Applications
Category:
<br />
<input name="bookCategory" type="text" class="form-control
input-lg" required />
<br />
</form>
</div>
NewBook.cshtml.cs:
…
using BookApp.Models;
namespace BookApp.Pages
{
public class NewBookModel : PageModel
{
readonly IConfiguration _configuration;
book.Title = Request.Form["bookTitle"];
book.Isbn = Request.Form["bookIsbn"];
book.PublisherName = Request.Form["bookPublisher"];
book.AuthorName = Request.Form["bookAuthor"];
book.CategoryName = Request.Form["bookCategory"];
connectionString =
_configuration.GetConnectionString("ConnectionString");
book.CreateBook(connectionString, book);
Response.Redirect("./Books");
}
}
}
141
17 CRUD Applications
EditBook.cshtml:
@page
@model BookApp.Pages.EditBookModel
@{
ViewData["Title"] = "Edit Book";
}
<div>
<h1>Edit Book</h1>
Title:
<br />
<input name="bookTitle" type="text"
value="@Model.bookdb.Title" class="form-control input-lg"
autofocus required />
<br />
ISBN:
<br />
<input name="bookIsbn" type="text"
value="@Model.bookdb.Isbn" class="form-control input-lg"
required />
<br />
Publisher:
<br />
<input name="bookPublisher" type="text"
value="@Model.bookdb.PublisherName" class="form-control
142
17 CRUD Applications
Author:
<br />
<input name="bookAuthor" type="text"
value="@Model.bookdb.AuthorName" class="form-control input-
lg" required />
<br />
Category:
<br />
<input name="bookCategory" type="text"
value="@Model.bookdb.CategoryName" class="form-control
input-lg" required />
<br />
</form>
</div>
EditBook.cshtml.cs:
…
using BookApp.Models;
namespace BookApp.Pages
{
public class EditBookModel : PageModel
{
readonly IConfiguration _configuration;
bookId = Convert.ToInt16(Request.Query["bookid"]);
connectionString =
_configuration.GetConnectionString("ConnectionString");
book.BookId = Convert.ToInt16(Request.Form["bookId"]);
book.Title = Request.Form["bookTitle"];
143
17 CRUD Applications
book.Isbn = Request.Form["bookIsbn"];
book.PublisherName = Request.Form["bookPublisher"];
book.AuthorName = Request.Form["bookAuthor"];
book.CategoryName = Request.Form["bookCategory"];
connectionString =
_configuration.GetConnectionString("ConnectionString");
book.EditBook(connectionString, book);
Response.Redirect("./Books");
}
}
}
DeleteBook.cshtml.cs:
…
using BookApp.Models;
using Microsoft.Extensions.Configuration;
namespace BookApp.Pages
{
public class DeleteBookModel : PageModel
{
readonly IConfiguration _configuration;
144
17 CRUD Applications
connectionString =
_configuration.GetConnectionString("ConnectionString");
book.DeleteBook(connectionString, bookId);
Response.Redirect("./Books");
}
}
}
145
Part 6 Additional
ASP.NET Core
Features
Here will some additional ASP.NET Core features be presented. like the use of Session
variables.
Typically, we need to share information between 2 different web pages as shown in Figure
18-1.
Very often we also need to share data between multiple web pages, this could be login
information, etc. See Figure 18-2.
• Cookies
• Session State
• TempData
• Query String
• Hidden fields
• Etc.
Session state is a mechanism that enables you to store and retrieve user specific values
temporarily. The default time is 20 minutes (but can be configured if necessary).
These values can be stored for the duration of the visitor's session on your site. It can be
used to share data between different web pages. It can, e.g., be used to store information if
the user is logged on to the application or not and the Username.
148
18 Session Data
You need to do the following in order to enable Session management in ASP.NET Core:
In the page model files (.cshtml.cs) where you shall use Session variables you need to add
the “Microsoft.AspNetCore.Http” Namespace:
149
18 Session Data
...
using Microsoft.AspNetCore.Http;
...
In order to write to Session Variables in C# we use the SetString() and SetInt32() methods.
Below you see an example:
...
string name;
int age;
HttpContext.Session.SetString("Name", name);
HttpContext.Session.SetInt32("Age", age);
In order to read from Session Variables in C# we use the GEtString() and GetInt32()
methods. Below you see an example:
string name;
int age;
name = HttpContext.Session.GetString("Name");
age = (Int32)HttpContext.Session.GetInt32("Age");
This application consists of 2 web pages. In Page 1 (Page1.cshtml) the user enters some data
into 2 textboxes; Name and Age. When the user clicks the “Save” button, the data is stored
in 2 Session variables. The Name is a String, and the Age is an Integer. Page 2 (Page2.cshtml)
reads the Session variables and present them to the user. See Figure 18-4.
150
18 Session Data
18.2.1 Page1
Let us start creating Page1. Sometimes we start development of the Razor file (.cshtml) and
other times it is smart to start with the Code Behind file (cshtml.cs).
151
18 Session Data
152
18 Session Data
From the webpage (Page1.cshtml) we retrieve the value the user enters in the “Name”
textbox and put the value into the variable “name”:
string name;
name = Request.Form["Name"];
From the webpage (Page1.cshtml) we retrieve the value the user enters in the “Age” input
field and put the value into the variable “age”:
int age;
age = Convert.ToInt32(Request.Form["Age"]);
18.2.2 Page2
Let us start creating Page2.
153
18 Session Data
154
18 Session Data
<p>
Your Name is: @Model.name
</p>
<p>
Your Age is: @Model.age
</p>
</div>
• https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state
• https://www.learnrazorpages.com/razor-pages/session-state
155
Part 7 Charting
Presenting data in charts is important. Here we will see how we can create charts in an
ASP.NET Core application.
• Google Charts
• Charts.js
19.1 Introduction
In Figure 19-1 you see an example where a chart is displayed on web page or a web
application.
158
20 Google Charts
Google Charts is a JavaScript based charting library for presenting different types of charts
on a web page.
Google Charts is an API (or framework) for creating Charts in your web pages. It is free to
use. It is easy to use (when you first know how to use it).
Web Site:
https://developers.google.com/chart
• Line Chart
• Bar Chart
• Column Chart
• Pie Chart
• etc.
160
20 Google Charts
5. Then, later in the web page, you create a <div> with that id to display the Google
Chart.
The entire example can be downloaded from the home page of this textbook.
161
20 Google Charts
The application shown in Figure 20-2 will demonstrate different chart types like “Line
Chart”, “Multi-Line Chart”, “Bar Chart” and “Column Chart”.
Web Page:
<html>
<head>
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales'],
['2004', 1000],
['2005', 1170],
['2006', 660],
['2007', 1030]
]);
var options = {
title: 'Company Performance',
curveType: 'function',
162
20 Google Charts
You should have SQL Server locally installed on your computer (for these examples). SQL
Server Express is recommended for these simple examples, but if you have another version
already, you can of course use that.
For the examples provided here, a simple database will be created, see below:
CREATE TABLE [CHARTDATA]
(
[ChartDataId] int NOT NULL IDENTITY ( 1,1 ) Primary Key,
[ChartTimeStamp] datetime NOT NULL DEFAULT GETDATE(),
[ChartValue] float NOT NULL
)
go
This is a simple database with just one table. The table contains 2 important columns, one
with timestamps, which is typically the x-axis in your chart. The other column is the data
itself, which is typically the y-axis.
Next, we need to add some data in the database. You can just enter some data manually in
order to have some data for the examples. See Figure 20-4.
163
20 Google Charts
• Line Chart
• Bar Chart
• Column Chart
We create a new ASP.NET Core application to demonstrate the different charts. Figure 20-5
shows the Solution Explorer in Visual Studio for our project (“ChartApp”).
164
20 Google Charts
As in previously ASP.NET Core examples we have created 2 folders, namely “Models” and
“Pages”.
In the “Models” folder we create our C# code that communicates and retrieve data from the
database. We create a class called “ChartData.cs” for this.
165
20 Google Charts
Next, we start creating the web pages for displaying the charts. We start with a “Line Chart”.
166
20 Google Charts
Lets starts creating the web page. As you now, a ASP.NET Core web page consists of 2
different files, a Page model file (“.cshtml.cs”), or a “code-behind file and the web page itself
with Razor syntax (“.cshtml”).
C# Code (LineChart.cshtml.cs):
using ChartApp.Models;
namespace ChartApp.Pages
{
public class LineChartModel : PageModel
{
public List<ChartData> chartDataList = new
List<ChartData>();
string connectionString;
readonly IConfiguration _configuration;
public LineChartModel(IConfiguration configuration)
{
_configuration = configuration;
}
public void OnGet()
{
chartDataList = ChartData();
}
private List<ChartData> ChartData()
{
connectionString =
_configuration.GetConnectionString("ConnectionString");
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Time', 'Data'],
@foreach (var data in Model.chartDataList) {
<text>['@data.ChartTimeStamp', @data.ChartValue],</text>
}
167
20 Google Charts
]);
var options = {
title: '@chartTitle',
curveType: 'function',
pointsVisible: true,
lineWidth: 3,
legend: 'none',
hAxis: {title: 'Time'},
vAxis: {title: '@chartUnit'},
width: '100%',
height: '100%',
chartArea: {width: '85%', height: '75%'}
};
var chart = new
google.visualization.LineChart(document
.getElementById('line_chart'));
chart.draw(data, options);
}
</script>
<div class="container-fluid lead">
<div id="line_chart" style="width: 800px; height: 600px"></div>
</div>
The new part in this example compared to the previous example are the part where we get
the build an array with the data from the database:
var data = google.visualization.arrayToDataTable([
['Time', 'Data'],
@foreach (var data in Model.chartDataList) {
<text>['@data.ChartTimeStamp', @data.ChartValue],</text>
}
]);
When running your application, the plot in Figure 20-6 should be the result.
168
20 Google Charts
169
20 Google Charts
170
20 Google Charts
26
In this example we plot 2 lines in the same chart. In this example, the blue line is the same
as in Figure 20-6 , while the red line is just the calculated Fahrenheit value.
@model ChartApp.Pages.MultiLineChartModel
@{
ViewData["Title"] = "MultiLine Chart";
<div class="text-center">
<h1 class="display-4">MultiLine Chart</h1>
</div>
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Time', 'Celsius', 'Fahrenheit'],
171
20 Google Charts
<text>['@data.ChartTimeStamp', @data.ChartValue,
@fahrenheitValue],</text>
]);
var options = {
title: '@chartTitle',
curveType: 'function',
pointsVisible: true,
lineWidth: 3,
legend: 'right',
hAxis: {title: 'Time'},
vAxis: {title: '@chartUnit'},
width: '100%',
height: '100%',
chartArea: {width: '70%', height: '75%'}
};
chart.draw(data, options);
}
</script>
</div>
The only difference from the other examples, is that we need to make 3 columns instead of
2. One column for the “TimeStamp” values, one column for the “Celsius” values, and one
column for the “Fahrenheit” value.
172
21 Chart.js
Chart.js is similar to Google Charts.
Web Site:
https://www.chartjs.org
Benefits:
Figure 22-1 show the .NET Core Class Library template for creating a new Class Library in
Visual Studio.
….
176
22. Class Libraries
In this example we will first create a Class Library, then we will create Applications that are
using the Class Library.
177
22. Class Libraries
• The Class Library, which contains common C# code for the 2 applications
• The BookAdm App. This app is used to configure the books that should be sold in the
BookStore App. The application uses the C# code in the Class Library.
• The BookStore App. This app is used by the customers that want to buy books in the
Book Store. The application uses the C# code in the Class Library.
Figure 22-4: New Project – Class Library (.NET Core) in Visual Studio
178
22. Class Libraries
179
22. Class Libraries
Figure 22-6: Visual Studio Solution with Web Application Project and Class
Library Project
180
22. Class Libraries
Figure 22-9
181
22. Class Libraries
Add Reference:
Figure 22-10
Figure 22-11
182
22. Class Libraries
Figure 22-12
183
22. Class Libraries
Figure 22-13
184
22. Class Libraries
Figure 22-14
185
22. Class Libraries
Figure 22-15
Figure 22-16
186
22. Class Libraries
Figure 22-17
187
23 Web API
Or REST API, Web Service – many names for the same.
Typically, you need to create functionality for User Registration, Login, etc. Here you will see
how this can be done from scratch. If you do it from scratch, you will have full control of
your code.
If you use something called "ASP.NET Core Identity" (which will be explained and
demonstrated in the next chapter) lots of "magic" happens behind the curtains. If something
not working, it may be more complicated to figure out why.
• Hashing
• Salting
• 2 Factor Authentication
• Etc.
Encryption is a two-way function. When you encrypt something, you are doing so with the
intention of decrypting it later.
To encrypt data, you use an algorithm. Many different encryption algorithms do exist
24.1.2 Hashing
Hashing is the practice of using an algorithm to map data of any size to a fixed length.
Encryption is a two-way function. Hashing is a one-way function.
Encryption is meant to protect data in transit, hashing is meant to verify that a file or piece
of data has not been altered—that it is authentic. In other words, it serves as a checksum.
Every hash value is unique.
191
22. Class Libraries
By using something called “Rainbow Table” the hacker can get access to your hashed
password, see Figure 24-3.
Figure 24-3: Using Rainbow Table for Hacking your Hashed Password
If a Hacker gets access to this Database, he can see that Mike and Peter have the same
password, but he does not know the actual password. If the Hacker has access to a so-called
“Rainbow table” (which is essentially a pre-computed database of hashes), he may also be
able to find the Password, as seen in Figure 24-3. If you have a complicated password, it is
less likely that your password is in such a Rainbow table.
192
22. Class Libraries
24.1.3 Salting
Salting is a technique typically used for Password Hashing. It is a unique value that can be
added to the end of the password to create a different hash value. The additional value is
referred to as a “salt”. This is done to make it even more secure. Typically, the Hashing
Algorithm uses a Random salt. This prevents an attacker from seeing whether users have
the same password. See Figure 24-4.
Assume Mike and Peter use the same Password, see Table 24-1. If a hacker gets access to
this database, he cannot see that Mike and Peter have the same password. This is because a
random Salt has made these 2 Hashed Passwords different!
Mike 4420d1918bbcf7
Bob 73fb51a0c9be7d
193
22. Class Libraries
Peter 4520d1818cbcf7
Figure 24-5 shows a typical Flow when Creating User and Login.
24.2 Microsoft.AspNetCore.Identity
This Namespace contains different Classes and Methods for Identity handling. We will use
the PasswordHasher<TUser> Class.
2 important Methods:
• HashPassword(TUser, String)
Returns a hashed representation of the supplied password for the specified user.
194
22. Class Libraries
Example:
using Microsoft.AspNetCore.Identity;
…
string username; //UserName given by user when creating a User
string passwordHashed;
195
22. Class Libraries
196
22. Class Libraries
24.4.1 Login
197
22. Class Libraries
All modern systems offer what we call “2 Factor Authentication”. This means in addition to
enter the password, the user needs to enter a one-time password received on E-Mail or
SMS.
Another basic feature is “Forgot Password?”. Today we have lots of accounts on different
systems. It is recommended that we use different Passwords for these accounts, and it is
easy to forget the password for one or more of these accounts. Because of that we need to
have “Forgot Password” functionality. This means that the user needs to enter his e-mail
address and then the system should send an email (or SMS or similar) with a new temporary
Password that the user needs to change once he is able to logon to the system again.
To increase security it is also normal to have some kind of keyword (What is your
Nickname?, What is your favorite Pet?, etc.) that the user needs to remember before he can
receive a new password.
198
25 ASP.NET Core Identity
25.1 Introduction
We will use ASP.NET Core Identity for creating an Application with built-in Authentication
that has the following features:
• User Registration
• User Login
• 2FA
ASP.NET Core Identity is an API that supports user interface (UI) login functionality out of
the box. You can manage users, passwords, roles, email confirmation, 2FA, and more.
Users can create an account with the login information stored in Identity or they can use an
external login provider.
Supported external login providers include Facebook, Google, Microsoft Account, and
Twitter.
ASP.NET Core Identity offers GUI for creating Users and User Login, 2FA, etc. If you need to
change the layout and behaviors of those “out of the box” provided GUIs, you need to use
“Scaffolding”. Scaffolding is explained below in more detail.
https://en.wikipedia.org/wiki/Scaffolding
Scaffolding, as used in computing, refers to one of two techniques: The first is a code
generation technique related to database access in some model–view–controller
frameworks; the second is a project generation technique supported by various tools.
https://en.wikipedia.org/wiki/Scaffold_(programming)
Applications that include Identity can apply the scaffolder to selectively add the source code
contained in the Identity Razor Class Library (RCL).
You might want to generate source code so you can modify the code and change the
behavior. For example, you could instruct the scaffolder to generate the code used in login
or registration.
Generated code takes precedence over the same code in the Identity RCL.
200
22. Class Libraries
Select Authentication:
Then, in the next window (see Figure 25-2) you need to select “Authentication”.
Change Authentication:
When you click “Authentication” in Figure 25-2, the “Change Authentication” window
appears (see Figure 25-3). Here you then should typically select “Individual User Accounts”.
201
22. Class Libraries
Solution Explorer:
When you have selected proper authentication, your project and files will be created for
you, see Figure 25-4. Lots of new stuff has been created for us that are used by the Identity
features we have enabled.
202
22. Class Libraries
203
22. Class Libraries
Confirm Registration:
204
22. Class Libraries
Login:
205
22. Class Libraries
206
22. Class Libraries
This means in addition to enter the password, the user needs to enter a one-time password
received on E-Mail or SMS.
207
22. Class Libraries
https://www.microsoft.com/en-us/account/authenticator
208
22. Class Libraries
Typically, you need to check in your different web pages if the user is logged in
(authenticated) or not
@User.Identity
• @User.Identity.IsAuthenticated
• @User.Identity.Name
209
22. Class Libraries
Razor Code:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div>
<h1>Welcome</h1>
<p>ASP.NET Core Identity Example Application</p>
<p>Is Authenticated: @User.Identity.IsAuthenticated</p>
<p>UserName: @User.Identity.Name</p>
</div>
210
22. Class Libraries
Figure 25-17
Razor Code:
<div>
<h2>Data</h2>
@if (User.Identity.IsAuthenticated)
{
<p>Show Data here (e.g., from your Database)...</p>
}
else
{
<p>You are not Logged In</p>
}
</div>
25.2.6 Scaffolding
If you are not happy with the default Layout of the different Identity web pages (Register,
Login, etc.) You can override the default Scaffolding and modify these web pages, so they fit
your needs.
211
22. Class Libraries
Figure 25-18
Figure 25-19
212
22. Class Libraries
Figure 25-20
Figure 25-21
Existing Login.cshtml
213
22. Class Libraries
Figure 25-22
Updated Login.cshtml
Figure 25-23
214
22. Class Libraries
215
Part 10 Testing
Introduction to Software Testing.
Figure 27-1
Web Servers are used to host web sites and web pages. The term web server can refer to
either the hardware (the computer) or the software (the computer application) that helps to
deliver web content that can be accessed through the Internet.
Reference: https://en.wikipedia.org/wiki/Web_server
Cross Platform
220
27. Web Servers
Cross Platform
GWS (Google Web Server) Google Custom Linux-based Web server 1.0%
that Google uses for its online
services
221
28 Deployment in Visual
Studio
Publish your application from Visual Studio.
29.1 Installation
IIS – Internet Information Services
Make sure to have the IIS Role installed with ASP.NET subcomponents
C:\inetpub\wwwroot
In order to install IIS and make sure it work with ASP.NET Core Web Applications, you need
to do the following.
• Install the .NET Core Hosting Bundle on the IIS server. If the Hosting Bundle is
installed before IIS, the bundle installation must be repaired. Run the Hosting Bundle
installer again after installing IIS.
In the video the ASP.NET Core Database CRUD Application is used as an example. See
Chapter 17.
The entire example can be downloaded from the home page of this textbook.
224
29. Internet Information Services (IIS)
225
29. Internet Information Services (IIS)
226
Part 12 Microsoft
Azure
Introduction to Microsoft Azure.
A cloud platform from Microsoft, a competitor to AWS, Google Cloud Platform, etc.
Web:
https://azure.microsoft.com/
Web:
https://portal.azure.com
Figure 31-1: Create and Configure your Azure SQL Databases in Azure Portal
Download:
https://docs.microsoft.com/en-us/sql/azure-data-studio/
Your local Management Studio: You connect to the Windows Azure SQL Server Database in
the same way as you connect to a local Database
Create Tables, Views, Stored Procedures, etc. -> using a SQL Script is recommended!
230
31. Databases in Azure
Azure Data Studio is a cross-platform (Windows, macOS, Linux) down-scaled version of SQL
Server Management Studio (Windows only).
Web Site:
https://docs.microsoft.com/sql/azure-data-studio
231
32 Web Applications in
Azure
App Services is a container (Web Server) for web pages and other web services like REST
API, etc.
You could say it is the Azure version of Internet Information Services (IIS). IIS is a web server
software from Microsoft.
Deploy the Web Project to the Azure Web App from Visual Studio.
233
Part 13 Resources
Additional resources.
Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing
responsive, mobile-first websites.
Web Site:
https://getbootstrap.com
Bootstrap is a popular HTML, CSS, and JavaScript framework for developing responsive,
mobile first projects on the web
Bootstrap is a free and open-source front-end web framework for designing websites and
web applications.
It contains HTML- and CSS-based design templates for typography, forms, buttons,
navigation and other interface components, as well as optional JavaScript extensions.
Additional Training:
To use the Free Font Awesome 5 icons, you can choose to download the Font Awesome
library, or you can sign up for an account at Font Awesome and get a code (called KIT CODE)
to use when you add Font Awesome to your web page.
Web Site:
https://fontawesome.com
Additional Training:
https://www.w3schools.com/icons/fontawesome5_intro.asp
Web Site:
https://www.halvorsen.blog/documents/software/weather/
The Weather System is based on a Capricorn 2000ex Weather Station with Weather
MicroServer from Columbia Weather Systems.
Main applications:
Multiple programming languages and frameworks has been used in the development if this
system, some examples are LabVIEW, C#, ASP.NET, PHP, JavaScript, CSS, Bootstrap, etc.
Different database systems are also in use, e.g., SQL Server (both local and in Microsoft
Azure), MySQL/MariaDB.
Web Servers that are used are Apache running on a Linux server, Internet Information
Services (App Service) running on Microsoft Azure.
The source code for the application presented below is available from the home page of this
textbook.
In the menu we have different files for the different features like:
• Today
• Weather
• Charts
• Parameters
• Weather Information
239
35. Weather System
• About
35.2 Database
The database structure is very basic.
MEASUREMENT table:
CREATE TABLE [MEASUREMENT]
(
[MeasurementId] int NOT NULL IDENTITY ( 1,1 ) Primary Key,
[MeasurementName] varchar(100) NOT NULL UNIQUE,
[MeasurementAlias] varchar(100) NULL,
[Unit] varchar(50) NULL
)
MEASUREMENTDATA table:
CREATE TABLE [MEASUREMENTDATA]
(
[MeasurementDataId] int NOT NULL IDENTITY ( 1,1 ) Primary Key,
[MeasurementId] int NOT NULL Foreign Key REFERENCES MEASUREMENT(MeasurementId),
[MeasurementTimeStamp] datetime NOT NULL ,
[MeasurementValue] float NOT NULL
)
SELECT
MEASUREMENTDATA.MeasurementDataId,
MEASUREMENT.MeasurementId,
MEASUREMENT.MeasurementName,
MEASUREMENT.MeasurementAlias,
MEASUREMENTDATA.MeasurementTimeStamp,
MEASUREMENTDATA.MeasurementValue,
MEASUREMENT.Unit
FROM MEASUREMENTDATA
INNER JOIN MEASUREMENT ON MEASUREMENTDATA.MeasurementId = MEASUREMENT.MeasurementId
GO
240
35. Weather System
DECLARE
@MeasurementId int
GO
241
35. Weather System
• Index.cshtml
• Weather.cshtml
• Chart.cshtml
• WeatherParameters.cshtml
• WeatherInformation.cshtml
• About.cshtml
• WeatherParameters.cs
• WeatherData.cs
• ChartData.cs
where you replaced the “xxx” with the settings for your database.
The user “sa” (System Administrator) is the default user. You can use that one for testing,
but for your final application you should setup and use another user.
35.4.1 appSettings.json
A better solution is to put the connection string inside the “appSettings.json” which is
meant for storing configuration data, such as connection strings, etc.
"ConnectionStrings": {
242
35. Weather System
where you replace the “xxx” with the settings for your database.
In this web application, the index file shows the current weather in a formatted way.
<div class="text-center">
<h1 class="display-4">Weather Today</h1>
</div>
<div class="text-lg-right">
<h3>@DateTime.Now.ToString("yyyy-MM-dd HH:mm")</h3>
</div>
<p> </p>
<h3>@Html.Raw(Model.weatherTemperatureText)</h3>
<h3>@Html.Raw(Model.weatherWindSpeedText)</h3>
<p> </p>
</div>
243
35. Weather System
Error! Reference source not found.) we see an example where Google Charts are used in an
ASP.NET Core Web Weather System Application.
244
35. Weather System
<div class="text-center">
<h1 class="display-4">Chart</h1>
</div>
245
35. Weather System
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Time', 'Data'],
<text>['@data.MeasurementTimeStamp',
@data.MeasurementValue],</text>
]);
var options = {
title: 'MeasurementName',
curveType: 'function',
pointsVisible: true,
lineWidth: 3,
legend: 'none',
hAxis: {title: 'Time'},
vAxis: {title: 'Unit'},
width: '100%',
height: '100%',
chartArea: {width: '85%', height: '75%'}
};
chart.draw(data, options);
}
</script>
<h1>@Model.measurementName</h1>
</div>
namespace WeatherSystem.Pages
{
public class ChartModel : PageModel
{
public string measurementName;
string connectionString;
246
35. Weather System
measurementName = Request.Query["measurementname"];
chartDataList = ChartData();
chartDataList = chartData.GetChartData(connectionString,
measurementName);
return chartDataList;
}
}
}
Model (“ChartData.cs”):
…
using System.Data.SqlClient;
namespace WeatherSystem.Models
{
public class ChartData
{
public int MeasurementDataId { get; set; }
public string MeasurementTimeStamp { get; set; }
public string MeasurementValue { get; set; }
247
35. Weather System
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr != null)
{
while (dr.Read())
{
ChartData chartData = new ChartData();
chartData.MeasurementDataId =
Convert.ToInt32(dr["MeasurementDataId"]);
chartData.MeasurementTimeStamp =
dr["MeasurementTimeStamp"].ToString();
chartData.MeasurementValue =
dr["MeasurementValue"].ToString();
chartDataList.Add(chartData);
}
}
return chartDataList;
}
}
}
248
35. Weather System
249
35. Weather System
250
35. Weather System
Below, the necessary steps for deploying the application to Microsoft Azure is presented.
Both the database and the web application will be deployed to Microsoft Azure.
When you have setup the web application, you need to make sure it has access to the
database. See Figure 35-9.
251
35. Weather System
Figure 35-9: Make sure the Web Application has Access to the Database
252
36 Voting System
Here will the “Voting System” application be presented. It can be used as an online Voting
System, e.g., vote for best athlete, best book, best song, best web page, etc. Only the
imagination limits what this application can be used for.
• CRUD functionality
• Query String Data
• Form Data
• Session Data
• Charts
• Login Features
• Etc.
The entire example can be downloaded from the home page of this textbook.
Figure 36-1 shows the Start Page (Index) page of the application.
254
35. Weather System
Figure 36-3 show the web page for presenting the results from the votes.
255
35. Weather System
256
37 Data Management
System (DMS)
The intention is to create an Open Source Cloud Platform for Data Management,
Datalogging and Data Analysis based on open standards.
Main Features:
Figure 37-2 shows the Data Management and Monitoring web application.
Web Site:
https://www.halvorsen.blog/documents/software/dmm/
Figure 37-3 shows the web interface for the Data Management System (DMS) after Login.
258
37. Data Management System (DMS)
Figure 37-4 and Figure 37-6 shows Web-based Data Management for setting up Devices and
respective Tags for the different Devices. Here we have configured the Device Weather
Station to have the Tag Temperature.
259
37. Data Management System (DMS)
260
37. Data Management System (DMS)
261
37. Data Management System (DMS)
262
Web Programming
ASP.NET Core