APBD
APBD
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
• 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.
• 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
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
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„
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.
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
+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
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 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