0% found this document useful (0 votes)
12 views620 pages

APBD

Uploaded by

michaltulej1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views620 pages

APBD

Uploaded by

michaltulej1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 620

APBD – LECTURE

1
I N T R O D U C T I O N TO V C S
I N T R O D U C T I O N TO . N E T
BASICS OF C#
TERMINAL/KONSOLA
• Mimo tego, że przyzwyczajeni jesteśmy do pracy z interfejsem graficznym, w czasie naszych
zajęć poznamy kilka podstawowych komend związanych z terminalem/konsolą.
• Umięjętność pracy z terminalem/konsolą jest często niezbędna – wiele narzędzi
wykorzystywanych w trakcie pracy and oprogramowaniem ma wyłącznie interfejs w postaci
konsoli/terminalu.
• Wiele narzędzi z interfejsem graficznych oferuje więcej możliwości w sytuacji korzystana z
terminalu/konsoli
BASICS OF WORKING IN TERMINAL
• cd folderName changing the root directory
• cd .. going one level up in the directory structure
• cd „C:\Users\Piotr\Desktop\Projects” you can also provide full path to file

• mkdir nameOfDir creating a new directory with specific name


• rmdir nameOfDir removing a directory with specific name
• ls listing files in the current location (names,
permissions, creationd date, etc.)
• clear removing text from the console
• pwd print the current path

Additional materials - https://www.youtube.com/watch?v=5XgBd6rjuDQ


https://www.youtube.com/watch?v=Us3G-nJYru0
BASICS OF WORKING IN TERMINAL
• You can git the up button to get the previous command you have typed in
WHAT IS “VERSION CONTROL”, AND
WHY SHOULD YOU CARE?
• Version control is a system that records changes to a file or set of files over
time so that you can recall specific versions later.
• If you are a graphic or web designer and want to keep every version of an
image or layout you have designed
• If you are a programmer you want to keep track of the changes in code
(especially if you are working in a team).
• It allows you to revert selected files back to a previous state, revert the entire
project back to a previous state, compare changes over time, see who last
modified something that might be causing a problem, who introduced an issue
and when, and more.
WHAT IS “VERSION CONTROL”, AND
WHY SHOULD YOU CARE?
Using a VCS also generally means that if you
screw things up or lose files, you can easily
recover. In addition, you get all this for very
little overhead.
LOCAL VERSION CONTROL SYSTEMS
• The simplest example of the local version control system
– Simply copying the work „just in case” – so that we won’t by any change destroy our previous work
CENTRALIZED VERSION CONTROL
SYSTEMS
• Next major problem that people encounter was the
need to collaborate with developers on the same
codebase/system.
• To deal with this problem a Centralized Version
Control Systems (CVCSs) were created – for ex. CVS,
Subversion, Perforce)
CENTRALIZED VERSION CONTROL
SYSTEMS
CENTRALIZED VERSION CONTROL
SYSTEMS
• CVCSs have a lot of advantages – for ex. everyone knows to a certain degree what everyone
else on the project is doing.
• Administrators can control exactly who can do what
• The downside is that CVCS has a single point of failure. If the server goes down for an hour
– nobocy can collaborate at all, save the changes or do anything else.
• If the hard disk of the central database becomes corrupted, and proper backups haven’t been
kept – we lose absolutely everything – entire history of the project. Only local snapshosts on
users’ local machiune wil be left out.
DISTRIBUTED VERSION CONTROL
SYSTEMS
• DVCSs (Git, Mercurial, Bazaar, Darcs) – is the answer to previous problems. In DVCSs the
clients dont just check the latests snapshot of the files. They fully mirror the repository,
including its full history.
• Even if the server will die, we can still re-create the whole repository history just from a single
copy.
DISTRIBUTED VERSION CONTROL
SYSTEMS
GIT – KRÓTKA HISTORIA
• Git został stworzony przez Linusa Torvaldsa w 2005 roku jako system kontroli wersji do
zarządzania kodem źródłowym jądra Linuxa. Przed Git'em, Linus korzystał z systemu kontroli
wersji o nazwie BitKeeper, ale zrezygnował z niego po tym, jak firma, która go rozwijała,
zablokowała niektóre funkcje, co wywołało kontrowersje w społeczności Linuxa.
• W odpowiedzi na ten problem, Linus postanowił stworzyć własny system kontroli wersji, który
byłby szybki, wydajny i rozproszony, umożliwiając każdemu programiście pracę niezależnie od
reszty zespołu. Git został wydany jako oprogramowanie o otwartym kodzie źródłowym i
szybko zyskał popularność nie tylko wśród programistów Linuxa, ale również w całym świecie
programistycznym, stając się jednym z najpopularniejszych systemów kontroli wersji.
WHY WE ARE USING GIT?
• Free
• Open source
• Fast
• Scalable
• Often the main version control system used in many companies you will be working with.
• Allow you to easily track history and collaborate on a single project
• Probably the most often used version control system
GIT - TOOLS
• Git is a console tool.You can download it here
, https://git-scm.com/downloads

• During the installation you can pick all the default choices
• There are a lot of GUI tools for Git and we will also use a few of them – Source Treem Git
Kraken etc.
• On the same website you can also find a free book about Git
https://git-scm.com/book/en/v2

• Remember that GUI tools won’t allow you to use all the functionality that Git offers. Thats why
its good to learn the basics of working in the terminal.
GIT - CONFIGURATION
• We have a few settings we should set up after installing Git.
• Git allows us to set configuration at a few levels:
– System – for all users
– Global – for all repositories of the current user
– Local – the current directory
• There are a few things we should set up: our user email, user name and how to deal with line
endings.

git config –global user.name „Piotr Gago”


git config –global user.email „[email protected]
GIT - CONFIGURATION
• One more thing we should deal with are line endings.
• git config –global core.autocrlf true on Windows
• git config –global core.autocrlf input on Mac/Linux
GIT - HELP
• You can get help about specific command in git using:
– git config –help this way we will get help about the config command
– https://git-scm.com/docs official documentation
ADDITIONAL CONSOLE TOOLS
• To make working with git a little easier you can install additional tools. They will help you to
visualize in the console the state of the current git repository.
• They are not required.
• It works on Windows
• https://github.com/dahlbyk/posh-git
GIT – CREATING A NEW REPOSITORY
• To create a new in the current location we use the following command:
• git init
• In the example below it means that the whole content of the „MyApp” folder will be under
version control system.
GIT WORKFLOW
GIT COMMIT

• Every commit represents a full snapshot of


