Mohan PDF
Mohan PDF
Learning Web Technology is essential today because Internet has become the
number one source to information, and many of the traditional software applications have
become Web Applications. Web Applications have become more powerful and can fully
replace desktop application in most situations.
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).
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.
Desktop Applications
Desktop Applications comes in many flavors:
Windows Forms Apps are the oldest but are still very popular.
Web Applications
Web Applications use a mix of different technologies and different programming
languages.
We have:
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.
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”).
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.
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:
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.
4
Figure 2-1: ASP.NET
• 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 programmi
• 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).
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
Visual Studio
Microsoft Visual Studio is an integrated development environment (IDE) from
Microsoft. It can be used to develop console and graphical user interface applications along
with Windows Forms applications, web sites, web applications, and web services, etc.
.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.
This means you have all the necessary tools available to create great web applications using
C# on your Mac.
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.
WPF Application
This is a newer approach for creating desktop applications in Visual Studio. It has a
deeper separation of the GUI and the code.
Universal Applications
This is an attempt to make universal application that works on any kind of
devices from desktops to mobile phones.
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.
11
• appSettings.json – This file contains configuration data, such as connection strings.
• 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
Resources
Here are some important ASP.NET Core resources:
12
13
14
Code:
@page
@model IndexModel
15
@{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<h1 class="display-4">Hello World</h1> </div>
16
Basic Examples
Razor supports C# and uses the @ symbol to transition from HTML to C#. Razor
evaluates C# expressions and renders them in the HTML output.
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>
17
Let’s add a message in addition to the datetime.
18
using System;
using System.Collections.Generic; using
Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages; using
Microsoft.Extensions.Logging; namespace HelloWorld.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger; public string message =
"How are you today?"; public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
19
Query String Data
Typically, we need to send data between different web pages or between the same web page.
In this case we typically send data or information through the query string.
Example:
public void OnGet()
{
bookId = Convert.ToInt16(Request.Query["bookid"]);
Book book = new Book();
connectionString =
_configuration.GetConnectionString("ConnectionString");
}
In this example the URL in the web browser could look something like this
https://BookApp/EditBook?bookid=4
If we want to send more than one variable, we use &, for example:
https://BookApp/EditBook?bookid=4&booktitle=Python&author=hamsun
20
Form Data
Typically, the user enter data into different fields on a web page. In order to send
these data to the server for some kind of processing (e.g., store the data in a database) we use
Form Data.
Example
public void OnPost()
{
Book book = new Book();
connectionString =
_configuration.GetConnectionString("ConnectionString");
book.EditBook(connectionString, book);
Response.Redirect("./Books"); }
HTML Code:
<form name="bookForm" id="bookForm" method="post">
Title:
<br />
<input name="bookTitle" type="text" class="form-control input-lg" autofocus required />
<br />
21
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 />
<br />
</form>
22
ASP.NET Core Fundamentals
• 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
Startup Class
Initial code for your application.
Web root
The web root is by default the “wwwroot” folder.
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.
appsettings.json
This file contains configuration data, such as connection strings.
24
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"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" }
Shared Pages
The shared pages have an underscore in their names, e.g., _Layout.cshtml.
Folder: ./Pages/Shared
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).
25
<!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>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-page="/Index">WebApplication</a> <button class="navbar-toggler"
type="button" data-toggle="collapse" datatarget=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a> </li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asppage="/Privacy">Privacy</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<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>
@RenderSection("Scripts", required: false)
</body>
</html>
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>
@RenderSection("Scripts", required: false)
</body>
26
</html>
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";
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.
Razor Pages
Razor pages should be placed in the default folder called “Pages”. Typically, your start page
should be named “Index.cshtml”.
27
All Razor pages needs to start with the @page directive.
The Page Model file (Test.cshtml.cs) or “code behind” file will look something like this:
using System.Collections.Generic;
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)).
28
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.
Additional Resources
ASP.NET Core fundamentals:
https://docs.microsoft.com/enus/aspnet/core/fundamentals/
29
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.
Razor Syntax
Razor supports C# and uses the @ symbol to transition from HTML to C#. Razor evaluates
C# expressions and renders them in the HTML output.
Example:
@{
var number = 1;
}
The value of variables is rendered into HTML by prefixing them with the @ sign.
Example:
The number is @number
Example:
13. Razor
Comments can be used in different ways, either // for a single line or /* */ for multiple lines.
Example:
// This is a comment
…
/* … */
/*
Multiple Lines
…
…
*/
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
Database Systems
A Database is a structured way to store lots of information. The information is stored in
different tables.
• SQL Server
• MySQL • MariaDB
• Etc.
SQL Server
SQL Server is a Database System from Microsoft. SQL Server comes in different editions,
for basic, personal use SLQ Server Express is recommended because it is simple to use and
it is free.
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).
33
It is quite simple to create a new database in Microsoft SQL Server. Just right-click on the
“Databases” node and select “New Database…”
34
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.
35
Here we can write any kind of queries that is supported by the SQL language.
• INSERT
• SELECT
• UPDATE
• DELETE
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:
36
Additional Resources:
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.
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
37
• 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:
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.
38
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”.
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,
39
Description varchar(1000) NULL,
Address varchar(50) NULL,
Phone varchar(50) NULL,
PostCode varchar(50) NULL,
PostAddress varchar(50) NULL,
)
GO
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…”:
40
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.
The NOT NULL constraint enforces a column to NOT accept NULL values.
41
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:
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.
42
If we take a closer look at the CUSTOMER table created earlier:
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,
Phone varchar(50) NULL,
)
GO
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…”:
Then click “Add” and then set the “Is Unique” property to “Yes”:
43
AUTO INCREMENT or IDENTITY:
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,
Phone varchar(50) NULL,
)
GO
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:
44
Views
Views are virtual table for easier access to data stored in multiple tables.
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.
SELECT
SCHOOL.SchoolName,
45
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.
Stored Procedures
A Stored Procedure is a precompiled collection of SQL statements. In a stored procedure you
can use if sentence, declare variables, etc.
Triggers
A database trigger is code that is automatically executed in response to certain events on a particular
table in a database.
46
ure 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.