the specific version of our repository (from
specific point in time)
GIT WORKFLOW - EXAMPLE
GIT – CHECKING THE STATUS OF
REPOSITORY
• git status
GIT – STAGING FILES
• git add program.txt
• git add models/*
• git add *.java
• git add . adding all detected changes to staging area
GIT – CREATE COMMIT
• git commit –m „Short description of the commit”
• git commit without the „m” parameter – you will need to type the message in
default text editor for Git.
GIT – COMMITTING – BEST
PRACTICES
• The size of the commit matters. Commit should not be too small, for ex:
– „Added System.out.println”
– „Added int a”
– „Added field FirstName to student”
• Too many small commits make history hard to follow. We have thousands of commits
representing tiny changes.
GIT – COMMITTING – BEST
PRACTICES
• Too large commits are also a „bad thing”.
• Typical commit size is up to 100-150 lines of code
GIT – COMMITTING – BEST
PRACTICES
• How to describe your commit?
– Commit message should be short
– Descriptive
– It can include link or id of the task assigned in some kind of tasking system (for ex. Jira)
– We can use:
• PRESENT: Fix the bug associated with FB login
• PAST: Fixed the bug associated with FB login
GIT – DISPLAY HISTORY
• We can display the local history using the following commands.
• git log
• git log –oneline
• git log –oneline –reverse
GIT – IGNORING FILES
• Sometimes, we can encounter individual files that we should not store in the
repository.
• We can use .gitignore file to „tell git” which files should be ignored by it.
• It will only work if the ignored files are not yet added to the history of the
repository
• Examples of .gitignore files can be found at
https://github.com/github/gitignore
GIT – DISCARDING THE LOCAL CHANGES
• Sometimes you may like to remove the current/unsaved changes from the repository.
• We can think about it as resetting the repository to the last saved commit
• git reset –hard
• git clean -df
GIT – RESTORE A FILE TO THE
PREVIOUS VERSION
• We can restore any previously saved file and save it as the new commit
• git restore --source=HEAD~1 Program.java
GIT – EXAMPLE IN INTELLIJ
• During our exercises please use JetBrains IntelliJ IDEA for Java development
• You can download a free, community version
• There are versions for Windows/Mac/Linux
• https://www.jetbrains.com/idea/download/#section=windows
GIT – GITHUB, BITBUCKET, GITLAB
• Git by itsels save the changes only to our local database. It does not provide any way of sharing
the repository with other users.
• For this purpose we usually use additional services/websites like:
– https://github.com/
– https://bitbucket.org/
– https://about.gitlab.com/
– And others...
• Often companies have their own, private servers for code repositories
• We will use GitHub during the course of our subject.
GIT - BRANCH
• Branch is represented by a list of connected commits. Those commits represent the history of
our repository.
• We can have more than a single branch.
GIT – RÓZNE METODY ORGANIZACJI
PRACY NA GAŁĘZIACH
• Jest wiele metodyk/strategii pracy z Git’em. Większość firm ma własne metody pracy z Git’em.
• Przykłady takich strategii:
– Gitflow Workflow (traktowany obecnie jako nieco zbyt skomplikowany sposób pracy)
• https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow
– Trunk based development
• https://trunkbaseddevelopment.com/

• https://buddy.works/blog/5-types-of-git-workflows
GIT – EXAMPLE OF TRACKING REMOTE
REPOSITORY
• git remote add server https://github.com/gagop/test-repo.git
• git push --set-upstream server master
GIT – MOVING CHANGES TO THE SERVER
• There is one more important command which allows us to move our changes to the remove
server.
• git push
ADDITIONAL SOURCES ABOUT GIT
• https://www.youtube.com/watch?v=Ebe9D5zRkvM
• https://www.youtube.com/watch?v=SWYqp7iY_Tc
• https://www.youtube.com/watch?v=D6EI7EbEN4Q&list=PLjHmWifVUNMKIGHmaGPVqSD-
L6i1Zw-MH

• In additional PDF that will be uploaded with this presentation you can find a cheatsheet with
useful git commands
.NET BASICS
• .NET 7, .NET Framework, .NET Core, Xamarin – are related and overlapping platforms for
developers used to build applications and services
.NET 7
• .NET 7 is the latest version of the .NET framework, which is a free, open-source, cross-
platform framework for building modern applications. It is the successor of .NET Core 3.1 and
.NET 5.0, and it brings several new features, performance improvements, and bug fixes. .NET 7
includes new language features, improved garbage collection, better support for ARM
processors, and enhancements to the .NET runtime and SDK.
XAMARIN
• Xamarin is a free, open-source platform for building cross-platform mobile applications. It was
acquired by Microsoft in 2016 and is now part of the .NET ecosystem. Xamarin allows
developers to write mobile applications using C# and the .NET framework and share code
across multiple platforms, including iOS, Android, and Windows. Xamarin includes a set of tools
and libraries that make it easy to build native user interfaces and access device-specific APIs.
.NET CORE
• .NET Core is an open-source, cross-platform framework for building modern applications. It
was developed by Microsoft and released in 2016. .NET Core was designed to be modular,
lightweight, and optimized for performance. It includes a runtime, libraries, and tools for
building applications for Windows, Linux, and macOS. .NET Core has been replaced by .NET 5
and .NET 6, which include all the features of .NET Core and are designed to be used for new
projects.
.NET FRAMEWORK
• The .NET Framework provides a
common language runtime (CLR), which
is responsible for managing memory,
security, and other system services, and
a class library, which provides a set of
APIs for interacting with the operating
system, file system, network, and other
resources. The framework also supports
a variety of programming models,
including object-oriented programming,
component-based development, and
event-driven programming.
• .NET Framework is a development
platform that includes a Common
Language Runtime (CLR) and Base Class
Library (BCL)
• .NET Framework was originally
designed to be cross-platform
.NET FRAMEWORK 4.7.2
• Since .NET Framework 4.7.2 it became an official component of Windows operating system
• All the apps on a computer written in .NET Framework share the same versin of the CLR and
libraries stored in Global Assembly Cache (GAC), which can lead to issues if some of
them need a specific version for compatibility
• Practically speaking, .NET Framework is Windows-only and a legacy platform.
.NET CORE
• Microsoft started to work on decoupling the .NET from Windows
• This meant rewriting a lot of the code – this version of .net was branded .NET Core
• .NET Core includes a cross-platform implementation of a CLR known as CoreCRL and a
streamlined library of classes known as CoreFX
• At the conference in May 2020, the .NET team announced that their plan for the unification of
.NET had been delayed
• The schedule .NET 5 to be released November 10, 2020 and it would unify all the various
.NET platforms except mobile.
.NET RUNTIME AND SDK VERSIONS
• .NET Runtime versioning follows semantic versioning
– https://semver.org/lang/pl/
• .NET SDK does not follow semantic versioning
WHAT IS A .NET STANDARD?
• Microsoft at some point had to suport three forked platforms for programming:
– .NET Core
– .NET Framework
– Xamarin
• .NET Standard is a specification for a set of APIs that all .NET platforms could implement to
indicate what level of compatibility they have.
• By the end of 2021, Microsoft promises that there will be a single .NET platform
• .NET 6 is planned to have a single BCL and two runtimes: one optimized for server or desktop
scenarios and one optimized for mobile apps on the Xamarin runtime.
WHAT IS A .NET STANDARD?
• .NET Standard is a specification for a set of common APIs that are shared across all .NET
platforms, including .NET Framework, .NET Core, and Xamarin. The goal of .NET Standard is
to enable developers to write code that can run on any .NET platform, without having to
worry about platform-specific APIs or dependencies.
• .NET Standard defines a set of APIs that are guaranteed to be available on any platform that
implements the standard. These APIs include basic types and classes, such as strings, collections,
and IO, as well as more advanced functionality, such as threading, networking, and cryptography.
• By targeting .NET Standard in their projects, developers can write code once and run it on any
platform that supports .NET Standard. This simplifies the development process and makes it
easier to write cross-platform code.
• The .NET Standard specification is versioned, and each version defines a different set of APIs
that are available. Developers can target a specific version of .NET Standard based on the
requirements of their project and the platforms they need to support.
.NET STANDARD
C# LANGUAGE
• C# is a modern, object-oriented, and type-safe programming language.
• C# has its roots in the C family of languages and will be immediately familiar to C, C++, Java,
and JavaScript programmers.
• C# is an object-oriented, component-oriented programming language.
• Garbage collection - automatically reclaims memory occupied by unreachable unused
objects.
• C# programs run on .NET, a virtual execution system called the common language runtime
(CLR) and a set of class libraries.
• The CLR is the implementation by Microsoft of the common language infrastructure (CLI), an
international standard.
C# VS JAVA
• Syntax
• C# and Java have similar syntax and both are influenced by C++. However, C# syntax is
considered to be more concise and expressive, while Java is considered to be more verbose.

• Platform
• C# is primarily used for building applications that run on the Microsoft .NET framework, while
Java is used for building applications that run on the Java Virtual Machine (JVM). However, both
languages are capable of building cross-platform applications.

• Memory Management:
• Both C# and Java use garbage collection to automatically manage memory allocation and
deallocation. However, C# provides more control over the garbage collector than Java does,
allowing developers to optimize memory usage.
C# VS JAVA
• Performance
• In terms of performance, both C# and Java are considered to be highly efficient. However, C#
is often considered to be faster than Java due to its more efficient garbage collector and better
support for multi-threading.

• Libraries
• Both C# and Java have extensive libraries that provide a wide range of functionality for building
applications. However, C# has a larger set of libraries for building Windows-specific
applications, while Java has a larger set of libraries for building enterprise-level applications.
VISUAL STUDIO
• Solution Explorer
• Git Changes
• Build -> Build Solution
• Debug -> Start Debugging
• Debug -> Start Without Debugging
• Check the structure of the project on disk

• Additional materials
– https://www.youtube.com/watch?v=5AOp8zFu4Vg
– https://www.youtube.com/watch?v=1CgsMtUmVgs
C# - HISTORY
C# - SYNTACTIC SUGAR
• C# lets you declare local variables without giving them explicit types. It is possible with the
help of the “var” type variable. The “var” keyword is used to declare a var type variable.
• In C#, the string keyword is an alias for String. Therefore, String and string are equivalent. The
convention is however to use string.
C# - NAMESPACES
• Namespaces are used in C# to organize and provide a level of separation of codes.
• They can be considered as a container which consists of other namespaces, classes, etc. A
namespace can have following types as its members: Namespaces (Nested Namespace)
C# - PROPERTIES
C# - ATTRIBUTES
C# - HELP WITH EXERCISE 1
• Making an HTTP get request
C# - ASYNC/AWAIT
C# - HELP WITH EXERCISE 1
• Try to use Regular Expressions to find all the emails within the source code.
• https://docs.microsoft.com/pl-pl/dotnet/standard/base-types/regular-expressions
ADDITIONAL C# MATERIALS
• https://docs.microsoft.com/pl-pl/dotnet/csharp/
• https://www.youtube.com/watch?v=gfkTfcpWqAY
• https://www.w3schools.com/cs/
C# - CODING CONVENTION
• https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-
conventions
Basics of C# Language

APBD – lecture 2 Design patterns


SOLID
C# language
• It was designed by Andres Hejlsberg in1999.
• It was originally named Cool which stood for C-like Object-Oriented
Language.
• In Nov 2005, C# 2.0 was released with the addition of generics.
• Later it got its name C# inspired by musical notation. This name was
also used by Microsoft earlier in the year 1988 for an incompleted
project.
C# features
• It was derived from C++ and Java.
• It is part of Microsoft Visual Studio
• Simple
• No pointers
• No operators like “::” or “->”
• Varying ranges of primitive types.
• Memory management and garbage collection is automatic and does not
need explicit code.
C# features
• Modern
• Built according to the current trend.
• Powerful, scalable, robust.
• Object-Oriented
• Supports OOP concepts such as inheritance, encapsulation, polymorphism, interfaces, etc.
• C# introduces structures enabling primitive types to become objects.
• Type-Safe
• It does not allow us to perform unsafe casts.
• Reference types are initialized to null and value types are initialized to zero by the compiler
automatically.
• Arrays are bound checked and are zero-based indexed.
C# vs Java - similarities
• Object-Oriented: Both languages are object-oriented and hence support
concepts like encapsulation, polymorphism, inheritance, and more.
• Dependence from C and C++: C and C++ are a superset to both Java and C#.
• Intermediate Language Code Generation: Java compiler and C# compilers both
generate an intermediate language code after compilation. C# compiler generates
Microsoft Intermediate Language (MSIL), whereas Java compiler generates Java
bytecode.
• Advance Features: Both languages include advanced features like garbage
collection.
• Syntax: Both languages are syntactically similar.
• Inheritance: Both languages support class inheritance.
C# vs Java - differences
• Runtime Environment: Java runs on JRE(Java Runtime Environment), whereas C#
runs on CLR(Common Language Runtime).
• Programming Paradigm: Java is a strictly object-oriented language whereas C# is
object-oriented as well as functional, strongly typed, and component-oriented.
• Operator Overloading: Java doesn't support operator overloading, whereas C#
supports operator overloading for multiple operators.
• Pointers: Java does not support pointers, whereas C# supports pointers only in
unsafe mode.
• Arrays: Java arrays are a specialization of Object, while C# arrays are a
specialization of System.
Aliases
+string is an alias in C# for System.String.
+Int is an alias for System.Int32
Namespaces
+The namespace keyword is used to declare a scope that
contains a set of related objects. You can use a namespace to
organize code elements and to create globally unique types.
Using class from diff namespace
Classes
+A type that is defined as a class is a reference type.
Classes
+Creating an object using the default constructor.
Class inheritance
Class inheritance
Class inheritance
Struct
+A structure type (or struct type) is a value type that can
encapsulate data and related functionality. You use the struct
keyword to define a structure type.
Record

A record in C# is a new type of reference type introduced in C# 9.0 that is designed to make it easier to create
and work with immutable data. Records provide a concise syntax for declaring types that are primarily used to
hold data.
Records have built-in support for value-based equality, meaning that two records are considered equal if
they have the same values for all of their properties. They also have built-in support for deconstruction,
which allows you to easily extract values from a record and assign them to variables.
Record

In this example, we've created two instances of the Person record, person1 and person2. We've set
the Age property for each person, and then we've compared them using the == operator. Since they
have different values for their FirstName and Age properties, the comparison will return false.
We've also used the deconstruction feature to extract the values of person1's FirstName and
LastName properties and assign them to the firstName and lastName variables. We've then printed
these values to the console.
Interface
+An interface contains definitions for a group of related
functionalities that a non-abstract class or a struct must
implement.
Interface
• An interface is typically like an abstract base class with only
abstract members.
• Any class or struct that implements the interface must
implement all its members.
• An interface can't be instantiated directly. Its members are
implemented by any class or struct that implements the
interface.
• A class or struct can implement multiple interfaces. A class can
inherit a base class and also implement one or more interfaces.
Built-in interfaces
+IEquatable<T>
+IComparable<T>
+IDisposable
Access modifers
+ public: The type or member can be accessed by any other code in the same assembly or
another assembly that references it.
+ private: The type or member can be accessed only by code in the same class or struct.
+ protected: The type or member can be accessed only by code in the same class, or in a
class that is derived from that class.
+ internal: The type or member can be accessed by any code in the same assembly, but
not from another assembly.
+ protected internal: The type or member can be accessed by any code in the assembly in
which it's declared, or from within a derived class in another assembly.
+ private protected: The type or member can be accessed only within its declaring
assembly, by code in the same class or in a type that is derived from that class.
Properties
+Properties are first class citizens in C#. The language defines
syntax that enables developers to write code that accurately
expresses their design intent.
+The syntax for properties is a natural extension to fields.
Properties
Properties
C# - properties
Full property
Attributes
+Attributes provide a powerful method of associating metadata,
or declarative information, with code (assemblies, types,
methods, properties, and so forth).
Generics
Generics
• Use generic types to maximize code reuse, type safety, and performance.
• The most common use of generics is to create collection classes.
• The .NET class library contains several generic collection classes in
the System.Collections.Generic namespace. These should be used whenever
possible instead of classes such as ArrayList in
the System.Collections namespace.
• You can create your own generic interfaces, classes, methods, events, and
delegates.
• Generic classes may be constrained to enable access to methods on particular
data types.
• Information on the types that are used in a generic data type may be obtained at
run-time by using reflection.
Collections
Anonymous types
+Anonymous types provide a convenient way to encapsulate a
set of read-only properties into a single object without having to
explicitly define a type first.
Partial types
+A partial method has its signature defined in one part of a partial
type, and its implementation defined in another part of the type.
The dynamic type
+The dynamic type indicates that use of the variable and
references to its members bypass compile-time type checking.
Parallel programming /Async
programming
Thread
ThreadPool
Parallel programming /Async
programming
Parallel programming /Async
programming
Parallel programming /Async
programming
Asynchronous members
+If you have any I/O-bound needs (such as requesting data from
a network, accessing a database, or reading and writing to a file
system), you'll want to utilize asynchronous programming.
+Utilizes some of the concept which existed before in C#
Async programming
Async programming
Async programming
C# - parallel and async programming
+https://docs.microsoft.com/en-us/dotnet/standard/parallel-
processing-and-concurrency
+http://blog.kokosa.net/
+https://tooslowexception.com/
C# - guidelines and conventions
+https://docs.microsoft.com/en-us/dotnet/csharp/programming-
guide/inside-a-program/coding-conventions
+https://github.com/ktaranov/naming-
convention/blob/master/C%23%20Coding%20Standards%20an
d%20Naming%20Conventions.md
C# - additional resources about the
language
+https://docs.microsoft.com/en-us/dotnet/csharp/whats-
new/csharp-version-history
+https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/
+https://www.tutorialspoint.com/csharp/index.htm
+http://people.cs.aau.dk/~normark/oop-
csharp/html/notes/collections_themes-list-sect.html
+http://blog.kokosa.net/author/konrad-kokosa
How to write „good” software?
+Different subproblems:
+Logging/Monitoring
+Maintainability
+User requirements
+Performance
+Readability
+Testability
Different guidelines
SOLID
+In object-oriented computer programming, SOLID is a mnemonic
acronym for five design principles intended to make software
designs more understandable, flexible, and maintainable.
+The principles are a subset of many principles promoted by
American software engineer and instructor Robert C. Martin,first
introduced in his 2000 paper Design Principles and Design Patterns.
+https://sites.google.com/site/unclebobconsultingllc/getting-a-solid-
start
+http://cleancoder.com/products
SOLID
+Single-responsibility principle
+Open–closed principle
+Liskov substitution principle
+Interface segregation principle
+Dependency inversion principle
Single responsibility (SRP)
+Principle that states that every class in a program should have
responsibility over a single part of that program's functionality,
which it should encapsulate. We can extend this to methods.
+„A class should have only one reason to change”
Single responsibility
(SRP)- example
Open–closed principle
+„software entities (classes, modules, functions, etc.) should be
open for extension, but closed for modification”
Open–closed principle -
example
Liskov substitution principle
+„if S is a subtype of T, then objects of type T may be replaced
with objects of type S (i.e., an object of type T may be
substituted with any object of a subtype S) without altering any
of the desirable properties of the program”
Liskov substitution
principle - example
Interface segregation principle (ISP)
+„no client should be forced to depend on methods it does not
use”
+„ISP splits interfaces that are very large into smaller and more
specific ones so that clients will only have to know about the
methods that are of interest to them.”
Interface segregation
principle (ISP) - example
Dependency inversion principle
+form of loosely coupling software modules
+strong cohesion – low coupling
+High-level modules should not depend on low-level modules.
Both should depend on abstractions (e.g., interfaces).
+Abstractions should not depend on details. Details (concrete
implementations) should depend on abstractions.
Dependency inversion
principle - example
Design patterns (GoF)
+Set of common solutions for frequently ocurring problems in
object-oriented software design
+Grouped into 4 categories:
+Creational design patterns
+Structural design patterns
+Behavior design patterns
Design patterns/Refactoring - materials
+https://sourcemaking.com/design_patterns
+https://refactoring.guru/refactoring
Code refactoring - example
APBD – lecture 3
Basics of REST API
ASP.NET Core Web API
Different kind of applications
Rise of internet and mobile applications
+Development of browsers push the development of JS
language (introduction of Node.js)
+Mobile systems becoming more powerful
+Mobile apps, web apps, SPA (React, Angular, Vue), PWA,
server-side rendered web apps
+We can generally provide similar UX in web or mobile app –
similar to desktop environment
Rise of internet and mobile applications
Communication between heterogeneous
systems
SOAP
REST
+REST is acronym for REpresentational State Transfer. It is
architectural style for distributed hypermedia systems and was
first presented by Roy Fielding in 2000 in his famous
dissertation.
+https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_sty
le.htm
REST
+Like any other architectural style, REST also does have it’s own
6 guiding constraints which must be satisfied if an interface
needs to be referred as RESTful. These principles are listed
below.
Client–server
+By separating the user interface concerns from the data storage
concerns, we improve the portability of the user interface across
multiple platforms and improve scalability by simplifying the
server components.
Stateless
+Each request from client to server must contain all of the
information necessary to understand the request, and cannot
take advantage of any stored context on the server. Session
state is therefore kept entirely on the client.
Cacheable
+Cache constraints require that the data within a response to a
request be implicitly or explicitly labeled as cacheable or non-
cacheable. If a response is cacheable, then a client cache is
given the right to reuse that response data for later, equivalent
requests.
Uniform interface
+By applying the software engineering principle of generality to
the component interface, the overall system architecture is
simplified, and the visibility of interactions is improved.
+In order to obtain a uniform interface, multiple architectural
constraints are needed to guide the behavior of components.
REST is defined by four interface constraints: identification of
resources; manipulation of resources through representations;
self-descriptive messages; and, hypermedia as the engine of
application state.
Layered system
+The layered system style allows an architecture to be
composed of hierarchical layers by constraining component
behavior such that each component cannot “see” beyond the
immediate layer with which they are interacting.
Code on demand (optional)
+REST allows client functionality to be extended by downloading
and executing code in the form of applets or scripts. This
simplifies clients by reducing the number of features required to
be pre-implemented.
Resource
+The key abstraction of information in REST is a resource. Any
information that can be named can be a resource: a document
or image, a temporal service, a collection of other resources, a
non-virtual object (e.g. a person), and so on.
+REST uses a resource identifier to identify the particular
resource involved in an interaction between components
Resource
+The state of the resource at any particular timestamp is known
as resource representation.
+A representation consists of data, metadata describing the
data and hypermedia links which can help the clients in
transition to the next desired state.
Resource
+The data format of a representation is known as a media type.
+https://www.iana.org/assignments/media-types/media-
types.xhtml
+The media type identifies a specification that defines how a
representation is to be processed.
+A truly RESTful API looks like hypertext. Every addressable
unit of information carries an address, either explicitly (e.g., link
and id attributes) or implicitly (e.g., derived from the media type
definition and representation structure).
According to Roy Fielding:
+„Hypertext (or hypermedia) means the simultaneous
presentation of information and controls such that the
information becomes the affordance through which the user (or
automaton) obtains choices and selects actions. Remember
that hypertext does not need to be HTML (or XML or JSON) on
a browser. Machines can follow links when they understand the
data format and relationship types.”
Resource
+Resource representations shall be self-descriptive: the
client does not need to know if a resource is employee or
device. It should act on the basis of media-type associated
with the resource. So in practice, you will end up creating lots
of custom media-types – normally one media-type
associated with one resource.
Resource methods
+Another important thing associated with REST is resource methods
to be used to perform the desired transition. A large number of
people wrongly relate resource methods to HTTP
GET/PUT/POST/DELETE methods.
+Roy Fielding has never mentioned any recommendation around
which method to be used in which condition. All he emphasizes is
that it should be uniform interface. If you decide HTTP POST will be
used for updating a resource – rather than most people recommend
HTTP PUT – it’s alright and application interface will be RESTful.
REST != HTTP
+REST and HTTP are not same !!
ASP.NET Core
+ASP.NET Core is a cross-platform, high-performance, open-
source framework for building modern, cloud-enabled, Internet-
connected apps. With ASP.NET Core, you can:
• Build web apps and services, Internet of Things (IoT) apps, and mobile
backends.
• Use your favorite development tools on Windows, macOS, and Linux.
• Deploy to the cloud or on-premises.
• Run on .NET Core.
ASP.NET Core web API
+ASP.NET Core Web API is a platform for building web
applications that use HTTP for communication. HTTP
(Hypertext Transfer Protocol) is a protocol that defines the rules
for transferring resources and the rules of communication
between the server and the client.
+ASP.NET Core Web API allows you to create APIs based on the
HTTP protocol.
ASP.NET Core web API
+This means that a Web API application can ultimately be
consumed by a mobile application, web application, desktop
application, SPA or IoT, or - more broadly - any application
whose communication takes place via the HTTP protocol.
+We will learn how to create REST-like API
Program.cs – builder pattern
https://refactoring.guru/design-patterns/builder
Startup.cs
Adding custom controller
ASP.NET Core request pipeline

https://refactoring.guru/design-patterns/chain-of-
responsibility
Attribute routing
Attribute routing
Attribute routing
Changing the return type
List of HTTP status codes
• 1xx informational response – the request was received, continuing process
• 2xx successful – the request was successfully received, understood, and
accepted
• 3xx redirection – further action needs to be taken in order to complete the
request
• 4xx client error – the request contains bad syntax or cannot be fulfilled
• 5xx server error – the server failed to fulfil an apparently valid request
• https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Content negotiation
Endpoint design guidelines
+Use nouns instead of verbs in endpoint paths
+Name collections with plural nouns
+Nesting resources for hierarchical objects
+Handle errors gracefully and return standard error codes
+Allow filtering, sorting, and pagination
Endpoint examples
+GET /companies/3/employees should get the list of all
employees from company 3
+GET /companies/3/employees/45 should get the details of
employee 45, which belongs to company 3
+DELETE /companies/3/employees/45 should delete employee
45, which belongs to company 3
+POST /companies should create a new company and return the
details of the new company created
HTTP methods
+ GET method requests data from the resource and should not produce any side effect.
E.g /companies/3/employees returns list of all employees from company 3.
+ POST method requests the server to create a resource in the database, mostly when a
web form is submitted. E.g /companies/3/employees creates a new Employee of company
3.
+ POST is non-idempotent which means multiple requests will have different effects.
+ PUT method requests the server to update resource or create the resource, if it doesn’t
exist. E.g. /companies/3/employees/john will request the server to update, or create if
doesn’t exist, the john resource in employees collection under company 3.
+ PUT is idempotent which means multiple requests will have the same effects.
+ DELETE method requests that the resources, or its instance, should be removed from the
database. E.g /companies/3/employees/john/ will request the server to delete john
resource from the employees collection under the company 3.
Sorting, filtering, searching, pagination
+ Sorting In case, the client wants to get the sorted list of companies, the GET /companies
endpoint should accept multiple sort params in the query. E.g GET
/companies?sort=rank_asc would sort the companies by its rank in ascending order.
+ Filtering For filtering the dataset, we can pass various options through query params. E.g
GET /companies?category=banking&location=india would filter the companies list data
with the company category of Banking and where the location is India.
+ Searching When searching the company name in companies list the API endpoint should
be GET /companies?search=Digital Mckinsey
+ Pagination When the dataset is too large, we divide the data set into smaller chunks,
which helps in improving the performance and is easier to handle the response. Eg. GET
/companies?page=23&pageSize=10 means get the list of companies on 23rd page.
Passing data through query string
+Usually used to modify, transform the resource
Passing data through query string
Passing data through query string –
explicit declaration
Passing data using URL segment
+path/to/page
+All following elements can be considered „segments”:
+path
+to
+page
+Because they are a part of the URL we usually use them to
identify a resource
+Ex. api/students/s1234
Passing data using URL segment
Passing data using URL segment
Passing data using HTTP body
HTTP headers – Content-Type
HTTP return status codes
Multiple endpoints matching the same
request
Multiple endpoints matching the same
request
Unclear HTTP return code
What is wrong with this code?
Bibliography
+https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
+https://docs.microsoft.com/pl-pl/aspnet/core/web-api/?view=aspnetcore-
5.0
+https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm
+https://restfulapi.net/
+https://www.merixstudio.com/blog/best-practices-rest-api-development/
+https://hackernoon.com/restful-api-designing-guidelines-the-best-
practices-60e1d954e7c9
SQL Connection / SQL Command

APBD – lecture 4
Dependency injection in REST
API Validation in REST API
Notes 1 - names
+Using correct and meaningful names
Notes 1 - names
Notes 2 – hardcoding paths
Notes 4 – fail-fast, invert ifs
Notes 3 - conventions
Notes 4 – fail-fast, invert ifs
Notes 5 – looong methods
Notes 5 – magic strings/magic numbers
Notes 5 – magic strings/magic numbers
Declarative validation
Declarative validation
Declarative validation
Custom validation attribute
IValidatableObject
Data annotations
Dependency injection
+Dependency Injection (DI) is a software design pattern that
allows us to develop loosely coupled code.
+.NET supports the dependency injection (DI) software design
pattern, which is a technique for achieving Inversion of
Control (IoC) between classes and their dependencies
Preparing the dependency
Injection of dependency through
constructor
Registering the dependency
Types of injection
+Constructor Injection: In the constructor injection, the injector
supplies the service (dependency) through the client class
constructor.
+Property Injection: In the property injection (aka the Setter
Injection), the injector supplies the dependency through a public
property of the client class.
+Method Injection: In this type of injection, the client class
implements an interface which declares the method(s) to supply the
dependency and the injector uses this interface to supply the
dependency to the client class.
Property injection
Method injection
Different methods for registering service
in dependency injection container
+AddSingleton() - A Singleton service is created only one time
per application and that single instance is used throughout the
application lifetime. As the name suggest, AddSingleton()
method creates a Singleton service. A Singleton service is
created when it is first requested. This same instance is then
used by all the subsequent requests.
Different methods for registering service
in dependency injection container
Different methods for registering service
in dependency injection container
+AddTransient() - This method creates a Transient service. A
new instance of a Transient service is created each time it is
requested.
+AddScoped() - This method creates a Scoped service. A new
instance of a Scoped service is created once per request within
the scope. For example, in a web application it creates 1
instance per each http request but uses the same instance in
the other calls within that same web request.
Different methods for registering service
in dependency injection container
Working with relational databases
+Inserting data into the database
+Updating data into the database
+Deleting data from a database
Working with relational databases
+Connection – To work with the data in a database, the first
obvious step is the connection. The connection to a database
normally consists of the below-mentioned parameters.
+Database name / Data source
+Credentials
+Optional parameters
+Selecting data from the database – Once the connection has
been established, the next important aspect is to fetch the data
from the database.
Different way to interact with database
+Low level interaction – using database providers and sending
the requests in SQL language
+Different issues:
+Different relational databases have different communication protocols
+Managing the connection
+Parsing the results into objects
+Managing the changes in database structure
Database providers
+There are database specific providers (they can usually
communicate with a specific type of database – MS SQL
Server, Oracle, MySQL, PostgreSQL, etc.)
+Sql/SqlCommand
+There are more generic providers which acts as a middle layer
which allows us to communicate with different relational
systems
+For ex. OdbcConnection/OdbcCommand
+Usually they may be slower than database specific providers
Working with relational databases
+SqlConnection/SqlCommand comes from namespace
System.Data.SqlClient;
+They represent extension of generic DbConnection class

+https://github.com/microsoft/referencesource/blob/master/
System.Data/System/Data/SqlClient/SqlConnection.cs
+https://github.com/microsoft/referencesource/blob/master/
System.Data/System/Data/SqlClient/SqlCommand.cs
SqlConnection
+The SqlConnection class handles MS SQL Server database
connections.
+It initiates a connection to your SQL database. This class is best
used in a using resource acquisition statement.
+We call Open to query the database with SqlCommand.
SqlConnection
SqlConnection
+When creating a new instance we should provide the
ConnectionString.
+ConnectionString usually defines:
+Data source
+Database name
+User credentials
+Optional parameters (for ex. timeout)
SqlConnection
SqlConnection
SqlConnection
+The responsibility of SqlConnection is opening, managing and
closing the connection.
+SqlConnection is not „interested” what we are sending to the
database. This is another responsibility
+Remember that SqlConnection represents an important
resource and we should always close it (dispose it).
SqlConnection
+When you are done using the connection object, you must
close it. Failure to do so could have serious consequences in
the performance and scalability of your application.
What is connection pooling?
+Connection pooling is a strategy that is used to minimize the
cost associated with opening and closing connections to
the database.
+It enables you to reuse connections rather than create new
connections to the database as and when they are requested.
+A connection pool contains a collection of idle, open, reusable
connections. The pooler manages the connection pool and maintains
a set of active connections for each given connection metadata,
connection configuration information.
What is connection pooling?
+Note that you can have multiple connection pools exist in the same
application domain.
+A connection pool is created per unique connection string that you
use to connect to the database and not per database.
+First time you connect to a database with a particular connection
string, a new connection pool is created
+When you connect to the same database with the same connection
string the next time, no new connection pool is created, rather, the
existing connection pool is reused.
What is connection pooling?
• We can control the connection pool with certain optional attributes in connection
string
• ConnectionTimeout -- this is used to specify the wait period (in seconds) when a new
database connection is requested for. The default value is 15.
• MinPoolSize -- this represents the minimum number of connections in the pool.
• MaxPoolSize -- this represents the maximum number of connections in the pool. The default
value is 100.
• Pooling -- this controls if connection pooling is turned on or off and can have a value of true
of false. When this is set to true, the requested connection is retrieved from the appropriate
connection pool.
• In order to ensure that connection pooling works efficiently, you should ensure
that you close the database connections when they are no longer needed.
SqlConnection – simple usage example
What is connection pooling?
SqlCommand
+SqlCommand class in C# is used to store and execute the
SQL statement against the SQL Server database.
SqlCommand – creation
SqlCommand – creation
+SqlCommand():
+This constructor is used to initializes a new instance of the
System.Data.SqlClient.SqlCommand class..
+SqlCommand(string cmdText):
+It is used to initializes a new instance of the
System.Data.SqlClient.SqlCommand class with the text of the
query. Here, the cmdText is the text of the query that we want to
execute.
SqlCommand – creation
+SqlCommand(string cmdText, SqlConnection connection):
+It is used to initializes a new instance of the
System.Data.SqlClient.SqlCommand class with the text of the
query and a System.Data.SqlClient.SqlConnection. Here, the
cmdText is the text of the query that we want to execute, and
the parameter connection is the connection to an instance of
SQL Server.
SqlCommand – different methods
+BeginExecuteNonQuery(): This method initiates the asynchronous
execution of the Transact-SQL statement or stored procedure that is
described by this SqlCommand.
+Cancel(): This method tries to cancel the execution of a
SqlCommand.
+CreateParameter(): This method creates a new instance of a
SqlParameter object.
+ExecuteReader(): This method Sends the
SqlCommand.CommandText to the SqlCommand.Connection and
builds a SqlDataReader.
SqlCommand – different methods
+ExecuteScalar(): This method Executes the query and returns
the first column of the first row in the result set returned by the
query. Additional columns or rows are ignored.
+ExecuteNonQuery(): This method executes a Transact-SQL
statement against the connection and returns the number of
rows affected.
SqlConnection, SqlCommand - example
SqlCommand – passing parameters
SqlInjection
+https://owasp.org/www-community/attacks/SQL_Injection
+https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_
Prevention_Cheat_Sheet.html
SqlCommand – using parameters
+SqlParameter -
+https://docs.microsoft.com/en-
us/dotnet/framework/data/adonet/configuring-parameters-and-
parameter-data-types
+https://www.dotnetperls.com/sqlparameter
SqlCommand – using parameters
Moving the connection string to
app.settings
Moving the connection string to
app.settings
Issues?
+What problems may arise due to multiple concurrent
connections?
Bibliography
+ https://en.wikipedia.org/wiki/Fail-fast
+ https://docs.microsoft.com/pl-pl/aspnet/core/mvc/models/validation?view=aspnetcore-5.0
+ https://docs.microsoft.com/pl-pl/aspnet/core/mvc/models/validation?view=aspnetcore-
5.0#remote-attribute
+ https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-5.0
+ https://www.plukasiewicz.net/Artykuly/DIP_IoC_DI
+ https://docs.microsoft.com/pl-pl/aspnet/core/fundamentals/dependency-
injection?view=aspnetcore-5.0
+ https://www.tutorialsteacher.com/ioc/dependency-injection
+ https://www.coreprogramm.com/2020/02/difference-between-addsingleton-addScoped-
addTransient.html
Bibliography
+ http://www.differencebetween.net/technology/software-technology/difference-between-
odbc-and-sql-2/#ixzz6D5EuzKbL
+ https://sekurak.pl/czym-jest-sql-injection/
+ https://owasp.org/www-community/attacks/SQL_Injection
+ https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.
html
+ https://www.infoworld.com/article/3104045/how-does-adonet-connection-pooling-
work.html
+ https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/configuring-parameters-
and-parameter-data-types
+ https://en.wikipedia.org/wiki/Magic_string
+ https://en.wikipedia.org/wiki/Magic_number_(programming)
Async code

APBD – lecture 5
Transactions
Stored procedures
Avoid blocking calls
+Generally our REST API should be designed to proces many
requests simultaneously.
+Asynchronous APIs allow a small pool of threads to handle
thousands of concurrent requests by not waiting on blocking
calls.
+Rather than waiting on a long-running synchronous task to
complete, the thread can work on another request.
Avoid blocking calls
+A common performance problem in ASP.NET Core apps is
blocking calls that could be asynchronous. Many synchronous
blocking calls lead to Thread Pool starvation and degraded
response times.
Avoid blocking calls
+Do not:
+Block asynchronous execution by calling Task.Wait or Task.Result.
+Acquire locks in common code paths. ASP.NET Core apps are most
performant when architected to run code in parallel.
+Do:
+Make hot code paths asynchronous.
+Call data access, I/O, and long-running operations APIs
asynchronously if an asynchronous API is available. Do not use
Task.Run to make a synchronous API asynchronous.
Example of turning synchronous endpoint
into an asynchronous one
Performance comparison of both
endpoints
Transaction
+A transaction is the smallest work unit that is executed in the
database and transactions also meet the properties of the ACID
+ACID (atomicity, consistency, isolation and durability). SQL
Server can operate 3 different transactions modes, and these
are:
+Auto-commit transactions
+Implicit transactions
+Explicit transactions
Auto-commit transactions
+The auto-commit transaction mode is the default transaction mode of
the SQL Server. In this mode, each SQL statement is evaluated as a
transaction by the storage engine.
+In this context, if any SQL statement completes its execution
successfully it is committed, and the data modification will become
permanent in the database.
+On the other hand, if any statement faces any error, it will be rolled
back. In this transaction mode, we don’t try to manage transactions
and all operations are managed by the SQL Server.
Implicit transactions
+In the implicit transaction mode, SQL Server takes the
responsibility for beginning the transactions implicitly but it waits
for the commit or rollback commands from the user.
+In the implicit transaction mode, the database objects involved
in the transaction will remain locked until the commit or rollback
commands are executed.
+In order to use the implicit transaction mode, we need to set
implicit transaction mode to ON. We can use the following
syntax to enable or disable the implicit transaction mode.
Implicit transactions

The implicit transaction is a connection-level setting


and we can set this setting when connecting to the
SQL Server.
Explicit transaction
+In the explicit transaction mode, we have to define the starting
and ending points of the transactions.
+It means that all transactions must start with the BEGIN
TRANSACTION statement and end with either COMMIT
TRANSACTION or ROLLBACK TRANSACTION statements.
Explicit transaction
Transactions
+Usually, when fulfilling any business process, we have multiple
database operations we have to execute; for example, A single
banking transaction can consist of numerous
insert/update/delete statements.
+We want to perform either all operations or none of them. If we
execute only some of them, and then the exception will stop the
execution – this can put our database into an inconsistent state.
SqlTransaction
Using stored procedures
Pros of stored procedure
+Performance benefits
+Pre-parsed SQL
+Pre-generated query execution plan
+Reduced network latency
+Potential cache benefits
+Unless using the dynamic SQL – we are protected against SQL
Injection
+Allows us to control the access to db objects on very low level
Cons of stored procedures
+Our code will become highly dependent on the exact database
type we are using.
+The business logic of our application may get scattered
between different places – our code, and the database
+Stored procedures are harder to version control
+Our developers need to know the specific dialect of SQL
+Stored procedures may become a problem when we want to
use load balancing (especially master-master replication).
Pros of raw SQL approach
+All the business logic is located within our code.
+We can more easily version control the application.
+By using specific additional libraries we can make our code
more independent from the database we are using (we will see
that in future classes).
Cons of raw SQL
+Requires a lot of boilerplate code (unless we are using
something more abstract than SqlConnection/SqlCommand).
+Impedance mismatch problem
+We have to remember about SQL injection
Bibliography
+https://docs.microsoft.com/pl-pl/dotnet/csharp/programming-
guide/concepts/async/
+https://docs.microsoft.com/pl-
pl/aspnet/core/performance/performance-best-
practices?view=aspnetcore-5.0
+https://www.plukasiewicz.net/Artykuly/SQL_Transactions
+https://www.sqlshack.com/modes-of-transactions-in-sql-server/
Delegates
LINQ
APBD – lecture 6 Lambda
Extension methods
Anonymous types
Interaction with database
C# - multiparadigm languages
+C# is an objective language
+However with the next versions of the C# language we can see
a shift towards functional programming.
+Nowadays we can see that a lot of languages „traditionally”
object oriented are gaining more functional features.
Objective vs functional programming
+Objective programming - usually the first-class citizen is a
class. This is a way most of us are used to think about the
programs – as a set of classes communicating with each other.

+Functional programming – is a paradigm which concentrates


on computing the result rather than on performing actions. This
way of approaching a problem is often more suitable than
objective way of thinking.
Functional programming
+Functional programming have a lot of benefits and characteristics
which we won’t discuss here like:
+ First-Class functions
+ Lazy evaluation
+ Higher-order functions
+ Immutability
+ Modularity
+ No side-effects
+ Lazy evaluation
+ Recursive function calls
C# multiparadigm language
+Nowadays in C# and a lot of other languages including Java
we can see a lot of features close to functional programming.
+We will use some of those features in C# language when
working with more complex libraries for ex. for database
communication.
Delegates in C#
+On of the elements of C# language that appeared very early are
delegates. This is type-safe mechanism which enables us to
pass, return and use functions as parameters.
+We can think about it as a type-safe function pointer
Delegates in C#
Generic delegates – Func<T> and
Acion<T>
Lambda expressions
+Lambda expression allows us create an anonymous function.
+Use the lambda declaration operator => to separate the
lambda's parameter list from its body.
Lambda expressions - example
Extension methods
+Extension methods enable you to "add" methods to existing
types without creating a new derived type, recompiling, or
otherwise modifying the original type.
+Extension methods are static methods, but they're called as if
they were instance methods on the extended type.
+The most common extension methods are the LINQ standard
query operators that add query functionality to the
existing System.Collections.IEnumerable and System.Collections.
Generic.IEnumerable<T> types.
Extension methods
+Extension methods are additional custom methods which were
originally not included with the class.
+Extension methods can be added to custom, .NET Framework
or third party classes, structs or interfaces.
+The first parameter of the extension method must be of the type
for which the extension method is applicable, preceded by this
keyword.
+Extension methods can be used anywhere in the application by
including the namespace of the extension method.
Extension methods - example
Anonymous types
+In C#, an anonymous type is a type (class) without any name
that can contain public read-only properties only. It cannot
contain other members, such as fields, methods, events, etc.
+You create an anonymous type using the new operator with an
object initializer syntax. The implicitly typed variable- var is used
to hold the reference of anonymous types.
Anonymous types
+The following example demonstrates creating an anonymous
type variable student that contains three properties named Id,
FirstName, and LastName.

+The properties of anonymous types are read-only and cannot


be initialized with a null, anonymous function, or a pointer type.
The properties can be accessed using dot (.) notation, same as
object properties. However, you cannot change the values of
properties as they are read-only.
Anonymous types
Collections hierarchy
LINQ – Language Integrated Query
+Language-Integrated Query (LINQ) is the name for a set of
technologies based on the integration of query capabilities
directly into the C# language.
+We can use it on any object implementing IEnumerable<T>
+Introduced in .Net 3.5
+LINQ (Language Integrated Query) is uniform query syntax in
C# and VB.NET to retrieve data from different sources and
formats.
LINQ – Language Integrated Query
+LINQ can often be used with different data sources – for ex.
relational databases, XML documents etc. (we need additional
libraries for that).
+We will use LINQ with database next week.
LINQ – syntax
+Methods related to LINQ reside in System.Linq namespace
+LINQ provides two ways of writing queries:
+Query Syntax or Query Expression Syntax
+Method Syntax or Method Extension Syntax or Fluent

+We can mix both of them.


+The method syntax is more expressive – there are things which
we cannot do in query syntax
LINQ – query syntax
LINQ – query syntax

https://www.tutorialsteacher.com/linq/linq-query-syntax
LINQ – method syntax
+Method syntax (also known as fluent syntax) uses extension
methods included in the Enumerable or Queryable static class,
similar to how you would call the extension method of any class.
+The compiler converts query syntax into method syntax at
compile time.
+Using the method syntax we will rely on Lambda expressions,
extension methods and anonymous types
LINQ – method syntax
LINQ – method syntax

https://www.tutorialsteacher.com/linq/linq-method-syntax
Bibliography
+ https://hamidmosalla.com/2019/04/25/functional-programming-in-c-sharp-a-brief-guide/
+ https://www.infoq.com/presentations/c-sharp-functional-features/
+ https://www.youtube.com/watch?v=v7WLC5As6g4
+ https://docs.microsoft.com/pl-pl/dotnet/csharp/programming-guide/concepts/linq/
+ http://people.cs.aau.dk/~normark/oop-csharp/html/notes/collections_themes-list-sect.html
+ https://docs.microsoft.com/pl-pl/dotnet/csharp/programming-guide/classes-and-
structs/extension-methods
+ https://www.tutorialsteacher.com/csharp/csharp-anonymous-type
+ https://www.tutorialsteacher.com/linq/linq-query-syntax
+ https://www.tutorialsteacher.com/linq/linq-method-syntax
LINQ – example of methods in both
syntaxes
+https://docs.microsoft.com/en-us/samples/dotnet/try-
samples/101-linq-samples/
+https://linqsamples.com/
APBD – lecture 7
ORM
EntityFramework Core
Object/Relational Mapping (O/RM)
framework
+Object–relational mapping (ORM, O/RM, and O/R mapping
tool) in computer science is a programming technique for
converting data between incompatible type systems using
object-oriented programming languages.
+This creates, in effect, a "virtual object database" that can be
used from within the programming language. There are both
free and commercial packages available that perform object–
relational mapping, although some programmers opt to
construct their own ORM tools.
Entity Framework Core
+Entity Framework Core is the new version of Entity Framework
after EF 6.x. It is open-source, lightweight, extensible and a
cross-platform version of Entity Framework data access
technology.
+Entity Framework is an Object/Relational Mapping (O/RM)
framework. It is an enhancement to ADO.NET that gives
developers an automated mechanism for accessing & storing
the data in the database.
Entity Framework Core
EF Core Development Approaches
+EF Core supports two development approaches
+1) Code-First
+2) Database-First.
+EF Core mainly targets the code-first approach and provides
little support for the database-first approach because the visual
designer or wizard for DB model is not supported as of EF Core
2.0.
Code first
+In the code-first approach, EF Core API creates the database
and tables using migration based on the conventions and
configuration provided in your domain classes. This approach is
useful in Domain Driven Design (DDD).
Database first
+In the database-first approach, EF Core API creates the domain
and context classes based on your existing database using EF
Core commands. This has limited support in EF Core as it does
not support visual designer or wizard.
EF Core Database Providers
+Entity Framework Core uses a provider model to access many
different databases. EF Core includes providers as NuGet
packages which you need to install.
EF Core - installation
+EF Core is not available by default
+We will need to install required libraries using Nuget package
manager
+Microsoft.EntityFrameworkCore – main package for EF Core
+Microsoft.EntityFrameworkCore.SqlServer - db provider for
MS SQL Server database
EF Core - tools
+Microsoft.EntityFrameworkCore.Tools – Along with the DB
provider package, you also need to install EF tools to
execute EF Core commands.
+These make it easier to perform several EF Core-related
tasks in your project at design time, such as migrations,
scaffolding, etc.
+This will allow you to execute EF Core commands for
scaffolding, migration etc. directly from Package Manager
Console (PMC) within Visual Studio.
Database first approach
+Database first approach is often used when the database we
want to use already exists and we simply want to start
communicating with it (mainly SELECT, INSERT, UPDATE,
DELETE).
+We usually don’t want to affect the structure of the database
+In this scenario we assume that db developer is responsible for
any changes to the database structure. We simply want to „use”
the database.
Database first approach
+To use this approach:
+We could create all the necessary classes manually
+We can generate all the necessary classes automatically using
scaffolding. The generation read the metadata about our tables and
generete classes based on that.
Scaffolding necessary classes
+1. First its good to prepare yourself some kind of folder which
we will use as the container for all the generated classes.
Otherwise classes will be generated into the root of the project.
Scaffolding necessary classes
+2. (for Visual Studio) open Tools -> NuGet Package Manager ->
Package Manager Console
Scaffolding necessary classes
+3. In the Package Manager Console run the following
command.
+ Scaffold-DbContext "Data Source=db-mssql16.pjwstk.edu.pl;Initial
Catalog=pgago;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer
-OutputDir Models -Tables "Client,Trip,Client_Trip,Country, Country_Trip„

+ First parameter – represent your connection string


+ Second parameter – library used as the database provider
+ OutputDir – allows us to specify when we want to generate the required classes
+ Tables – allows us to choose which tables we are interested in (by default all
the tables will be taken into account)
Scaffolding necessary classes
+2.1 (in other IDEs) Open the terminal/console and run the
following command:

dotnet ef dbcontext scaffold "Data Source=db-mssql16.pjwstk.edu.pl;Initial


Catalog=pgago;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer --output-
dir Models --table Client --table Trip
Result of scaffolding the classes
+As a result of scaffolding the necessary classes we should get:
+DbContext class – usually named after the name of the database
+Model classes – one class per table from database
Model classes
+Every class is mapped to the table in database
Model classes
+partial – models are generated as partial classes. This mechanism allows
us later to extend easily the functionality of the class (if needed).
+public virtual ICollection<ClientTrip> ClientTrips
+ This collection represents a relations in the database. Each client can be assigned to
many ClientTrips. In „objective world” it means that client can have multiple
ClientTrips objects assigned to him.
+ virtual – this keyword means that this property can be overriden. This may be usefull
when using lazy loading or other mechanisms.
+ ICollection<ClientTrip> - ICollection<T> is the most generic interface which allows
us to add/remove elements from collection. (IEnumerable<T> does not specify those
methods). In other words we are using the most generic interface we can.
DbContext
+The DbContext class is an integral part of Entity Framework. An
instance of DbContext represents a session with the database
which can be used to query and save instances of your entities
to a database.
DbContext
+DbContext in EF Core allows us to perform following tasks:
1.Manage database connection
2.Configure model & relationship
3.Querying database
4.Saving data to the database
5.Configure change tracking
6.Caching
7.Transaction management
DbContext
+To use DbContext in our application, we need to create the
class that derives from DbContext, also known as context class.
This context class typically includes DbSet<TEntity> properties
for each entity in the model. Consider the following example of
context class in EF Core.
DbContext
DbContext
+Change Tracking
+The Change Tracker detects changes made to entities and sets the
EntityState of an object accordingly. The state of the entity determines
the type of operation that the database will be asked to perform upon it,
and therefore the SQL that will be generated.
+Model Building
+The DbContext builds a conceptual model based on convention and
configuration, and maps that to the database. The model and its
mappings are built at application startup and are persisted in memory
for the lifetime of the application.
DbContext
+Data Mapping
+ The DbContext includes a data mapper layer responsible for mapping the results of
SQL queries to entity instances and other types defined by the client application.
+Object Caching
+ The DbContext provides a first-level cache for objects that it is asked to retrieve from
the data store. Subsequent requests for the same object will return the cached object
instead of executing another database request.
+Transaction Management
+ When the DbContext SaveChanges method is called, a transaction is created and all
pending changes are wrapped in it as a single unit of work. If an error occurs when
the changes are applied to the database, they are rolled back and the database is left
in an unmodified condition.
DbSet<T>
+The DbSet<TEntity> class represents a collection for a given
entity within the model and is the gateway to database
operations against an entity.
+DbSet<TEntity> classes are added as properties to the
DbContext and are mapped by default to database tables that
take the name of the DbSet<TEntity> property.
DbSet<T>
+DbSet objects represent collections of entities in memory. Any changes
you make to the contents of a DbSet will only be committed to the
database if the SaveChanges method of the DbContext is called.
+The DbSet class exposes a number of methods that enable you to perform
basic CRUD (Create, Read, Update, Delete) operations against entities.
+When the DbContext SaveChanges method is called, a transaction is
created and all pending changes are wrapped in it as a single unit of work.
If an error occurs when the changes are applied to the database, they are
rolled back and the database is left in an unmodified condition.
Simple select query
+Following code:
+Opens connection to db
+Generate SELECT statement
+Parses the result
+Closes the connection to db
Select query
+DbSet<T> implements Ienumerable<T> which means we can
use our Linq knowledge to create more complex SQL query.
Select query
+Remember that not every Linq can be translated into SQL. You
may get an exception similar to „We do not know how to
translate your LINQ into SQL code”.
Select query – when the query is executed
+We have to remember that our code is executed in a „lazy way”.
+The return value from a Linq query on a DbSet<T> is of
following type:
IQueryable<T>
+The IQueryable interface inherits the IEnumerable interface so
that if it represents a query, the results of that query can be
enumerated.
+Enumeration causes the expression tree associated with
an IQueryable object to be executed.
+The definition of "executing an expression tree" is specific to a
query provider.
Expression trees
When the query is executed?
When the query is executed?
Eager loading
+We can force the query to be executed immediately by using
following methods.
+.ToList()
+.ToListAsync()
+.Single()
+.SingleAsync()
+.First()
+.FirstAsync()
Eager loading
Select - join
Cycle problem during serialization
Cycle problem during serialization

System.Text.Json.JsonSerializer doesn’t have a way to simply ignore circular references, whereas Newtonsoft
does.
Add Nuget package Microsoft.AspNetCore.Mvc.NewtonsoftJson
Select – projection query
Select – projection query
+We can also load multiple related entities by using the
projection query instead of Include() or ThenInclude() methods.
The following example demonstrates the projection query to
load the Student, Grade, and Teacher entities.
Multiple Include
+Use the Include() method multiple times to load multiple
navigation properties of the same entity. For example, the
following code loads Grade and StudentCourses related entities
of Student.
ThenInclude
+EF Core introduced the new ThenInclude() extension method to
load multiple levels of related entities. Consider the following
example:

In the above example, .Include(s => s.Grade) will load the Grade reference
navigation property of the Student entity. .ThenInclude(g => g.Teachers) will load
the Teacher collection property of the Grade entity. The ThenInclude method must
be called after the Include method. The above will execute the following SQL
queries in the database.
Select – using subqueries
Select – using subqueries
+ SELECT [c0].[LastName], (
+ SELECT COUNT(*)
+ FROM [trip].[Client_Trip] AS [c]
+ WHERE [c0].[IdClient] = [c].[IdClient]) AS [Trips]
+ FROM [trip].[Client] AS [c0]
Insert
SaveChanges() wraps all the queries into
a single transaction.

In this example we will send a single


Insert statement
Insert – complex example
Update
+When updating entities – we are often using change tracking.
+DbContext tracks all the objects that we fetched through
DbSet<T> objects
UPDATE [trip].[Client]
SET [LastName] = @p0
WHERE [IdClient] =
@p1;
SELECT @@ROWCOUNT;
Update Data in Disconnected Scenario in
Entity Framework Core
+EF Core API builds and execute UPDATE statement in the database
for the entities whose EntityState is Modified. In the connected
scenario, the DbContext keeps track of all entities so it knows which
are modified and hence automatically sets EntityState to Modified.
+In the disconnected scenario such as in a web application, the
DbContext is not aware of the entities because entities were
modified out of the scope of the current DbContext instance. So, first
we need to attach the disconnected entities to a DbContext
instance with Modified EntityState.
ChangeTracker in Entity Framework Core
+The DbContext in Entity Framework Core includes the
ChangeTracker class in
Microsoft.EntityFrameworkCore.ChangeTracking namespace
which is responsible of tracking the state of each entity retrieved
using the same DbContext instance. It is not intended to use it
directly in your application code because it may change in
future versions. However, you can use some methods for
tracking purpose.
ChangeTracker in Entity Framework Core
+The ChangeTracker class in Entity Framework Core starts
tracking of all the entities as soon as it is retrieved using
DbContext, until they go out of its scope. EF keeps track of all
the changes applied to all the entities and their properties, so
that it can build and execute appropriate DML statements to the
underlying data source.
Update – setting the state manually
Delete
Delete - relationship configuration
Delete without additional fetch
Injecting DbContext
Using DTOs, custom models
+Often we need to pass into endpoint set of parameters which do
not fit any database-related model. In other situations we would
like to return a custom model which includes a set of fields
combined from multiple tables.
DTO – Data Transfer Object
+A Data Transfer Object is an object that is used to encapsulate
data and send it from one subsystem of an application to
another.
+DTOs are most commonly used by the Services layer in an N-
Tier application to transfer data between itself and the UI layer.
Bibliography
+https://docs.microsoft.com/pl-pl/ef/core/managing-
schemas/scaffolding?tabs=dotnet-core-cli
+https://docs.microsoft.com/pl-pl/ef/core/cli/dotnet
+https://www.learnentityframeworkcore.com/
+https://www.entityframeworktutorial.net/efcore
+https://livebook.manning.com/book/entity-framework-core-in-action/a-a-
brief-introduction-to-linq/v-11/13
+https://docs.microsoft.com/pl-pl/ef/core/querying/related-data/eager
+https://www.entityframeworktutorial.net/efcore/querying-in-ef-core.aspx
APBD – lecture 8
Entity Framework Core
Code first
Lazy loading in Entity Framework Core
+Microsoft.EntityFrameworkCore.Proxies
+Lazy loading allow us to automatically fetch missing data if
needed.
Lazy loading with proxies
+The simplest way to use lazy-loading is by installing the
Microsoft.EntityFrameworkCore.Proxies package and enabling
it with a call to UseLazyLoadingProxies. For example:

Or when using AddDbContext:


Lazy loading with proxies
+EF Core will then enable lazy loading for any navigation
property that can be overridden--that is, it must be virtual and
on a class that can be inherited from.
+For example, in the following entities, the Post.Blog and
Blog.Posts navigation properties will be lazy-loaded.
Lazy loading with proxies
N+1 problem
+The N + 1 problem is an anti-pattern that is a problem with
ORMs in general, which most often occurs with lazy loading.
+The N + 1 problem occurs when an application gets data from
the database, and then loops through the result of that data.
+That means we call to the database again and again and again.
In total, the application will call the database once for every row
returned by the first query (N) plus the original query ( + 1).
N+1 problem
N+1 problem
+Generated SQL code
N+1 problem
+The problem is that in our original query we’re not getting data
from the LinkedPosts entity, just data from Posts and PostTags.
Entity Framework knows that it doesn’t have the data for the
LinkPosts entity, so it gets the data from the database for each
row in the query results.
+Obviously, making multiple calls to the database instead of one
call for the same data is slower.
Code first approach
+Code First workflow begins with classes that describe the
conceptual model and then Entity Framework generate a
database from that model automatically.
+In this approach the whole database is manager through code –
this includes modeling the database structure and querying the
database.
Code first approach - advantages
+We can speed up the development
+Our C# code represent our whole database – by versioning our
code we version also the database
+We have a complete history of changes in the database in the
form of migrations.
+In theory – we can much more easily change the database by
switching the provider and running the migrations again.
Code first approach - disadvantages
+Database is generated from C# code – this means that often
people do not take into consideration normal forms
+The growing database structure is at some point becoming
denormalized which may be a problem
+A lot of databases have „special features” – specific to
database. Code first approach may not allow us to use all the
database-specific features.
Code first – step-by-step
+1. Install the necessary libraries:
+Microsoft.EntityFrameworkCore
+Microsoft.EntityFrameworkCore.SqlServer
+Microsoft.EntityFrameworkCore.Tools
Code first – step 2
+2. Create model classes – they should represent the structure
of the tables created later in database.
Code first – step 3
+Add necessary metadata related to database constraints:
+We can do it declaratively:
+ Simpler
+ Violates SRP
+ Suitable for simpler projects
+We can do it within DbContext
+ Allows us to completely separate the Model class from database constraints
definition.
Code first – step 3
Code first – step 4
+We need to create a class which will represent our database.
+This class should inherit from DbContext class.
+It should also contain DbSet<T> properties representing tables
in database.
+We will also create two constructors – usefull for us while
injecting the context in Startup class
+We will override onConfiguring method to setup the connection
string.
Code first – step 4
Code first – step 5
+Now we can finally create the first migration. We can do it by
using the Package Manager Console or dotnet cli.
+Package Manager Console
+ Add-Migration InitialMigration
+dotnet cli
Code first – step 5
+After running the command we will see a Migrations folder.
Inside we should find two classes.
Code first – step 5
+MainDbContextModelSnapshot – this class represent the
current version of the database. It describes the current schema
of database (all the tables, constraints etc.).
+Its often used when we create a new migration to determine
what was changed since the last migration.
+This file is regenerated with every migration. We should not
modify it ourselves.
Code first – step 5
Code first – step 5
+20210428105949_InitialMigration
+This class represent migration – which is „some kind of change in
database structure”.
+We can think of migration like a „commit” for database.
+Migration is simply a class that inherits from DbMigration and it
contains two methods:
+ Up() – for applying the migration to database (ex. Creating a table)
+ Down() – for doing the opposite. Reverting the migration (ex. Dropping the table)
+The name of migration represent a timestamp concatenated with name
we provided in the console.
+This way in case of any errors we can easily revert migration in case of
any problems.
Code first – step 5
+Just like commits – migration should be small/medium. We
shouldn’t try to create the whole database in a single migration.
+Usually changes to database are incremental.
Code first – step 5
Code first – step 6
+Remember that migration does not mean that anything has
changed in database yet.
+To execute the migration on database we should run:
+Update-Database
Code first – step 6
+After running the command we can take a look in database. We
should find the following tables.
Code first – step 6
+We can see that students table was created. This should not
suprise us.
+There is however one additional table: __EFMigrationsHistory
+This table is used to store the information about migrations already run
against the database.
+This way we don’t run the same migration twice by mistake.
Changes in our models
+After that we can repeat the whole proces. First we can make
some changes and then run the command Add-Migration
again.
+EF should automatically detect (by comparison of our models
with ModelSnapshot) what changed and generate correct
migration.
Changes in our models
Changes in our models
+Then we are running again the Add-Migration command.

+Then we are running again the Update-Database command.


One-to-many relationship
+Lets assume we would like to create a Status class. Status is
just a dictionary table which comprises from IdStatus and Name
+Every student is assigned to a single Status. Every status can
be assigned to multiple students.
One-to-many relationship
One-to-many relationship
+Remember to add Status class as a DbSet<Status> to our
MainDbContext.
One-to-many relationship
+Next we add the navigation properties to both Student and
Status classes.
One-to-many relationship
One-to-many relationship
+This is enough to generate the migration. EF is smart enough to
determine that following properties. However, we do not have a
direct access to foreign key which will be generated in Student
class.
+Such access may be usefull – for writing a more optimized SQL
queries.
One-to-many relationship
+We can explicitly create a foreign key and define that this
property should be used as the foreign key.
Defining the explicit foreign key
One-to-many relationship
+Now we can create a new migration.
One-to-many relationship
Additional information
+Take a look at the migration.
+By default EF Core will create an index on the foreign key –
which is generally a good practice.
Many-To-Many Relationship
Let’s assume that there is many-to-many relationship between student and studia classes.
To implement such relationship let’s add collections to each of the classes.
Many-To-Many Relationship
EF generated an association table which is „transparent” from the point of
view of our code.
Inheritance
+Let’s assume that we need a Department class. We may have
different type of departments. Therefore we decided to use
inheritance.
Inheritance
+Then we add the models to the DbContext class and generate
new migration.
Inheritance
+On the database level we will only see a single table with
additional column called dyscriminator.
Different inheritance models
+https://docs.microsoft.com/pl-pl/ef/core/modeling/inheritance
Other useful commands
+Script-Migration
+Allows us to generate the SQL script based on our migration (without
running it against database)
+Remove-Migration – allows us to remove migration (only if it
hasn’t been applied to the database yet)
+https://docs.microsoft.com/pl-pl/ef/core/managing-
schemas/migrations/managing?tabs=vs
Reverting database to a specific migration
+Update-Database –Migration:”nameOfMigration”
+The command above allows us to revert the state of the
database to a specific migration.
+REMEMBER: This is a destructive command and it may remove
tables with data. Be cautious!
Other db-related attribute annotations
Other db-related attribute annotations
The DatabaseGenerated Attribute
+The DatabaseGenerated attribute specifies how values are
generated for a property by the database. The attribute takes a
DatabaseGeneratedOption enumeration value, which can be
one of three values:
+Computed
+Identity
+None
Defining constraints in DbContext
The DatabaseGenerated Attribute
Defining constraints using FluentAPI
Defining constraints in DbContext
+https://docs.microsoft.com/pl-
pl/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-
simple-key%2Csimple-key
Splitting large configuration into separate
files
+We can separate configuration for each entity into separate file
which implements the IEntityTypeConfiguration<T>
Splitting large configuration into separate
files
Splitting large configuration into separate
files
Seeding the database
+Seed data is data that you populate the database with at the
time it is created. You use seeding to provide initial values for
lookup lists, for demo purposes, proof of concepts etc.
Seeding the database
Bibliography
+https://docs.microsoft.com/pl-pl/ef/core/managing-
schemas/migrations/?tabs=dotnet-core-cli
+https://docs.microsoft.com/pl-pl/ef/core/managing-
schemas/migrations/managing?tabs=dotnet-core-cli
+https://www.entityframeworktutorial.net/efcore/entity-framework-
core-migration.aspx
+https://docs.microsoft.com/pl-pl/ef/core/modeling/data-seeding
+https://www.learnentityframeworkcore.com/migrations/seeding
Custom middlewares

APBD – lecture 9 Error logging


Authentication and authorisation
Middlewares
+As you rememeber previous lectures ASP.NET Core API is
using middlewares to handle the incoming HTTP requests.
Middleware
+Each middleware is responsible for transforming the incoming
request and modify it in some way. Then the request is passed
to the next middleware.
Middleware configuration
+Middleware chain is configured in the Startup.cs class
+Remember that position of middleware in the chain is important
Middleware configuration
Adding custom middleware
Custom middleware – error handling
Registering created middleware
Using custom extension method for
registering middleware
Authentication and Authorization
+Authentication is the process of determining a user's identity.
+Authorization is the process of determining whether a user has
access to a resource.
Common Authentication Methods
+Token authentication: This solution is a property-based
authentication, like a card with an RFID chip in it. The advantage to
this type of authentication is that a hacker would need the physical
item to gain access.
+Passwords: The most common and well-known form of
authentication is the password. You set a password that only you
know and link it to your username and account. When you enter that
password, if it matches, the system knows it’s you. While passwords
are common and easy to set up, they’re also inefficient as a sole
method of authentication because they’re easy to lose, forget, guess
or steal.
Common Authentication Methods
+Physiological biometrics: Some examples include
fingerprints, eye patterns (iris or retina) and even vein pattern.
Biometrics are very popular because a biometric authenticator
cannot be forgotten like a password or lost like an access card.
No one can take and use a person’s physiological biometrics
without subjecting the real user to physical trauma.
Common Authentication Methods
+Behavior biometrics: Some examples include keystroke
dynamics, voiceprints and gait analysis.
+Certain behavioral patterns are unique to individuals, such as
how quickly and how hard they hit certain keys when typing,
how fast or slowly they speak and how big a stride they take
when they walk. These kinds of biometrics cannot be stolen
under any circumstances and are nearly impossible to
duplicate, making them highly effective authenticators.
Common Authentication Methods
+Multi-factor authentication: Multi-factor authentication,
meaning two different authentication requirements, such as a
password and an eye-scan. While one authentication factor
may be hackable, it’s exponentially harder to hack two or more.
Hand-in-hand with MFA are time-sensitive, one-time passwords.
This method allows the user to obtain exclusive access to a
password that will only work for a short amount of time, making
it useless to steal after that period has expired.
Authentication/Authorization
+We will discuss a few common ways to implement
authetication/authorization in REST API:
+API Key
+HTTP Basic Auth
+Token authentication (JWT)
+We will also talk about storing the passwords securely in
database
API Key
+The API key is a unique identifier that authenticates requests
associated with your project for usage and billing purposes.
+Often used with external APIs
+Using API keys is a way to authenticate an application accessing the
API, without referencing an actual user. The app adds the key to
each API request, and the API can use the key to identify the
application and authorize the request. The key can then be used to
perform things like rate limiting, statistics, and similar actions.
API Key
API Key
+Then we can check at the controller or middleware level the
value in the header. The traffic should use HTTPS.
API Key - benefits
+It’s relatively easy for clients to use API keys. Even though most
providers use different methods, adding a key to the API request is
quite simple.
API Key - drawbacks
+The API key only identifies the application, not the user of the
application. It’s often difficult to keep the key a secret.
+For server-to-server communication, it’s possible to hide the key
using TLS and restrict the access to only be used in backend
scenarios. However, since many other types of clients will
consume the APIs, the keys are likely to leak.
ASP.NET Identity
+Is an API that supports user interface (UI) login functionality.
+Manages users, passwords, profile data, roles, claims, tokens,
email confirmation, 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 Identity
HTTP Basic Auth
+HTTP Basic Auth is a simple method that creates a username
and password style authentication for HTTP requests.
+This technique uses a header called Authorization, with a
base64 encoded representation of the username and
password. Depending on the use case, HTTP Basic Auth can
authenticate the user of the application, or the app itself.
HTTP Basic Auth - example

+On the server side we can handle the


authentication/authorization logic using additional middleware
HTTP Basic Auth
+When using basic authentication for an API, this header is usually
sent in every request. The credentials become more or less an API
key when used as authentication for the application. Even if it
represents a username and password, it’s still just a static string.
+In theory, the password could be changed once in a while, but that’s
usually not the case. As with the API keys, these credentials could
leak to third parties. Granted, since credentials are sent in a header,
they are less likely to end up in a log somewhere than using a query
or path parameter, as the API key might do.
HTTP Basic Auth
+Using basic authentication for authenticating users is usually
not recommended since sending the user credentials for every
request would be considered bad practice. If HTTP Basic Auth
is only used for a single request, it still requires the application
to collect user credentials. The user has no means of knowing
what the app will use them for, and the only way to revoke the
access is to change the password.
HTTP Basic Auth - benefits
+HTTP Basic Auth is a standardized way to send credentials.
The header always looks the same, and the components are
easy to implement. It’s easy to use and might be a decent
authentication for applications in server-to-server environments.
HTTP Basic Auth - drawbacks
+When a user is authenticated, the application is required to
collect the password. From the user perspective, it’s not
possible to know what the app does with the password.
+The application will gain full access to the account, and there’s
no other way for the user to revoke the access than to change
the password. Passwords are long-lived tokens, and if an
attacker would get a hold of a password, it will likely go
unnoticed. When used to authenticate the user, multi-factor
authentication is not possible.
Token/Bearer Authentication
+A token-based architecture relies on the fact that all services
receive a token as proof that the application is allowed to call
the service.
+The token might be issued by a third party that can be trusted
by both the application and service (OAuth 2.0).
+OAuth 2.0 is an authorization protocol which uses some of the
techniques described here.
Token/Bearer authentication
+Bearer authentication (also called token authentication) is an
HTTP authentication scheme that involves security tokens
called bearer tokens.
+The name “Bearer authentication” can be understood as “give
access to the bearer of this token.” The bearer token is a cryptic
string, usually generated by the server in response to a login
request. The client must send this token in the Authorization
header when making requests to protected resources:
Bearer token authentication
Access token
+Access token is obtained during the login process. Access
token contain additional information encoded within it (for ex.
Username, roles etc.).
+Access token is usually a JWT (JSON Web Token).
+An example can be found here:
+https://jwt.io/
+Every request to the API should include the Authorization
header containing the access token.
JSON Web Token
+JSON Web Token (JWT) is an open standard (RFC 7519) that defines a
compact and self-contained way for securely transmitting information
between parties as a JSON object.
+This information can be verified and trusted because it is digitally
signed. JWTs can be signed using a secret (with the HMAC algorithm) or
a public/private key pair using RSA or ECDSA.
+This is crucial in providing a stateless mechanism of authentication for
our API.
+Stateless means that the server does not have to „remember” anything
about the generated tokens. The server still will be able to verify the
authenticity of the token using the secret key used to sign it.
When should you use JSON Web Tokens?
+Authorization: This is the most common scenario for using
JWT. Once the user is logged in, each subsequent request will
include the JWT, allowing the user to access routes, services,
and resources that are permitted with that token. Single Sign
On is a feature that widely uses JWT nowadays, because of its
small overhead and its ability to be easily used across different
domains.
When should you use JSON Web Tokens?
+Information Exchange: JSON Web Tokens are a good way of
securely transmitting information between parties. Because
JWTs can be signed—for example, using public/private key
pairs—you can be sure the senders are who they say they are.
Additionally, as the signature is calculated using the header and
the payload, you can also verify that the content hasn't been
tampered with.
What is the JSON Web Token structure?
+In its compact form, JSON Web Tokens consist of three parts
separated by dots (.), which are:
+Header
+Payload
+Signature
+Therefore, a JWT typically looks like the following.
+xxxxx.yyyyy.zzzzz
What is the JSON Web Token structure?
+ Header
+ The header typically consists of two parts: the type of the token, which is JWT, and the signing
algorithm being used, such as HMAC SHA256 or RSA.
+ Payload
+ The second part of the token is the payload, which contains the claims. Claims are statements about
an entity (typically, the user) and additional data. There are three types of claims: registered, public,
and private claims.
+ Registered claims: These are a set of predefined claims which are not mandatory but
recommended, to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp
(expiration time), sub (subject), aud (audience), and others.
+ Public claims: These can be defined at will by those using JWTs. But to avoid collisions they should
be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision
resistant namespace.
+ Private claims: These are the custom claims created to share information between parties that
agree on using them and are neither registered or public claims.
What is the JSON Web Token structure?
+Do note that for signed tokens this information, though
protected against tampering, is readable by anyone. Do not put
secret information in the payload or header elements of a
JWT unless it is encrypted.
+Signature
+To create the signature part you have to take the encoded header, the
encoded payload, a secret, the algorithm specified in the header, and
sign that.
+For example if you want to use the HMAC SHA256 algorithm, the
signature will be created in the following way:
Implementing the process in ASP.NET
Core Web API
+Add the NuGet package:
+Microsoft.AspNetCore.Authentication.
+Usually JWT is short-lived. It expires after a few minutes. After
the token is expired the server should return 401 with additional
info in header.
+Client can use the refresh token to obtain new access token
without login and password. Refresh t
+This we even in case of access token being leaked to anyone –
the token will expire after short time.
Refresh token process
1. Injecting services and configuring token
validation process
2. Adding necessary middlewares
How to store password securely?
+Password should never be stored as plaintext in the database
+Password should be stored as hashed values – preferably with the
addition of salt and pepper (pepper is used in critical security
situations).
+We should use a cryptographically strong hashing function
+Hashed passwords are not unique to themselves due to the
deterministic nature of the hash function: when given the same input,
the same output is always produced. This potentially makes certain
attacks possible and easier (dictionary-based attacks or rainbow
tables).
How to store password securely?
+Mitigating Password Attacks with Salt
+ To mitigate the damage that a hash table or a dictionary attack could do, we
salt the passwords. According to OWASP Guidelines, a salt is a value
generated by a cryptographically secure function
+ A salt is a unique, randomly generated string that is added to each password
as part of the hashing process. As the salt is unique for every user, an
attacker has to crack hashes one at a time using the respective salt rather
than calculating a hash once and comparing it against every stored hash.
+ This makes cracking large numbers of hashes significantly harder, as the time
required grows in direct proportion to the number of hashes.
How to store password securely?
+ Peppering
+ A pepper can be used in addition to salting to provide an additional layer of protection.
The purpose of the pepper is to prevent an attacker from being able to crack any of the
hashes if they only have access to the database, for example, if they have exploited a
SQL injection vulnerability or obtained a backup of the database.
+ One of several peppering strategies is to hash the passwords as usual (using a password
hashing algorithm) and then HMAC or encrypt the hashes with a symmetrical encryption
key before storing the password hash in the database, with the key acting as the pepper.
Peppering strategies do not affect the password hashing function in any way.
+ The pepper is shared between stored passwords, rather than being unique like a salt.
+ Unlike a password salt, the pepper should not be stored in the database.
+ Peppers are secrets and should be stored in "secrets vaults" or HSMs (Hardware
Security Modules).
+ Like any other cryptographic key, a pepper rotation strategy should be considered.
PBKDF2 - Password-Based Key Derivation
Function 2
+PBKDF2 is a simple cryptographic key derivation function,
which is resistant to dictionary attacks and rainbow table
attacks.
+It is based on iteratively deriving HMAC many times with some
padding. The PBKDF2 algorithm is described in the Internet
standard RFC 2898 (PKCS #5).
+PBKDF2 is a good way to store password securely in database
Example
+The code example can be found within code sample from
lecture
Bibliography
+ https://docs.microsoft.com/en-us/ef/core/querying/related-data/
+ https://docs.microsoft.com/en-us/ef/core/querying/related-data/lazy
+ https://www.brentozar.com/archive/2018/07/common-entity-framework-problems-
n-1/
+ https://docs.microsoft.com/pl-
pl/aspnet/core/security/authentication/?view=aspnetcore-5.0
+ https://blog.gutek.pl/2015/05/04/asp-net-5-middleware-krtko-ale-trafnie/
+ https://www.tutorialsteacher.com/core/aspnet-core-middleware
+ https://nordicapis.com/the-difference-between-http-auth-api-keys-and-oauth/
+ https://jwt.io/introduction
Bibliography
+https://auth0.com/blog/adding-salt-to-hashing-a-better-way-to-
store-passwords/
+https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_
Storage_Cheat_Sheet.html
+https://cheatsheetseries.owasp.org/cheatsheets/Password_Stor
age_Cheat_Sheet.html#salting
APBD – lecture 10
Web applications
ASP.NET MVC
Desktop vs Web application etc.
+During our classes we are talking mostly about web apps.
+WebApps nowadays have a lot of advantages over classical
desktop apps related mostly to advancements in web
technologies and web browsers.
How to choose what kind of app we want
to use?

https://www.scnsoft.com/blog/mobile-web-app-types
Web technologies
+Web browsers - Browsers request information and then they
show us in the way we can understand. Think of them as the
interpreters of the web. (Google Chrome, Safari, Firefox, Edge
etc.)
Web technologies
+HTML5 - HTML is a markup language which is used by the
browser to manipulate text, images and other content to display
it in required format.
+Nowadays HTML5 is a living standard.
+HTML5 constists not only from the definitione of „tags”. There are also
numerous APIs

+HTML Standard (whatwg.org)


+https://www.w3.org/TR/html52/
Web technologies
+CSS3
+Used for styling the HTML elements
+Cascading Style Sheets Level 3 (CSS3) is the iteration of the CSS
standard used in the styling and formatting of Web pages.
+CSS3 incorporates the CSS2 standard with some changes and
improvements.
+https://www.w3.org/TR/2001/WD-css3-roadmap-20010523/
Web technologies
+JavaScript (EcmaScript)
+ Is a general-purpose programming language, standardised by Ecma
International according to the document ECMA-262
+ https://www.ecma-international.org/publications-and-
standards/standards/ecma-262/
+ JavaScript is an interpreted language, not a compiled language.
+ At the beginning used only for simple web site scripting – nowadays we can
say that its a multi-purpose language used for web, server, mobile etc.
+ Big change for development of JS language was introduction of Node.js
(around 2010-2011)
+ https://www.youtube.com/watch?v=jo_B4LTHi3I
Website, webapps etc.
+We will try to get step-by-step a numer of different ways to
create a website/webapp
1. Static website (HTML, CSS, JS)
EXAMPLE
2. MPA – server-side rendered app
+We would like the content of the website to be dynamic (for ex.
different for every user).
+We can use different server-side rendering for that (SSR)
+There are a lot of server-side technologies we can use for that:
+Java, C#, Python, JS (Node.js), Ruby, etc.
+What are the advantages and disadvantages of MPA?
2. MPA – server-side rendered app
EXAMPLE
3. SPA – Single-page applications
+A single-page application is an app that works inside a browser
and does not require page reloading during use. You are using
this type of applications every day. These are, for instance:
Gmail, Google Maps, Facebook or GitHub.
+SPAs are all about serving an outstanding UX by trying to
imitate a “natural” environment in the browser — no page
reloads, no extra wait time.
3. SPA – Single-page applications
+SPA requests the markup and data independently and renders
pages straight in the browser.
+We can do this thanks to the advanced JavaScript frameworks
like AngularJS, Ember.js, Meteor.js, Knockout.js, React.js,
Vue.js
+Another important step in developing SPA was introducing
possibility of making AJAX requests directly from the browser
+What are the advantages and disadvantages of SPA?
3. SPA – Single-page applications
4. PWA – Progressive Web Apps, Hybrid
web apps
+Progressive Web Apps are using extensively modern HTML5
apis – especially those related to caching the data on the client
side. This way we are able to create a web application that can
work offline.
+Hybrid apps – mixing the SPA approach with SSR. Often using
technologies like Next.js or Gatsby.js
+What are the advantages and disadvantages of PWA/Hybrid
apps?
.Release history
ASP.NET MVC history
ASP.NET MVC Core
+ASP.NET Core MVC is a rich framework for building web apps
and APIs using the Model-View-Controller design pattern.
+What is the MVC pattern?
+The Model-View-Controller (MVC) architectural pattern separates an
application into three main groups of components: Models, Views, and
Controllers. This pattern helps to achieve separation of concerns.
Model Responsibilities
+The Model in an MVC application represents the state of the
application and any business logic or operations that should be
performed by it. Business logic should be encapsulated in the
model, along with any implementation logic for persisting the
state of the application.
View Responsibilities
+Views are responsible for presenting content through the user
interface. They use the Razor view engine to embed .NET code
in HTML markup.
Controller Responsibilities
+Controllers are the components that handle user interaction,
work with the model, and ultimately select a view to render.
+In an MVC application, the view only displays information; the
controller handles and responds to user input and interaction. In
the MVC pattern, the controller is the initial entry point, and is
responsible for selecting which model types to work with and
which view to render (hence its name - it controls how the app
responds to a given request).
What is ASP.NET Core MVC
+The ASP.NET Core MVC framework is a lightweight, open
source, highly testable presentation framework optimized for
use with ASP.NET Core.
+ASP.NET Core MVC provides a patterns-based way to build
dynamic websites that enables a clean separation of concerns. It
gives you full control over markup, supports TDD-friendly
development and uses the latest web standards.
Example
Routing
+ASP.NET Core MVC is built on top of ASP.NET Core's routing, a
powerful URL-mapping component that lets you build
applications that have comprehensible and searchable
URLs. Convention-based routing enables you to globally define
the URL formats that your application accepts and how each of
those formats maps to a specific action method on a given
controller
Routing
+Attribute routing enables you to specify routing information by
decorating your controllers and actions with attributes that
define your application's routes.
Model binding
+ASP.NET Core MVC model binding converts client request data
(form values, route data, query string parameters, HTTP
headers) into objects that the controller can handle.
+As a result, your controller logic doesn't have to do the work of
figuring out the incoming request data; it simply has the data as
parameters to its action methods.
Model validation
+ASP.NET Core MVC supports validation by decorating your
model object with data annotation validation attributes. The
validation attributes are checked on the client side before
values are posted to the server, as well as on the server before
the controller action is called.
Model validation
Model validation
Dependency injection
+ASP.NET Core has built-in support for dependency injection
(DI). In ASP.NET Core MVC, controllers can request needed
services through their constructors, allowing them to follow the
Explicit Dependencies Principle.
Filters
+Filters help developers encapsulate cross-cutting concerns, like
exception handling or authorization.
+Filters enable running custom pre- and post-processing logic for
action methods, and can be configured to run at certain points
within the execution pipeline for a given request. Filters can be
applied to controllers or actions as attributes (or can be run
globally).
Razor view engine
+ASP.NET Core MVC views use the Razor view engine to
render views. Razor is a compact, expressive and fluid template
markup language for defining views using embedded C# code.
+Razor is used to dynamically generate web content on the
server. You can cleanly mix server code with client side content
and code.
Strongly typed views
+Razor views in MVC can be strongly typed based on your
model.
+Controllers can pass a strongly typed model to views enabling
your views to have type checking and IntelliSense support.
Bibliography
+Overview of ASP.NET Core MVC | Microsoft Docs
+Get started with ASP.NET Core MVC | Microsoft Docs
+https://docs.microsoft.com/en-
us/aspnet/core/mvc/overview?view=aspnetcore-5.0
+https://www.c-sharpcorner.com/article/getting-started-with-net-
core-on-visual-studio-2017/
APBD – lecture 11
WebAssembly
Blazor – server side
WebAssembly - problems
+Earlier in the past, the VM has been ready to load only
JavaScript. This has worked well for us as JavaScript is
powerful enough to resolve most problems people face on the
internet today.
+We have got run into performance problems, however, when
trying to use JavaScript for more compelling use cases like
Virtual and Augmented Reality( VR and AR), 3D games,
computer vision, image/video editing, and different other
domains that demand native performance.
WebAssembly - problems
+Additionally, the value of downloading, compiling and parsing
huge JavaScript apps are prohibitive. Smart Phones and other
resource-constrained platforms can further amplify these
performance bottlenecks.
+With the arrival of WebAssembly appearing in browsers, the
virtual machine that we talked about earlier will now load and
run two forms of code — JavaScript and WebAssembly.
What is WebAssembly?
+WebAssembly is a new type of code that can be run in modern web
browsers and provides new features and major gains in performance. It
is not primarily intended to be written by hand, rather it is designed to
be an effective compilation target for source languages like C, C++,
Rust, etc.

+This has huge implications for the web platform — it provides a way to
run code written in multiple languages on the web at near-native
speed, with client apps running on the web that previously couldn’t
have done so.
WebAssembly
WebAssembly
JavaScript vs WASM
JavaScript vs WASM
WASM
+WebAssembly is a binary instruction format for a
stack-based virtual machine

+WASM is designed as a portable target for


compilation of high-level languages like
C/C++/Rust enabling deployment on the web for
client/server applications
What is WebAssembly?
+WebAssembly is a new type of code that can be run in modern web
browsers and provides new featurWhat’s more, you don’t even have
to know how to create WebAssembly code to take advantage of it.
+WebAssembly modules can be imported into a web (or Node.js) app,
exposing WebAssembly functions for use via JavaScript.
+JavaScript frameworks could make use of WebAssembly to confer
massive performance advantages and new features while still
making functionality easily available to web developers.s and major
gains in performance. It is not primarily intended to be written by
hand, rather it is designed to be an effective compilation target for
source languages like C, C++, Rust, etc.
WebAssembly goals
+WebAssembly is being created as an open standard inside the
W3C WebAssembly Community Group with the following goals:
+Be fast, efficient, and portable — WebAssembly code can be
executed at near-native speed across different platforms by taking
advantage of common hardware capabilities.
+Be readable and debuggable — WebAssembly is a low-level
assembly language, but it does have a human-readable text format (the
specification for which is still being finalized) that allows code to be
written, viewed, and debugged by hand.
WebAssembly goals
+Keep secure — WebAssembly is specified to be run in a safe,
sandboxed execution environment. Like other web code, it will
enforce the browser's same-origin and permissions policies.
+Don't break the web — WebAssembly is designed so that it
plays nicely with other web technologies and maintains
backwards compatibility.
WebAssembly
+WebAssembly Compatability with Web Platform. The web
platform is thought of as having two parts:
+A virtual machine (VM) that runs the web applications code, e.g. the JS
code that powers your apps.
+A set of Web APIs that a web application can call to regulate web
browser/device functionality and make things happen (CSSOM, DOM,
IndexedDB, WebGL, Web Audio API, etc.).
WebAssembly - benefits
Write WebAssembly Yourself

https://webassembly.studio/
WebAssembly – C++
WebAssembly – C#
WebAssembly and JS
Blazor
+Blazor is a framework for building interactive client-side web UI
with .NET:
+Create rich interactive UIs using C# instead of JavaScript.
+Share server-side and client-side app logic written in .NET.
+Render the UI as HTML and CSS for wide browser support, including
mobile browsers.
+Integrate with modern hosting platforms, such as Docker.
Blazor - components
+Blazor apps are based on components. A component in Blazor
is an element of UI, such as a page, dialog, or data entry form.
+Components are .NET C# classes built into .NET assemblies
that:
+Define flexible UI rendering logic. \
+Handle user events.
+Can be nested and reused.
+Can be shared and distributed as Razor class libraries or NuGet
packages.
Blazor WebAssembly
+Blazor WebAssembly is a single-page app (SPA) framework for
building interactive client-side web apps with .NET.
+Blazor WebAssembly uses open web standards without plugins
or recompiling code into other languages.
+Blazor WebAssembly works in all modern web browsers,
including mobile browsers.
+Running .NET code inside web browsers is made possible by
WebAssembly (abbreviated wasm).
Blazor WebAssembly
+When a Blazor WebAssembly app is built and run in a browser:
+C# code files and Razor files are compiled into .NET assemblies.
+The assemblies and the .NET runtime are downloaded to the browser.
+Blazor WebAssembly bootstraps the .NET runtime and configures the
runtime to load the assemblies for the app. The Blazor WebAssembly
runtime uses JavaScript interop to handle DOM manipulation and
browser API calls.
Blazor WebAssembly
Blazor – Client side
Blazor Server
+Blazor decouples component rendering logic from how UI
updates are applied.
+Blazor Server provides support for hosting Razor components
on the server in an ASP.NET Core app. UI updates are handled
over a SignalR connection.
Blazor Server
+The runtime stays on the server and handles:
+Executing the app's C# code.
+Sending UI events from the browser to the server.
+Applying UI updates to the rendered component that are sent back by
the server.
The connection used by Blazor Server to communicate with the browser
is also used to handle JavaScript interop calls.
Blazor Server
@page directive
+Routing tules helps us define which component will appear on
the screen according to the URL in which the user is located
+There routing rules are configured using the @page directive
@page directive
App.razor
+App.razor defines our routing template
+By default defines the view that will be displayed in case of a
missing element
+Otherwise displays the component based by the route
App.razor
App.razor- changing the 404 page
Route params
Route constraints
Catch-all route
NavigationManager
+Use NavigationManager to manage URIs and navigation in C#
code. NavigationManager provides the event and methods
shown in the following table.
NavigationManager
NavigationManager
Working with 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. Razor is also found in Razor components files
(.razor).
+https://docs.microsoft.com/en-
us/aspnet/core/mvc/views/razor?view=aspnetcore-5.0
Working with Razor
Working with Razor - classes
+Let’s define a separate class
Working with Razor - classes
+We can use _Imports.razor file to define the common imports
available in all the components
Working with Razor - classes
Working with Razor – loops/conditionals
+Lets create a Models folder with a student class
Working with Razor
+Using MarkupString allows us to
interpret corretly the HTML
(carefull with injections)
Working with Razor
Working with Razor
Components
+A component is a resuable piece of user interface, which may
contain logic
+A component is a class
+We can nest component to create complex interfaces
+Similar idea to other frontend technologies like
React/Angular/Vue
Atomic design
First component - StudentsList
+Let’s extract the Students list to a separate razor component –
Shared/StudentsList.razor
StudentsList.razor
StudentsList.razor
Using component
+Then we can create a new page Students in which we can use
our previously created StudentsList.razor component
Parameters
+A component can receive parameters through its parameters
+Parameters can be data, events, content
Parameter - StudentList
+Let’s assume we can pass a list of students from parent
component to child component.
+To do that we have to add the [Parameter] property to the
StudentList component.
Parameter - StudentList
Parameter - StudentList
+Now we can pass a list of
students from parent
component
Arbitrary parameters
+Allows us to easily pass multiple parameters at once
Arbitrary parameters
Data binding
+Allows us to synchronize the control with the data
+Razor components provide data binding features with the
@bind Razor directive attribute with a field, property, or Razor
expression value.
Data binding
Event callback
+Events allows us to pass data from child component to the
parent component.
+Parent passed even handler to the child component. Then the
child component calls the event handler and passes the data to
the parent controller
Event callback - child
Event callback - parent
Render fragment
RenderFragment is used to render
components or content at run time in Blazor.

The RenderFragment class allows you to


create the required content or component in a
dynamic manner at runtime. In the following
code example, the content is created at
runtime on OnInitialized.
Render fragment
Lifecycle of a Component
+OnInitialized and OnInitializedAsync
+OnParameterSet and OnParameterSetAsync
+OnAfterRender and OnAfterRenderAsync
+ShouldRender
Lifecycle of a
Component
Partial classes
Bibliography
+https://developer.mozilla.org/en-
US/docs/WebAssembly/Concepts
+https://gavilan.blog/blog/
+https://docs.microsoft.com/en-
us/aspnet/core/blazor/fundamentals/routing?view=aspnetcore-
5.0
+https://atomicdesign.bradfrost.com/chapter-2/
APBD – lecture WebAssembly

11/12 Blazor – client side


WebAssembly
+WebAssembly is a new type of code that can be run in modern
web browsers — it is a low-level assembly-like language with a
compact binary format that runs with near-native performance
and provides languages such as C/C++, C# and Rust with a
compilation target so that they can run on the web. It is also
designed to run alongside JavaScript, allowing both to work
together.
SPA
+A single-page application (SPA) is a web application or website
that interacts with the user by dynamically rewriting the current
web page with new data from the web server, instead of the
default method of a web browser loading entire new pages.
WebAssembly
WebAssembly – C#
Introduction to ASP.NET Core Blazor
+Blazor is a framework for building interactive client-side web UI
with .NET:
+Create rich interactive UIs using C# instead of JavaScript.
+Share server-side and client-side app logic written in .NET.
+Render the UI as HTML and CSS for wide browser support, including
mobile browsers.
+Integrate with modern hosting platforms, such as Docker.
Blazor Client Side - advantages
+Using .NET for client-side web development offers the following
advantages:
+Write code in C# instead of JavaScript.
+Leverage the existing .NET ecosystem of .NET libraries.
+Share app logic across server and client.
+Benefit from .NET's performance, reliability, and security.
+Stay productive with Visual Studio on Windows, Linux, and macOS.
+Build on a common set of languages, frameworks, and tools that are
stable, feature-rich, and easy to use.
Blazor Client Side - features
+Blazor Client Side is using the same features we have
discussed during our last lecture:
+Component based architecture
+@page directive and routing mechanism
Blazor Client Side – hosting model
+The primary Blazor hosting model is running client-side in the
browser on WebAssembly. The Blazor app, its dependencies,
and the .NET runtime are downloaded to the browser.
+The app is executed directly on the browser UI thread.
+UI updates and event handling occur within the same
process. The app's assets are deployed as static files to a web
server or service capable of serving static content to clients.
Blazor Client Side – hosting model
Blazor Client Side – hosting model
+When the Blazor WebAssembly app is created for deployment
without a backend ASP.NET Core app to serve its files, the app
is called a standalone Blazor WebAssembly app.
+When the app is created for deployment with a backend app to
serve its files, the app is called a hosted Blazor
WebAssembly app.
Blazor Client Side – hosting model
+A hosted Blazor WebAssembly Client app typically interacts
with the backend Server app over the network using web API
calls or SignalR (Use ASP.NET Core SignalR with Blazor).
Example – initial project structure
Communication between backend and
frontend
Blazor Client Side – project structure
+The blazor.webassembly.js script is provided by the framework
and handles:
+Downloading the .NET runtime, the app, and the app's dependencies.
+Initialization of the runtime to run the app.
PWA – Progressive Web Apps
+The term "Progressive Web App" isn't a formal or official
name. It's just a shorthand used initially by Google for the
concept of creating a flexible, adaptable app using only web
technologies.
PWA – Progressive Web Apps
+Progressive Web Apps (PWAs) provide access to open web
technologies for cross-platform interoperability and provide
your users with a native, app-like experience customized for
their devices.
+PWAs are websites that are progressively enhanced to
function like native apps on supporting platforms. The
qualities of a PWA combine the best of the web and native
apps.
What makes an app a PWA?
+PWAs are not created with a single technology
+They represent a new philosophy for building web apps,
involving some specific patterns, APIs, and other features.
+. It's not that obvious if a web app is a PWA or not from first
glance.
+An app could be considered a PWA when it meets certain
requirements, or implements a set of given features: works
offline, is installable, is easy to synchronize, can send push
notifications, etc.
What makes an app a PWA?
+In addition, there are tools to measure how complete (as a
percentage) a web app is, such as Lighthouse.
+By implementing various technological advantages, we can
make an app more progressive, thus ending up with a higher
Lighthouse score. But this is only a rough indicator.
PWA characteristics
+Discoverable:
+the contents can be found through search engines.
+Installable
+it can be available on the device's home screen or app launcher.
+Linkable
+so you can share it by sending a URL
+Network independent
+so it works offline or with a poor network connection.
PWA characteristics
+Progressive
+ so it's still usable on a basic level on older browsers, but fully-functional on
the latest ones.
+Re-engageable
+ so it's able to send notifications whenever there's new content available
+Responsive
+ so it's usable on any device with a screen and a browser—mobile phones,
tablets, laptops, TVs, refrigerators, etc.
+Safe
+ so the connections between the user, the app, and your server are secured
against any third parties trying to get access to sensitive data.
Blazor Client Side – advantages
+The Blazor WebAssembly hosting model offers several benefits:
+There's no .NET server-side dependency. The app is fully functioning
after it's downloaded to the client.
+Client resources and capabilities are fully leveraged.
+Work is offloaded from the server to the client.
+An ASP.NET Core web server isn't required to host the app. Serverless
deployment scenarios are possible, such as serving the app from a
Content Delivery Network (CDN).
Blazor Client Side – disadvantages
+The app is restricted to the capabilities of the browser.
+Capable client hardware and software (for example,
WebAssembly support) is required.
+Download size is larger, and apps take longer to load.
+.NET runtime and tooling support is less mature. For example,
limitations exist in .NET Standard support and debugging.
Blazor Client Side – server-hosted
+Usually SPA require some kind of remote API to communicate
with database and/or other services
Blazor Client Side – server-hosted
Isomorphic web application architecture
+The isomorphic web application architecture consists of
implementing two web applications, one on the server side
and one on the client side, using the same programming
language and reusing code across the two environments.
Blazor Client Side – server-hosted
Blazor Client Side – server-hosted
Question – why do we need backend?
Blazor Client Side app
+ Project structure
+ Fundamentals
+ Dependency injection
+ Static files
+ Configuration
+ Layouts
+ Components
+ Routing
+ Forms
+ API communication
+ Security
ASP.NET Core Blazor forms and validation
+The Blazor framework supports webforms with validation using
the EditForm component bound to a model that uses data
annotations.
ASP.NET Core Blazor forms and validation
+An EditForm creates an EditContext based on the assigned
model instance as a cascading value for other components
in the form.
+The EditContext tracks metadata about the edit process,
including which fields have been modified and the current
validation messages.
+Assigning to either an EditForm.Model or an
EditForm.EditContext can bind a form to data.
ASP.NET Core Blazor forms and validation
ASP.NET Core Blazor forms and validation
ASP.NET Core Blazor forms and validation
form submission
+The EditForm provides the following callbacks for handling form
submission:
+Use OnValidSubmit to assign an event handler to run when a form
with valid fields is submitted.
+Use OnInvalidSubmit to assign an event handler to run when a
form with invalid fields is submitted.
+Use OnSubmit to assign an event handler to run regardless of the
form fields' validation status. The form is validated by calling
EditContext.Validate in the event handler method. If Validate returns
true, the form is valid.
Built-in form components
+The Blazor framework provides built-in form components to
receive and validate user input.
+Inputs are validated when they're changed and when a form is
submitted. Available input components are shown in the
following table.
Built-in form components
Built-in form components
+All of the input components, including EditForm, support
arbitrary attributes.
+Any attribute that doesn't match a component parameter is
added to the rendered HTML element.
Built-in form components
+Input components provide default behavior for validating when
a field is changed, including updating the field CSS class to
reflect the field's state as valid or invalid.
+Some components include useful parsing logic.
+For example, InputDate<TValue> and InputNumber<TValue>
handle unparseable values gracefully by registering
unparseable values as validation errors.
Built-in form components
+Display name support:
+The following built-in components support display names with the
InputBase<TValue>.DisplayName parameter:
+ InputDate<TValue>
+ InputNumber<TValue>
+ InputSelect<TValue>
Built-in form components

If the field contains an invalid date when the form is submitted,


the error message doesn't display a friendly name. The field
name, "ProductionDate" doesn't have a space between
"Production" and "Date" when it appears in the validation
summary:
Built-in form components

The validation summary displays the friendly name when the field's value
is invalid:
Example
Data Annotations Validator component
and custom validation
+The DataAnnotationsValidator component attaches data
annotations validation to a cascaded EditContext.
+Enabling data annotations validation requires the
DataAnnotationsValidator component.
+To use a different validation system than data annotations, use
a custom implementation instead of the
DataAnnotationsValidator component.
Data Annotations Validator component
and custom validation
+Blazor performs two types of validation:
+Field validation is performed when the user tabs out of a field. During
field validation, the DataAnnotationsValidator component associates all
reported validation results with the field.
+Model validation is performed when the user submits the form.
During model validation, the DataAnnotationsValidator component
attempts to determine the field based on the member's name that the
validation result reports.
+Validation results that aren't associated with an individual member are
associated with the model rather than a field.
Validator components
+Validator components support form validation by managing a
ValidationMessageStore for a form's EditContext.
+The Blazor framework provides the DataAnnotationsValidator
component to attach validation support to forms based on
validation attributes (data annotations).
+You can create custom validator components to process
validation messages for different forms on the same page or the
same form at different steps of form processing.
Validator components – step-by-step
+Create a validator component from ComponentBase:
+When the validator component is initialized, a new
ValidationMessageStore is created to maintain a current list of
form errors.
+The message store receives errors when developer code in the form's
component calls the DisplayErrors method. The errors are passed to
the DisplayErrors method in a Dictionary<string, List<string>>. In the
dictionary, the key is the name of the form field that has one or more
errors. The value is the error list.
Validator components – step-by-step
+Messages are cleared when any of the following have occurred:
+Validation is requested on the EditContext when the
OnValidationRequested event is raised. All of the errors are cleared.
+A field changes in the form when the OnFieldChanged event is
raised. Only the errors for the field are cleared.
+The ClearErrors method is called by developer code. All of the
errors are cleared.
Validation on client and backend side
+Server validation is supported in addition to client-side validation:
+ Process client-side validation in the form with the DataAnnotationsValidator
component.
+ When the form passes client-side validation (OnValidSubmit is called), send
the EditContext.Model to a backend server API for form processing.
+ Process model validation on the server.
+ The server API includes both the built-in framework data annotations
validation and custom validation logic supplied by the developer. If validation
passes on the server, process the form and send back a success status code
(200 - OK). If validation fails, return a failure status code (400 - Bad Request)
and the field validation errors.
+ Either disable the form on success or display the errors.
Differences between client-side and
server-side validation
Communication between backend and
frontend
+Putting everything together
+More complex componenets
+Generic list
+Paging
+HTTP communication
+Smart vs Dumb Componenents
Communication between backend and
frontend
+Client side
+Business logic (thin or fat client)
+Validation (UX)
+Server side
+Business logic
+Validation
+Communication with database
+Shared
+Entities shared between server and client-side code
Bibliography
+ https://docs.microsoft.com/en-
us/aspnet/core/blazor/?view=aspnetcore-5.0
https://subscription.packtpub.com/book/web_development/97817
88394185/1/ch01lvl1sec12/the-single-page-application-spa-
architecture
https://docs.microsoft.com/en-us/aspnet/core/blazor/progressive-
web-app?view=aspnetcore-5.0&tabs=visual-studio
https://developer.mozilla.org/en-
US/docs/Web/Progressive_web_apps/Introduction

You might also like