Web Application
Programming Interface
(API)
Tahaluf Training Center 2023
1 Overview Of [Link] Core
2 Why [Link] Core ?
3 Differences between [Link] Core and [Link]
4 Overview of [Link] Web API
5 Difference between MVC & Web API
Overview Of
[Link] Core
[Link] Core is the latest version of Microsoft’s .NET Framework, which is a free, open-source,
general-purpose development platform. It's a cross-platform framework that works with Windows,
Mac OS X, and Linux.
Many applications can be made using [Link] Core, Such as Internet of Things (IoT)
apps, web apps, and mobile backends. Can run on the cloud or on-premises.
Why [Link] Core ?
Cross-platform
Open-source.
Development methods (can develop on multiple platforms)
Why
[Link] Core lightweight framework.
Deployment including Containerization
A cloud-ready.
Built-in dependency injection.
High speed and performance
DI (Dependency Injection) is a design pattern for software. It enables us to write code that is
loosely coupled. Dependency Injection's goal is to make code more manageable. Dependency
Injection helps in the reduction of tight coupling between program components. Dependency
Injection eliminates hard-coded dependencies between your classes by injecting them at
runtime rather than at design time.
Differences between [Link]
Core and [Link]
BASED ON .NET Core .NET Framework
The .Net Framework contains a few
Open Source .Net Core is an open source.
open source components.
(cross-platform) compatible with various
compatible with the only windows
Cross-Platform operating systems — Windows, Linux,
operating system.
and Mac OS.
. Net Core does not support the
. The Net Framework is used to create
development of desktop applications;
desktop and web applications, and it
Application Models instead, it is focused on the web,
also supports WPF and Windows
Windows Mobile, and the Windows
Forms applications.
Store.
BASED ON .NET Core .NET Framework
.NET Core is compatible with .NET Framework is compatible
Compatibility various operating systems — only with the Windows operating
Windows, Linux, and Mac OS. system.
[Link] Framework libraries are all
.Net Core software is distributed
Packaging and Shipping packaged and provided as a single
as a collection of Nugget packages.
unit.
BASED ON .NET Core .NET Framework
Micro-services may be created While REST API services are
Support for Micro-Services and and implemented using .Net Core, supported by .Net Framework,
API Services and a REST API is created in order microservice creation and
to accomplish this. implementation are not.
In terms of performance and
High performance and scalability application scalability,.Net
Performance and Scalability
are advantages [Link] Core. Framework performs less
effectively [Link] Core.
Difference between
MVC & Web API
While [Link] MVC is used to build web applications that provide both
views and data, [Link] Web API is used to quickly and easily create HTTP
services that just return data.
Web API will also take care of returning data in a certain format, such as JSON,
XML, or any other dependent on the Accept header in the request, so you don't
have to bother about it. JsonResult is an MVC feature that exclusively returns
data in JSON format.
Use [Link] MVC if you want to provide services that are only relevant to one
application. On the other hand, if your business requirements require you to offer
the functionality generally, you would desire a Web API approach.
While the request is mapped to actions in Web API based on HTTP verbs, it
is mapped to action names in MVC.
Additionally, Web API is a lightweight design that may be utilized with
mobile apps in addition to web applications.
Overview of [Link]
Web API
What are RESTful Services?
REST represents a Representational State Transfer.
REST is an architectural pattern used to create an API that uses HTTP as a
communication method.
REST specifies a collection of constraints that a system must adhere to.
❑ Client Server
A client sends a request, then a Server sends a response. This separation of concerns
supports the independence and evolution of server-side logic and client-side logic.
❑ Stateless
The communication between server and a client must be stateless.
The request from the client should contain all the information for the server needs it to complete a
process.
Each request is treated independently by the server.
❑ Cacheable
Every response should specify whether or not it can be cached on the client side as well as how
long it may be cached there. For any subsequent requests, the client will return the data from its
cache, eliminating the need to resend the request to the server.
❑ Uniform Interface
It implies that there should be a standard way of interacting with a certain server regardless of the
device or kind of application (website, mobile app).
❑ Layered system
An application architecture must be composed of several levels. There are several intermediary
servers between the client and the end server, and each layer has no knowledge of any layer other
than its immediate layer.
❑ Code on demand
It is an optional feature. Servers can also give executable code to clients, according to this such as
JavaScript code.
References
1. Complete Guide to Test Automation Arnon Axelrod 2018.
2. [Link]
Overview of Database
3. [Link]
Web Application
Programming Interface
(API)
Tahaluf Training Center 2023
1 Create a Class Diagram
2 Overview of Package
3 Overview of Stored Procedure
4 Create Package And Stored Procedure
Create a Class Diagram
Create the
following class
diagram
Overview of Package
A package is a schema object used to collect logically related PL/SQL variables, types and
subprograms.
Packages have two parts, a specification (header) and a body.
The specification is the interface.
The body used to define the code for the subprograms and the queries for the cursors.
Overview of Stored
Procedure
Stored procedures are similar to functions.
Stored procedure is created once and can be executed more than one time.
A stored procedure is created with a CREATE PROCEDURE statement and is executed
with a CALL statement.
Create Package And
Stored Procedure
Example 1
Create a course package that contains stored procedures to:
➢ display all courses in the database.
➢ Create a course.
➢ Update a course.
➢ Delete a course
➢ Get course by ID
The Learning Hub Copyright
2022- All Right Reserved
Packages Specification
create or replace PACKAGE Course_Package
As
PROCEDURE GetAllCourses;
PROCEDURE GetCourseById(id in number) ;
PROCEDURE CREATECOURSE(COURSENAME IN
[Link]%TYPE, CATID IN [Link]%TYPE,
image in varchar);
PROCEDURE UPDATECOURSE( ID IN NUMBER ,CNAME IN
[Link]%TYPE, CATID IN [Link]%TYPE,
image in varchar);
PROCEDURE DeleteCourse(Id in number);
End Course_Package;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
create or replace Package BODY Course_Package
As
PROCEDURE GetAllCourses
As
cur_all SYS_REFCURSOR ;
Begin
open cur_all for
Select * From course ;
Dbms_sql.return_result(cur_all);
End GetAllCourses ;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
PROCEDURE GetCourseById(id in number)
As
Cur_item SYS_REFCURSOR;
Begin
open cur_item for
select * from course
where courseid = id;
Dbms_sql.return_result(cur_item);
End GetCourseById;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
PROCEDURE CREATECOURSE(COURSENAME IN
[Link]%TYPE, CATID IN [Link]%TYPE ,
image in varchar)
AS
id number ;
BEGIN
INSERT INTO COURSE VALUES (DEFAULT , COURSENAME , CATID ,
image );
COMMIT;
END CREATECOURSE;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
PROCEDURE UPDATECOURSE( ID IN NUMBER ,CNAME IN
[Link]%TYPE, CATID IN [Link]%TYPE ,
image in varchar)
AS
BEGIN
UPDATE COURSE
SET COURSENAME = CNAME , categoryid = CATID , imagename =
image
WHERE COURSEID = ID ;
COMMIT;
END UPDATECOURSE;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
PROCEDURE DeleteCourse(Id in number)
As
Begin
delete from course
where courseid = id ;
commit;
End DeleteCourse;
End Course_Package;
Example 2
Create a student package that contains stored procedures to:
➢ display all students in the database.
➢ Create a student.
➢ Update a student.
➢ Delete a student
➢ Get student by ID
The Learning Hub Copyright
2022- All Right Reserved
Packages Specification
create or replace PACKAGE Student_Package AS
PROCEDURE GetAllStudent;
PROCEDURE CreateStudent(first_name IN VARCHAR,last_name in
varchar,date_of_birth in date);
PROCEDURE UpdateStudent(ID IN NUMBER, first_name IN
VARCHAR,last_name IN VARCHAR,date_of_birth date);
PROCEDURE DeleteStudent(ID IN NUMBER);
PROCEDURE GetStudentById(ID IN NUMBER);
END Student_Package;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
create or replace PACKAGE Body Student_Package as
PROCEDURE GetAllStudent
AS
c_all sys_refcursor;
BEGIN
open c_all for
select * from Student;
DBMS_SQL.RETURN_RESULT(c_all);
END GetAllStudent;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
PROCEDURE CreateStudent(first_name IN VARCHAR,last_name in
varchar,date_of_birth in date)
IS
BEGIN
INSERT INTO Student (firstName ,lastname ,dateofbirth )
VALUES(first_name,last_name,date_of_birth);
COMMIT;
END CreateStudent;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
PROCEDURE UpdateStudent(ID IN NUMBER, first_name IN
VARCHAR,last_name IN VARCHAR,date_of_birth date)
IS
BEGIN
Update Student SET firstname=first_name,lastname
=last_name,dateofbirth=date_of_birth
WHERE studentid =ID;
COMMIT;
END UpdateStudent;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
PROCEDURE DeleteStudent(ID IN NUMBER)
IS
BEGIN
DELETE Student WHERE studentid =ID;
COMMIT;
END DeleteStudent;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
PROCEDURE GetStudentById(ID IN NUMBER)
AS
c_all sys_refcursor;
BEGIN
OPEN c_all FOR
SELECT * FROM Student WHERE studentid =ID;
DBMS_SQL.RETURN_RESULT(c_all);
END GetStudentById;
END Student_Package;
Example 3
Create a studentCourse package that contains stored procedures to:
➢ display all studentCourse in the database.
➢ Create a studentCourse.
➢ Update a studentCourse.
➢ Delete a studentCourse
➢ Get studentCourse by ID
The Learning Hub Copyright
2022- All Right Reserved
Packages Specification
create or replace PACKAGE stdcourse_Package AS
PROCEDURE GetAllStdCourse;
PROCEDURE CreateStdCourse(stdidid IN number,courseid in
number,markof in number, dateof_register in date);
PROCEDURE UpdateStdCourse(SCid in number, stdidid IN
number,courseid in number,markof in number,dateof_register
in date);
PROCEDURE DeleteStdCourse(ID IN NUMBER);
PROCEDURE GetStdCourseById(ID IN NUMBER);
END stdcourse_Package;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
create or replace PACKAGE Body stdcourse_Package as
PROCEDURE GetAllStdCourse
AS
c_all sys_refcursor;
BEGIN
open c_all for
select * from stdcourse;
DBMS_SQL.RETURN_RESULT(c_all);
END GetAllStdCourse;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
PROCEDURE CreateStdCourse(stdidid IN number,courseid in
number,markof in number,dateof_register in date)
IS
BEGIN
INSERT INTO stdcourse (stdid ,courseid
,markofstd,dateofregister )
VALUES(stdidid,courseid,markof,dateof_register);
COMMIT;
END CreateStdCourse;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
PROCEDURE UpdateStdCourse(SCid in number,stdidid IN
number,courseid in number,markof in number,dateof_register
in date)
IS
BEGIN
Update stdcourse SET stdid = stdidid, courseid
=courseid,markofstd=markof,dateofregister=dateof_register
WHERE id =SCid;
COMMIT;
END UpdateStdCourse;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
PROCEDURE DeleteStdCourse(ID IN NUMBER)
IS
BEGIN
DELETE stdcourse WHERE id =ID;
COMMIT;
END
DeleteStdCourse;
The Learning Hub Copyright
2022- All Right Reserved
Packages Body
PROCEDURE GetStdCourseById(ID IN NUMBER)
AS
c_all sys_refcursor;
BEGIN
OPEN c_all FOR
SELECT * FROM stdcourse WHERE courseid =ID;
DBMS_SQL.RETURN_RESULT(c_all);
END GetStdCourseById;
END stdcourse_Package;
Exercise
✓ Create a stored procedure to display FirstName and LastName from table
student.
✓ Create a stored procedure to display student by firstName.
✓ Create a stored procedure to display student by BirthOfDate.
✓ Create a stored procedure to display a student by BirthOfDate interval.
✓ Create a stored procedure to display the students name
✓ with the highest n(3,4,…) marks
The Learning Hub Copyright
2022- All Right Reserved
In stdcourse_Package specification:
PROCEDURE GetStudentByFirstName(First_Name IN VARCHAR);
PROCEDURE GetStudentFNameAndLName;
PROCEDURE GetStudentByBirthdate(Birth_Date IN date);
PROCEDURE GetStudentBetweenInterval(DateFrom in date ,
DateTo in date);
procedure GetStudentsWithHighestMarks(NumOfStudent in
number);
The Learning Hub Copyright
2022- All Right Reserved
In stdcourse_Package Body:
PROCEDURE GetStudentByFirstName(First_Name IN VARCHAR)
AS
c_all sys_refcursor;
BEGIN
OPEN c_all for
SELECT * FROM Student WHERE FirstName=First_name;
DBMS_SQL.RETURN_RESULT(c_all);
END GetStudentByFirstName;
The Learning Hub Copyright
2022- All Right Reserved
In stdcourse_Package Body:
PROCEDURE GetStudentFNameAndLName
AS
c_all sys_refcursor;
BEGIN
OPEN c_all FOR
SELECT FirstName,LastName FROM Student;
DBMS_SQL.RETURN_RESULT(c_all);
END GetStudentFNameAndLName;
The Learning Hub Copyright
2022- All Right Reserved
In stdcourse_Package Body:
PROCEDURE GetStudentByBirthdate(Birth_Date IN date)
AS
c_all sys_refcursor;
BEGIN
OPEN c_all for
SELECT * FROM Student WHERE Trunc(DATEOFBIRTH) =
Birth_Date;
DBMS_SQL.RETURN_RESULT(c_all);
END GetStudentByBirthdate;
The Learning Hub Copyright
2022- All Right Reserved
In stdcourse_Package Body:
PROCEDURE GetStudentBetweenInterval(DateFrom in date ,
DateTo in date)
As
c_all SYS_REFCURSOR ;
Begin
open c_all for
select * from student
where dateofbirth >= datefrom and dateofbirth <= dateto;
dbms_sql.return_result(c_all);
End GetStudentBetweenInterval ;
The Learning Hub Copyright
2022- All Right Reserved
In stdcourse_Package Body:
procedure GetStudentsWithHighestMarks(NumOfStudent in
number)
As
c_all SYS_REFCURSOR;
Begin
open c_all for
select * from (select s.* from student s
inner join stdcourse sc
on [Link] = [Link]
order by [Link] desc)
where Rownum <= NumOfStudent;
Dbms_sql.return_result(c_all);
End GetStudentsWithHighestMarks;
References
1. Complete Guide to Test Automation Arnon Axelrod 2018.
2. [Link]
Overview of Database
3. [Link]
Web Application
Programming Interface
(API)
Tahaluf Training Center 2023
1 Create API Project
2 Overview of Project Architecture
3 Class Library
4 Package Installation
5
Create Domain Layer (Database First)
Create API Project
Open Visual Studio
Choose [Link] Core Web API.
Enter Project name and Solution name.
Choose Target Framework.
Note
Make sure that the "Enable OpenAPI Support" option is checked.
This option will register the Swagger service in the [Link] class which enables
you to use the Swagger tool to test the APIs.
We will go into more depth on testing tools in upcoming lectures.
The Project is created
Overview of Project
Architecture
What is [Link]?
The Program class is responsible for configuring the web host, setting up
dependency injection, and registering any middleware that the application may
need.
What is [Link]?
The [Link] file is a configuration file used to store configuration settings
like any application scope global variables, database connection strings, etc.
What is Controller?
Web API Controller is similar to [Link] Core MVC controller. It handles incoming
HTTP requests from the server and send response to the caller.
Class Library
Class libraries are the shared library concept for .NET.
They enable to componentize of useful functionality into modules that can be used by
multiple applications.
They are used as a means of loading functionality that is not known or not needed at
application startup.
Class libraries are described by the .NET Assembly file format.
Right Click on Solution Name => Add => New Project => Choose
Class Library.
Enter Project Name ([Link])
Enter Project Name ([Link])
Create dependencies
Right click on dependencies in [Link] => Add project
reference => Choose [Link] & [Link] => Ok
Create dependencies
Right click on dependencies in [Link] => Add project
reference => Choose [Link] => Ok
Package Installation
Install Packages
Tools => NuGet Package
Manager => Manage NuGet
Packages for Solution => Install
[Link]
[Link]
Install Packages
Tools => NuGet Package Manager
=> Manage NuGet Packages for
Solution => Install
[Link].
Install Packages
Tools => NuGet Package Manager
=> Manage NuGet Packages for
Solution => Install Dapper.
Install Packages
Tools => NuGet Package Manager =>
Manage NuGet Packages for Solution
=>
[Link]
Install Packages
Tools => NuGet Package Manager =>
Manage NuGet Packages for
Solution =>
[Link]
Install Packages
Tools => NuGet Package Manager =>
Manage NuGet Packages for Solution
=> Oracle. EntityFrameworkCore
Install Packages
Tools => NuGet Package
Manager => Manage NuGet
Packages for Solution =>
[Link].
Design
DB Context
The Learning Hub Copyright
2022- All Right Reserved
Database Connection
Write the following Connection String in [Link]:
"ConnectionStrings": {
"DBConnectionString": "Data
Source=(DESCRIPTION =(ADDRESS = (PROTOCOL =
TCP)(HOST = localhost)(PORT =
1521))(CONNECT_DATA =(SERVER =
DEDICATED)(SERVICE_NAME = xe))); User
Id=C##APITEST;PASSWORD=Bayan12345;Persist
Security Info=True;"
},
A DbContext instance is a session with the database used to retrieve and store
instances of your entities.
Create Common Folder
Right Click on [Link] => Add => New Folder => Common.
Right Click on [Link] => Add => New Folder => Common.
Create DbContext Class and Interface
Right Click on Common in [Link] => Add => Class => Choose
Interface => IDbContext.
Right Click on Common in [Link] => Add => Class =>
DbContext.
Note: Set Class and Interface public.
The Learning Hub Copyright
2022- All Right Reserved
IDbContext Code:
public interface IDbContext
{
DbConnection Connection { get; }
}
The Learning Hub Copyright
2022- All Right Reserved
DbContext Code:
public class DbContext: IDbContext
{
private DbConnection _connection;
private readonly IConfiguration _configuration;
public DbContext(IConfiguration configuration)
{
_configuration = configuration;
}
The Learning Hub Copyright
2022- All Right Reserved
DbContext Code:
public DbConnection Connection
{
get
{
if (_connection == null)
{
_connection = new OracleConnection
(_configuration["ConnectionStrings:
DBConnectionString"]);
_connection.Open();
}
The Learning Hub Copyright
2022- All Right Reserved
DbContext Code:
else if (_connection.State !=
[Link])
{
_connection.Open();
}
return _connection;
}
Add Services in Program
Write the following code in Configure services:
[Link]<IDBContext, DBContext>();
Create Domain Layer
(Database First)
Tools => NuGet Package Manager => Package Manager Console.
Package Manager Console => Default Project => [Link]
Scaffold-DbContext "User Id=C##Aseel;PASSWORD=Test321;DATA
SOURCE=localhost:1521/xe" [Link] -outputdir Data
References
[1]. [Link]
[2].[Link]
Overview of Database
[3]. [Link]
Web Application
Programming Interface
(API)
Tahaluf Training Center 2023
1 Overview of Onion Architecture
2 Layers of Onion Architecture
3
Benefits of Onion Architecture
Overview of Onion
Architecture
The majority of traditional architectures have inherent flaws with tight coupling and separation
of concerns.
Jeffrey Palermo proposed the Onion Architecture to give a better approach to build applications
in terms of testability, maintainability, and reliability.
Onion Architecture was created to solve the issues that 3-tier architectures face, as well as to
give a solution to common challenges.
Interfaces are used by onion architecture layers to communicate with one another.
Layers of Onion
Architecture
UI
Service
Repository
Domain
Entities
Domain Layer
The domain layer, which represents the business and behavior objects, is located in the
heart of the Onion Architecture. The goal is to have this core contain all your domain
objects.
Domain Layer
You could have domain interfaces in addition to domain objects. Without any heavy code
or dependencies, domain objects are likewise flat, as they should be.
Repository Layer
The layer's goal is to establish an abstraction layer between an application's business
logic and domain entity layers. It is a data access pattern that prompts a more loosely
coupled approach to data access.
Repository Layer
We can create a generic repository, which queries the data source for the data, maps the
data from the data source to a business entity, and maintains changes in the business
entity to the data source.
Service Layer
The layer contains interfaces for facilitating communication between the repository layer
and the user interface layer. It is also known as the "business logic layer" because it
contains the business logic for an entity.
UI
The outermost layer is this one. It may be the project for unit tests, web applications, or
web API. The Dependency injection Principle is implemented in this layer so that
applications can be developed that are loosely coupled. It communicates with the
internal layer via interfaces.
Benefits of Onion Architecture
❑ Interfaces link the layers of the onion architecture.
❑ A domain model forms the base for application architecture.
❑ There are no internal layers that are dependent on the external layers.
❑ The couplings are at the center.
❑ Architecture that is flexible, sustainable, and testable.
References
[1]. [Link]
architecture/#:~:text=Onion%20Architecture%20is%20based%20on,on%
Overview of Database
20the%20actual%20domain%20models
[2]. [Link]
us/dotnet/api/[Link]?view=efcore-
5.0
Web Application
Programming Interface
(API)
Tahaluf Training Center 2023
1 Overview of CRUD Operations
2 Repository
Overview of CRUD
Operations
CRUD is an acronym that comes from the computer programming world. It refers to
the four functions that are represented necessary to implement a persistent storage
application.
CRUD: Create, Read, Update and Delete.
Create
The create function allows users to create a new row in the database.
In the SQL relational database, the Create function is called INSERT.
Read
The read function is a search function. It allows users to retrieve and search specific
rows in the table and read their values.
In the SQL relational database, the Read function is called SELECT.
Update
The update function is used to update existing rows that exist in the database. To fully
change a record, users may have to update information in multiple fields.
In the SQL relational database, the Update function is called UPDATE.
Delete
The delete function allows users to delete rows from a database that is no longer
needed. Both Oracle HCM Cloud and SQL have a delete function that allows users to
delete one or more rows from the database.
In the SQL relational database, the Delete function is called DELETE.
Repository
Repository Layer
A repository Layer is intended to build an abstraction layer between the business logic
layer and the domain layer of an application. It is a domain approach that prompts a
more loosely coupled pattern to data access.
➢ Right Click on [Link] => Add => New Folder => Repository.
➢ Right Click on [Link] => Add => New Folder => Repository.
➢ Right Click on Repository Folder in [Link] => Add => Class => Interface =>
ICourseRepository.
➢ Right Click on Repository Folder in [Link] => Add => Class =>
CourseRepository.
➢ Note:
➢ Make sure all created classes and interfaces are public.
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => ICourseRepository add the following abstract
methods:
List<Course> GetAllCourse();
void CreateCourse(Course course);
void DeleteCourse(int id);
public void UpdateCourse(Course course);
Course GetByCourseId(int id);
In [Link] => Repository => CourseRepository => make the class inherit
the interface ICourseRepository:
public class CourseRepository : ICourseRepository
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => CourseRepository add the following :
private readonly IDBContext dBContext;
public CourseRepository(IDBContext dBContext)
{
[Link] = dBContext;
}}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => CourseRepository add the following :
public List<Course> GetAllCourse()
{
IEnumerable<Course> result =
[Link]<Course>("Course_Package.GetA
llCourses", commandType: [Link]);
return [Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => CourseRepository add the following :
public void CreateCourse(Course course)
{
var p = new DynamicParameters();
[Link]("COURSENAME", [Link],
dbType: [Link], direction:
[Link]);
[Link]("CATID", [Link],
dbType: DbType.Int32, direction:
[Link]);
The Learning Hub Copyright
2022- All Right Reserved
[Link]("image", course. Imagename, dbType:
[Link], direction: [Link]);
var result =
[Link]("Course_Package.CREATECOUR
SE", p, commandType: [Link]);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => CourseRepository add the following :
public void UpdateCourse(Course course)
{
var p = new DynamicParameters();
[Link]("ID", [Link], dbType:
DbType.Int32, direction: [Link]);
[Link]("CNAME", [Link], dbType:
[Link], direction: [Link]);
The Learning Hub Copyright
2022- All Right Reserved
[Link]("CATID", [Link], dbType:
DbType.Int32, direction: [Link]);
[Link]("image", course. Imagename, dbType:
[Link], direction: [Link]);
var result =
[Link]("Course_Package.UPDATECO
URSE", p, commandType: [Link]);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => CourseRepository add the following :
public void DeleteCourse(int id)
{
var p = new DynamicParameters();
[Link]("Id", id, dbType: DbType.Int32,
direction: [Link]);
var result =
[Link]("Course_Package.DeleteCour
se", p, commandType: [Link]);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => CourseRepository add the following :
public Course GetByCourseId(int id)
{
var p = new DynamicParameters();
[Link]("id", id, dbType: DbType.Int32,
direction: [Link]);
IEnumerable<Course> result =
[Link]<Course>("Course_Package.GetC
ourseById", p, commandType:
[Link]);
return [Link]();
}
Add Services in Program
Write the following code in Configure services:
[Link]<ICourseRepository, CourseRepository>();
➢ Right Click on Repository Folder in [Link] => Add => Class => Interface =>
IStudentRepository.
➢ Right Click on Repository Folder in [Link] => Add => Class =>
StudentRepository.
Note:
Make sure all created classes and interfaces are public.
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => IStudentRepository add the following
abstract methods:
List<Student> GetAllStudent();
void CreateStudent(Student Student);
void UpdateStudent(Student Student);
void DeleteStudent(int id);
Student GetStudentById(int id);
In [Link] => Repository => StudentRepository => make the class inherit
the interface IStudentRepository:
public class StudentRepository : IStudentRepository
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentRepository add the following :
private readonly IDBContext dBContext;
public StudentRepository(IDBContext dBContext)
{
[Link] = dBContext;
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentRepository add the following :
public List<Student> GetAllStudent()
{
IEnumerable<Student> result =
[Link]<Student>("Student_Package.Ge
tAllStudent", commandType:
[Link]);
return [Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentRepository add the following :
public void CreateStudent(Student Student)
{
var p = new DynamicParameters();
[Link]("first_name", [Link],
dbType: [Link], direction:
[Link]);
[Link]("last_name", [Link],
dbType: [Link], direction:
[Link]);
The Learning Hub Copyright
2022- All Right Reserved
[Link]("date_of_birth", [Link], dbType:
[Link], direction: [Link]);
var result =
[Link]("Student_Package.Cre
ateStudent", p, commandType:
[Link]);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentRepository add the following :
public void UpdateStudent(Student Student)
{
var p = new DynamicParameters();
[Link]("ID", [Link], dbType:
DbType.Int32, direction: [Link]);
[Link]("first_name", [Link],
dbType: [Link], direction:
[Link]);
[Link]("last_name", [Link],
dbType: [Link], direction:
[Link]);
The Learning Hub Copyright
2022- All Right Reserved
[Link]("date_of_birth", [Link], dbType:
[Link], direction: [Link]);
var result =
[Link]("Student_Package.Upda
teStudent", p, commandType:
[Link]);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentRepository add the following :
public void DeleteStudent(int id)
{
var p = new DynamicParameters();
[Link]("ID", id, dbType: DbType.Int32,
direction: [Link]);
var result =
[Link]("Student_Package.Dele
teStudent", p, commandType:
[Link]);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentRepository add the following :
public Student GetStudentById(int id)
{
var p = new DynamicParameters();
[Link]("ID", id, dbType: DbType.Int32,
direction: [Link]);
IEnumerable<Student> result =
[Link]<Student>("Student_Package.Ge
tStudentById", p, commandType:
[Link]);
return [Link]();
}
Add Services in Program
Write the following code in Configure services:
[Link]<IStudentRepository, StudentRepository>();
➢ Right Click on Repository Folder in [Link] => Add => Class => Interface =>
IStudentCourseRepository .
➢ Right Click on Repository Folder in [Link] => Add => Class =>
StudentCourseRepository.
Note:
Make sure all created classes and interfaces are public.
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => IStudentCourseRepository add the following
abstract methods:
List<Stdcourse> GetAllStudentCourse();
void CreateStudentCourse(Stdcourse
studentCourse);
void DeleteStudentCourse(int id);
void UpdateStudentCourse(Stdcourse
studentCourse);
Stdcourse GetStudentCourseById(int id);
In [Link] => Repository => StudentCourseRepository => make the class
inherit the interface IStudentCourseRepository:
public class StudentCourseRepository: IStudentCourseRepository
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentCourseRepository add the following :
private readonly IDBContext dBContext;
public StudentCourseRepository(IDBContext
dBContext)
{
[Link] = dBContext;
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentCourseRepository add the following :
public void CreateStudentCourse(StdCourse
studentCourse)
{
var p = new DynamicParameters();
[Link]("stdidid", [Link],
dbType: DbType.Int32, direction:
[Link]);
[Link]("courseid", [Link],
dbType: DbType.Int32, direction:
[Link]);
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentCourseRepository add the following :
[Link]("markof", [Link], dbType:
DbType.Int32, direction: [Link]);
[Link]("dateof_register",
[Link], dbType: [Link],
direction: [Link]);
var result =
[Link]("stdcourse_Package.Cr
eateStdCourse", p, commandType:
[Link]);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentCourseRepository add the following :
public void DeleteStudentCourse(int id)
{
var p = new DynamicParameters();
[Link]("SCID", id, dbType: DbType.Int32,
direction: [Link]);
var result =
[Link]("stdcourse_Package.De
leteStdCourse", p, commandType:
[Link]);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentCourseRepository add the following :
public List<StdCourse> GetAllStudentCourse()
{
IEnumerable<StdCourse> result =
[Link]<StdCourse>("stdcourse_Packag
[Link]", commandType:
[Link]);
return [Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentCourseRepository add the following :
public StdCourse GetStudentCourseById(int id)
{
var p = new DynamicParameters();
[Link]("SCID", id, dbType: DbType.Int32,
direction: [Link]);
IEnumerable<StdCourse> result =
[Link]<StdCourse>("stdcourse_Packag
[Link]", p, commandType:
[Link]);
return [Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentCourseRepository add the following :
public void UpdateStudentCourse(StdCourse studentCourse)
{
var p = new DynamicParameters();
[Link]("SCid", [Link], dbType:
DbType.Int32, direction: [Link]);
[Link]("stdidid", [Link], dbType:
DbType.Int32, direction: [Link]);
[Link]("courseid", [Link], dbType:
DbType.Int32, direction: [Link]);
The Learning Hub Copyright
2022- All Right Reserved
[Link]("markof", [Link], dbType:
DbType.Int32, direction: [Link]);
[Link]("dateof_register",
[Link], dbType: [Link],
direction: [Link]);
var result =
[Link]("stdcourse_Package.UpdateSt
dCourse", p, commandType: [Link]);
}
Add Services in Program
Write the following code in Configure services:
[Link]<IStudentCourseRepository, StudentCourseRepository>();
Exercise
✓ Create a function to display FirstName and LastName from table
student.
✓ Create a function to display students by firstName.
✓ Create a function to display students by BirthOfDate.
✓ Create a function to display a student by BirthOfDate interval.
✓ Create a function to display the student name with the highest
n(2,3,…) marks
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => IStudentRepository add the following :
List<Student> GetStudentByFName(string name);
List<Student> GetStudentFNameAndLName();
List<Student> GetStudentByBirthdate(DateTime
Birth_Date);
List<Student> GetStudentBetweenDate(DateTime
DateFrom ,DateTime DateTo );
List<Student> GetStudentsWithHighestMarks(int
numOfStudent);
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentRepository add the following :
public List<Student> GetStudentByFName(string name)
{
var p = new DynamicParameters();
[Link]("First_Name", name, dbType:
[Link], direction: [Link]);
IEnumerable<Student> result =
[Link]<Student>("Student_Package.Ge
tStudentByFirstName", p, commandType:
[Link]);
return [Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentRepository add the following :
public List<Student> GetStudentFNameAndLName()
{
IEnumerable<Student> result =
[Link]<Student>("Student_Package.Ge
tStudentFNameAndLName", commandType:
[Link]);
return [Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentRepository add the following :
public List<Student> GetStudentByBirthdate(DateTime
Birth_Date)
{
var p = new DynamicParameters();
[Link]("Birth_Date", Birth_Date, dbType:
[Link], direction: [Link]);
IEnumerable<Student> result =
[Link]<Student>("Student_Package.GetStudent
ByBirthdate", p, commandType: [Link]);
return [Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentRepository add the following :
public List<Student> GetStudentBetweenDate(DateTime DateFrom,
DateTime DateTo)
{
var p = new DynamicParameters();
[Link]("DateFrom", DateFrom, dbType:
[Link], direction: [Link]);
[Link]("DateTo", DateTo, dbType: [Link],
direction: [Link]);
IEnumerable<Student> result =
[Link]<Student>("Student_Package.GetStudent
BetweenInterval", p, commandType: [Link]);
return [Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentRepository add the following:
public List<Student> GetStudentsWithHighestMarks(int
numOfStudent)
{
var p = new DynamicParameters();
[Link]("NumOfStudent", numOfStudent, dbType:
DbType.Int32, direction: [Link]);
IEnumerable<Student> result =
[Link]<Student>("Student_Package.GetStudent
sWithHighestMarks",p, commandType:
[Link]);
return [Link]();
}
References
[1]. [Link]
architecture/#:~:text=Onion%20Architecture%20is%20based%20on,on%
Overview of Database
20the%20actual%20domain%20models
[2]. [Link]
us/dotnet/api/[Link]?view=efcore-
5.0
Web Application
Programming Interface
(API)
Tahaluf Training Center 2023
1 Overview Of Service
2 Create Service
Overview Of Service
The services layer is used to communicate between the Repository layer and UI.
Users can call it a business or domain layer since it holds the business logic for an
entity.
Service classes in the service layer are designed to do two things:
1. Query one or more Repositories.
2. Implement their own functionality, which is useful when functionality deals with
more than one business object.
Create Service
Right Click on [Link] => Add => New Folder => Service.
Right Click on [Link] => Add => New Folder => Service.
Right Click on Services in [Link] => Add => Class => ICourseService.
Right Click on Services in [Link] => Add => Class => CourseService.
Note:
Make sure all created classes and interfaces are public.
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => ICourseService add the following abstract methods:
List<Course> GetAllCourse();
void CreateCourse(Course course);
void DeleteCourse(int id);
public void UpdateCourse(Course course);
Course GetByCourseId(int id);
In [Link] => Service => Course Service => make the class inherit the
interface ICourseService:
public class CourseService : ICourseService
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => Course Service add the following :
private readonly ICourseRepository courseRepository;
public CourseService(ICourseRepository
courseRepository)
{
[Link] = courseRepository;
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => Course Service add the following :
public List<Course> GetAllCourse()
{
return [Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => Course Service add the following :
public void CreateCourse(Course course)
{
[Link](course);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => Course Service add the following :
public void UpdateCourse(Course course)
{
[Link](course);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => Course Service add the following :
public void DeleteCourse(int id)
{
[Link](id);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => Course Service add the following :
public Course GetByCourseId(int id)
{
return [Link](id);
}
Add Services in Program
Write the following code in Configure services:
[Link]<ICourseService, CourseService>();
➢ Right Click on Repository Folder in [Link] => Add => Class => Interface =>
IStudentService.
➢ Right Click on Repository Folder in [Link] => Add => Class =>
StudentService.
Note:
Make sure all created classes and interfaces are public.
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => IStudentService add the following abstract methods:
List<Student> GetAllStudent();
void CreateStudent(Student Student);
void UpdateStudent(Student Student);
void DeleteStudent(int id);
Student GetStudentById(int id);
In [Link] => Service => StudentService => make the class inherit the
interface IStudentService:
public class StudentService : IStudentService
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentService add the following :
private readonly IStudentRepository
_studentRepository;
public StudentService(IStudentRepository
studentRepository)
{
_studentRepository = studentRepository;
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentService add the following :
public List<Student> GetAllStudent()
{
return _studentRepository.GetAllStudent();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentService add the following :
public void CreateStudent(Student Student)
{
_studentRepository.CreateStudent(Student);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentService add the following :
public void UpdateStudent(Student Student)
{
_studentRepository.UpdateStudent(Student);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentService add the following :
public void DeleteStudent(int id)
{
_studentRepository.DeleteStudent(id);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentService add the following :
public Student GetStudentById(int id)
{
return
_studentRepository.GetStudentById(id);
}
Add Services in Program
Write the following code in Configure services:
[Link]<IStudentService, StudentService>();
➢ Right Click on Repository Folder in [Link] => Add => Class => Interface =>
IStudentCourseService.
➢ Right Click on Repository Folder in [Link] => Add => Class =>
StudentCourseService.
Note:
Make sure all created classes and interfaces are public.
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => IStudentCourseService add the following abstract
methods:
List<Stdcourse> GetAllStudentCourse();
void CreateStudentCourse(Stdcourse
studentCourse);
void DeleteStudentCourse(int id);
void UpdateStudentCourse(Stdcourse
studentCourse);
Stdcourse GetStudentCourseById(int id);
In [Link] => Service => StudentCourseService => make the class inherit
the interface IStudentCourseService:
public class StudentCourseService: IStudentCourseService
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentCourseService add the following :
private readonly IStudentCourseRepository
_studentCourseRepository;
public
StudentCourseService(IStudentCourseRepository
studentCourseRepository)
{
_studentCourseRepository =
studentCourseRepository;
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentCourseService add the following :
public void CreateStudentCourse(Stdcourse
studentCourse)
{
_studentCourseRepository.CreateStudentCourse(studentC
ourse);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentCourseService add the following :
public void DeleteStudentCourse(int id)
{
_studentCourseRepository.DeleteStudentCourse(id);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentCourseService add the following :
public List<Stdcourse> GetAllStudentCourse()
{
return
_studentCourseRepository.GetAllStudentCourse();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentCourseService add the following :
public List<Stdcourse> GetAllStudentCourse()
{
return
_studentCourseRepository.GetAllStudentCourse();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentCourseService add the following :
public void UpdateStudentCourse(Stdcourse
studentCourse)
{
_studentCourseRepository.UpdateStudentCourse(studentCou
rse);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentCourseService add the following :
public Stdcourse GetStudentCourseById(int id)
{
return
_studentCourseRepository.GetStudentCourseById(id);
}
Add Services in Program
Write the following code in Configure services:
[Link]<IStudentCourseService, StudentCourseService>();
Exercise
✓ Create a function to display FirstName and LastName from table
student.
✓ Create a function to display students by firstName.
✓ Create a function to display students by BirthOfDate.
✓ Create a function to display a student by BirthOfDate interval.
✓ Create a function to display the student name with the highest 3
marks
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => IStudentService add the following :
List<Student> GetStudentByFName(string name);
List<Student> GetStudentFNameAndLName();
List<Student> GetStudentByBirthdate(DateTime
Birth_Date);
List<Student> GetStudentBetweenDate(DateTime
DateFrom, DateTime DateTo);
List<Student> GetStudentsWithHighestMarks(int
numOfStudent);
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentService add the following :
public List<Student> GetStudentByFName(string name)
{
return
_studentRepository.GetStudentByFName(name);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentService add the following :
public List<Student> GetStudentFNameAndLName()
{
return
_studentRepository.GetStudentFNameAndLName();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentService add the following :
public List<Student> GetStudentByBirthdate(DateTime
Birth_Date)
{
return
_studentRepository.GetStudentByBirthdate(Birth_Date);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentService add the following :
public List<Student> GetStudentBetweenDate(DateTime
DateFrom, DateTime DateTo)
{
return
_studentRepository.GetStudentBetweenDate(DateFrom,
DateTo);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentService add the following :
public List<Student> GetStudentsWithHighestMarks(int
numOfStudent)
{
return
_studentRepository.GetStudentsWithHighestMarks(numOfStu
dent);
}
References
[1]. [Link]
architecture/#:~:text=Onion%20Architecture%20is%20based%20on,on%
Overview of Database
20the%20actual%20domain%20models
[2]. [Link]
us/dotnet/api/[Link]?view=efcore-
5.0
Web Application
Programming Interface
(API)
Tahaluf Training Center 2023
1 API Testing Tools (Postman)
2 Overview Of HTTP Verbs
3 Overview Of HTTP Status Code
4 Controller
5 Upload Image
API Testing Tools
(Postman)
The most popular API testing tools
Postman Swagger JMeter SoapUI
When we created the project, we checked the option "Enable OpenAPI Support" which
registers the Swagger service in the [Link] and make it the default tool for testing. But in
this course, we will use postman as an API testing tool.
Of course, you can choose your favorite tool for testing your APIs
Postman is an Application Programming Interface (API) development tool used to build, test,
and modify APIs.
Postman can make different types of HTTP methods (GET, PUT, PATCH, POST), convert the API
to code for various languages(like Python, and JavaScript), saving environments for later use.
Open the following link: [Link]
Overview Of HTTP Verbs
REST APIs enable to development of any kind of web application having all CRUD
operations (Create, Retrieve, Update, Delete).
REST guidelines suggest using specific HTTP verbs on a particular type of call made to the
server.
HTTP GET
Use GET requests to retrieve resource represent information only and not to update it in any way.
As GET requests do not update the state of the resource, these are said to be safe methods.
HTTP POST
Use POST APIs to create new resources, When talking strictly in terms of REST, POST verbs are used
to create a new resource into the collection of resources.
HTTP PUT
Use PUT APIs primarily to modify existing resource (if the resource does not exist, then API may
decide to create a new resource or not).
HTTP DELETE
DELETE APIs are used to delete resources (identified by the Request URI).
Overview Of HTTP
Status Code
Controller
Web API Controller handles incoming HTTP methods requests and sends a response to the caller.
Web API controller class can be created in the Controllers folder or any other folder in the
project's root folder.
Right Click on Controllers => Add => Controller => Choose API Controller –
Empty => CourseController.
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => CourseController add the following :
private readonly ICourseService courseService;
public CourseController(ICourseService
courseService)
{
[Link] = courseService;
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => CourseController add the following :
[HttpGet]
public List<Course> GetAllCourse()
{
return [Link]();
}
In Postman:
1. In URL add => Https://LocalHost:PortNumber/Api/ControllerName/[RouteName]/[Parameters]
2. Select The method => (Get)
3. Send the request
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => CourseController add the following :
[HttpPost]
public void CreateCourse(Course course)
{
[Link](course);
}
In Postman:
1. In URL add => Https://LocalHost:PortNumber/Api/ControllerName/[RouteName]/[Parameters]
2. Select The method => (Post)
3. Choose Body => raw => JSON => then add the course data as JSON object.
4. Send the request
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => CourseController add the following :
[HttpPut]
public void UpdateCourse(Course course)
{
[Link](course);
}
In Postman:
1. In URL add => Https://LocalHost:PortNumber/Api/ControllerName/[RouteName]/[Parameters]
2. Select The method => (Put)
3. Choose Body => raw => JSON => then add the course data as JSON object.
4. Send the request
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => CourseController add the following :
[HttpDelete]
[Route("delete/{id}")]
public void DeleteCourse(int id)
{
[Link](id);
}
In Postman:
1. In URL add => Https://LocalHost:PortNumber/Api/ControllerName/[RouteName]/[Parameters]
2. Select The method => (Delete)
1. Send the request
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => CourseController add the following :
[HttpGet]
[Route("getByCourseId/{id}")]
public Course GetByCourseId(int id)
{
return [Link](id);
}
In Postman:
1. In URL add => Https://LocalHost:PortNumber/Api/ControllerName/[RouteName]/[Parameters]
2. Select The method => (Get)
1. Send the request
Right Click on Controllers => Add => Controller => Choose API Controller –
Empty => StudentController.
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentController add the following :
private readonly IStudentService _studentService;
public StudentController(IStudentService
Istdservice)
{
this._studentService = Istdservice;
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentController add the following :
[HttpGet]
public List<Student> GetAllStudent()
{
return _studentService.GetAllStudent();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentController add the following :
[HttpPost]
public void CreateStudent(Student Student)
{
_studentService.CreateStudent(Student);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentController add the following :
[HttpPut]
public void UpdateStudent(Student Student)
{
_studentService.UpdateStudent(Student);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentController add the following :
[HttpDelete]
[Route("delete/{id}")]
public void DeleteStudent(int id)
{
_studentService.DeleteStudent(id);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentController add the following :
[HttpGet]
[Route("getByStudentId/{id}")]
public Student GetStudentById(int id)
{
return _studentService.GetStudentById(id);
}
Right Click on Controllers => Add => Controller => Choose API Controller –
Empty => StudentCourseController.
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentCourseController add the following :
private readonly IStudentCourseService
_studentCourseService;
public
StudentCourseController(IStudentCourseService
studentCourseService)
{
_studentCourseService =
studentCourseService;
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentCourseController add the following :
[HttpGet]
public List<Stdcourse> GetAllStudentCourse()
{
return
_studentCourseService.GetAllStudentCourse();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentCourseController add the following :
[HttpPost]
public void CreateStudentCourse(Stdcourse
studentCourse)
{
_studentCourseService.CreateStudentCourse(studentCourse
);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentCourseController add the following :
[HttpPut]
public void UpdateStudentCourse(Stdcourse
studentCourse)
{
_studentCourseService.UpdateStudentCourse(studentCourse
);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentCourseController add the following :
[HttpDelete]
[Route("delete/{id}")]
public void DeleteStudentCourse(int id)
{
_studentCourseService.DeleteStudentCourse(id);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentCourseController add the following :
[HttpGet]
[Route("getStudentCourseById/{id}")]
public Stdcourse GetStudentCourseById(int id)
{
return
_studentCourseService.GetStudentCourseById(id);
}
Exercise
✓ Create a function to display FirstName and LastName from table
student.
✓ Create a function to display students by firstName.
✓ Create a function to display students by BirthOfDate.
✓ Create a function to display a student by BirthOfDate interval.
✓ Create a function to display the student name with the highest
n(2,3,…) marks
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentController add the following :
[HttpGet]
[Route("GetStduentByFName/{name}")]
public List<Student> GetStudentByFName(string
name)
{
return
_studentService.GetStudentByFName(name);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentController add the following :
[HttpGet]
[Route("GetStduentFNameAndLName")]
public List<Student> GetStudentFNameAndLName()
{
return
_studentService.GetStudentFNameAndLName();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentController add the following :
[HttpGet]
[Route("GetStudentByBirthdate/{Birth_Date}")]
public List<Student>
GetStudentByBirthdate(DateTime Birth_Date)
{
return
_studentService.GetStudentByBirthdate(Birth_Date);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentController add the following :
[HttpGet]
[Route("GetStudentBetweenDate/{DateFrom}/{DateTo}")]
public List<Student>
GetStudentBetweenDate(DateTime DateFrom, DateTime
DateTo)
{
return
_studentService.GetStudentBetweenDate(DateFrom,
DateTo);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => StudentController add the following :
[HttpGet]
[Route("GetStudentsWithHighestMarks/{numOfStudent}")]
public List<Student>
GetStudentsWithHighestMarks(int numOfStudent)
{
return
_studentService.GetStudentsWithHighestMarks(numOfStuden
t);
}
Upload Image
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Right Click => Add New Folder (Images):
Create upload image function in Course Controller:
[Route("uploadImage")]
[HttpPost]
public Course UploadIMage()
{
var file = [Link][0];
var fileName = [Link]().ToString() +
"_" + [Link];
var fullPath = [Link]("Images",
fileName);
The Learning Hub Copyright
2022- All Right Reserved
using (var stream = new FileStream(fullPath,
[Link]))
{
[Link](stream);
}
Course item = new Course();
[Link] = fileName;
return item;
}
References
[1]. [Link]
architecture/#:~:text=Onion%20Architecture%20is%20based%20on,on%
Overview of Database
20the%20actual%20domain%20models
[2]. [Link]
us/dotnet/api/[Link]?view=efcore-
5.0
Web Application
Programming Interface
(API)
Tahaluf Training Center 2023
1 Overview of Data Transfer Object (DTOs)
2 Overview of Data Filtering
3 Create a Filter using DTO
Overview of Data Transfer
Object (DTOs)
Data Transfer Object or DTO is a simple object that is used to transfer data between
different parts of a system, such as between client and server, or between different
layers of an application. DTOs are designed to carry data without any business logic.
They are often used to encapsulate the data in a way that makes it easy to serialize and
deserialize, which is particularly useful for sending data over a network or for storing
data in a database.
How to Use DTOs?
DTOs are created as POJOs. They are flat data structures that contain no business or data
logic.
The image illustrates the interaction between the components:
RoleName
When to Use DTOs?
DTOs used in systems with remote calls, because they help to reduce the number of them
and when the domain or data access model is composed of many various objects, and the
presentation model needs all data at once or even reduces roundtrip between server and
client.
When to Use DTOs?
DTOs used to build different views from our domain or data access models and allow to
create other representations of the same domain, but optimizing them to the clients' needs
without affecting our domain design.
Overview of Data Filtering
Data filtering can refer to a wide range of solutions or strategies for refining data sets.
The data sets are refined into simply what a user needs, without including other data
that can be irrelevant, repetitive, or even sensitive.
Different types of data filters can be used to amend query, reports, results, or other kinds
of information results.
Create a Filter using
DTO
The Learning Hub Copyright
2022- All Right Reserved
In stdcourse_Package package specification Add a SearchStudentAndCourse Stored
Procedure:
PROCEDURE SearchStudentAndCourse(cName in varchar , sName in
varchar , DateFrom in date , DateTo in date);
The Learning Hub Copyright
2022- All Right Reserved
In stdcourse_Package package body Add a SearchStudentAndCourse Stored Procedure:
PROCEDURE SearchStudentAndCourse(cName in varchar , sName in
varchar , DateFrom in date , DateTo in date)
As
Get_Cur SYS_REFCURSOR;
Begin
open Get_Cur for
select [Link] , [Link] , [Link] , [Link]
from Student s
inner join stdCourse sc
The Learning Hub Copyright
2022- All Right Reserved
on [Link] = [Link]
inner join course c
on [Link] = [Link]
where (upper([Link]) like '%'||upper(sName) ||'%') -- null
And ( upper( [Link]) like '%' || upper( cname) || '%') -- S
And (DateFrom is null or DateTo is null or [Link] between
DateFrom and DateTo);
dbms_sql.return_result(Get_Cur);
End SearchStudentAndCourse;
Create a DTOs
Right Click on [Link] => Add New Folder => DTO.
Right Click on DTO => Add Class => Search.
The Learning Hub Copyright
2022- All Right Reserved
Search DTO Code:
public class Search
{
public string? Firstname { get; set; }
public string? Lastname { get; set; }
public decimal? Markofstd { get; set; }
public string? Coursename { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => IStudentCourseRepository add the following abstract
method:
List<Search> SearcheStudenCourse(Search search);
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Repository => StudentCourseRepository add the following method:
public List<Search> SearcheStudenCourse(Search search)
{
var p = new DynamicParameters();
[Link]("sName", [Link], dbType:
[Link], direction: [Link]);
[Link]("DateFrom", [Link], dbType:
[Link], direction: [Link]);
[Link]("DateTo", [Link], dbType:
[Link], direction: [Link]);
The Learning Hub Copyright
2022- All Right Reserved
[Link]("cName", [Link], dbType:
[Link], direction: [Link]);
var result =
[Link]<Search>("stdcourse_Package.Se
archStudentAndCourse", p, commandType:
[Link]);
return [Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => IStudentCourseService add the following abstract methods:
List<Search> SearcheStudenCourse(Search search);
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => StudentCourseService add the following method:
public List<Search> SearcheStudenCourse(Search search)
{
return
_studentCourseRepository.SearcheStudenCourse(search);
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controler => StudentCourseController add the following method:
[HttpPost]
[Route("SearchStudenCourse")]
public List<Search> SearcheStudenCourse(Search
search)
{
return
_studentCourseService.SearcheStudenCourse(search);
}
Exercise
Create a function to retrieve the total number of students in each course.
References
[1]. [Link]
architecture/#:~:text=Onion%20Architecture%20is%20based%20on,on%
Overview of Database
20the%20actual%20domain%20models
[2]. [Link]
us/dotnet/api/[Link]?view=efcore-
5.0
Web Application
Programming Interface
(API)
Tahaluf Training Center 2023
1 Overview of External API
2 The Differences Between external API and Internal API
3 Weather external API
4 Getting Data from Multiple Tables in Web API
Overview of External API
The main characteristics of external API activity are the Ability to fetch data in a JSON format
file to a 3rd party restful API endpoint.
Ability to receive and save a JSON response back, map it to output tables, and pass it
downstream to other workflow activities.
Limitations of External API:
1. 5MB HTTP response data size limit.
2. HTTP redirects are not allowed.
3. Request timeout is 1 minute.
4. Non-HTTPS URLs are rejected.
The Differences Between
External API and Internal API
Internal APIs VS External APIs
One of the most important things that you should consider in both your interface architecture
and API business strategy is the difference between internal and external API. An interface can
be described as internal and external depending on whether its target is for in-house or
external developers.
Internal APIs VS External APIs
External API Is an API designed for access by a larger population as well as web developers.
This implies that an external API can be easily used by developers inside the organization (that
published the API) and any other developers from the outside who desires to register into the
interface.
Weather external API
Overview of Weather external API
OpenWeather provides historical, current and forecasted weather data via light-speed APIs.
Before doing anything, you need an API key. Go to the Signup page.
Overview of Weather external API
The API key will send to you via email and may be found on the API keys page (under your
account).
In order to display the current weather for any city using the weather API on
[Link]
Install Packages
Tools => NuGet Package
Manager => Manage NuGet
Packages for Solution => Install
[Link]
The Learning Hub Copyright
2022- All Right Reserved
Create Weather controller:
[HttpGet("weather/{city}")]
public async Task<Weather> City(string city)
{
using (var client = new HttpClient())
{
var response = await
[Link]($"[Link]
5/weather?q={city}&appid=511ba00e6b1fdebcf7456541e7a163
90");
The Learning Hub Copyright
2022- All Right Reserved
var stringResult = await
[Link]();
var weatherResult =
[Link]<Weather>(stringResult);
return weatherResult;
}
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => DTO => Create a class for Weather:
namespace [Link]
{
public class Main
{
public string Temp { get; set; }
public string humidity { get; set; }
}
public class Wind
{
public string speed { get; set; }
}
The Learning Hub Copyright
2022- All Right Reserved
public class Weather
{
public Main main { get; set; }
public Wind wind { get; set; }
public string name { get; set; }
public string timeZone { get; set; }
}
}
Getting Data from Multiple
Tables
The Learning Hub Copyright
2022- All Right Reserved
To retrieve each category and their courses:
In Course_Package Create GetAllCategoryCourse Proceadure:
create or replace PACKAGE Course_Package AS
PROCEDURE GetAllCategoryCourse;
END Course_Package;
The Learning Hub Copyright
2022- All Right Reserved
create or replace PACKAGE Body Course_Package
as
PROCEDURE GetAllCategoryCourse
AS
c_all sys_refcursor;
BEGIN
OPEN c_all FOR
SELECT [Link], [Link] , [Link] ,
The Learning Hub Copyright
2022- All Right Reserved
[Link]
FROM Course C
INNER JOIN category cat
ON [Link] = [Link];
DBMS_SQL.RETURN_RESULT(c_all);
END GetAllCategoryCourse;
END Course_Package;
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Reopsitory => ICourseRepository => Create GetAllCategoryCourse:
Task<List<Category>> GetAllCategoryCourse();
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Reopsitory => CourseRepository => Create GetAllCategoryCourse:
public async Task<List<Category>> GetAllCategoryCourse()
{
var p = new DynamicParameters();
var result = await
[Link]<Category, Course,
Category>("Course_Package.GetAllCategoryCourse",
(Category, course) =>
{
[Link](course);
return Category;
},
The Learning Hub Copyright
2022- All Right Reserved
splitOn: "Courseid",
param: null,
commandType: [Link]
);
var results = [Link](p =>
[Link]).Select(g =>
{
The Learning Hub Copyright
2022- All Right Reserved
var groupedPost = [Link]();
[Link] = [Link](p =>
[Link]()).ToList();
return groupedPost;
});
return [Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => ICourseService => Create GetAllCategoryCourse:
Task<List<Category>> GetAllCategoryCourse();
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Service => CourseService => Create GetAllCategoryCourse:
public Task<List<Category>> GetAllCategoryCourse()
{
return
[Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
In [Link] => Controller => CourseController => Create GetAllCategoryCourse:
[HttpGet]
[Route("GetAllCategoryCourse")]
public Task<List<Category>>
GetAllCategoryCourse()
{
return [Link]();
}
The Result on postman:
References
[1]. [Link]
architecture/#:~:text=Onion%20Architecture%20is%20based%20on,on%
Overview of Database
20the%20actual%20domain%20models
[2]. [Link]
us/dotnet/api/[Link]?view=efcore-
5.0
Web Application
Programming Interface
(API)
Tahaluf Training Center 2023
1 Authentication VS Authorization
2 JSON Web Token (JWT)
3 Create LOGIN using JWT Token
Authentication
VS
Authorization
Authentication VS Authorization
Authentication verifies the user before allowing them access, and authorization determines
what they can do once the system has granted them access .
Verifying that someone or anything is who they claim they are is done through the
authentication procedure. To secure access to a program or its data, technology systems
normally require some type of authentication. For example, you often need to enter your login
and password in order to access a website or service online. Then, in the background, it checks
your entered login and password to a record in its database. The system decides you are a valid
user and provides you access if the data you provided matches.
The security procedure known as authorization establishes a user's or service's level of access.
In technology, authorisation is used to provide users or services permission to access certain
data or perform specific tasks.
JSON Web Token (JWT)
What is JSON Web Token?
JSON Web Token (JWT) is an open standard (RFC 7519) that specifies a condensed and
independent method for sending information securely between parties as a JSON object. Due
to its digital signature, this information can be verified and trusted.
Uses of JSON Web Tokens:
1. Authorization: The most typical application of JWT is for authorization. The JWT will be
included in each request once the user logs in, enabling access to the routes, services, and
resources that are authorized with that token
Uses of JSON Web Tokens:
2. Information Exchange: Sending information securely between parties is made possible by
JSON Web Tokens. You can be certain that the senders are who they claim to be since JWTs can
be signed. You may also confirm that the content hasn't been altered because the signature is
created using the header and the payload.
JSON Web Token structure
1. Header
2. Payload
3. Signature
The three components of a JSON Web Token are separated by dots (.) like the following:
[Link]
Header
The type of the token, which is JWT, and
the signature algorithm being used, such
as HMAC SHA256 or RSA, are both
typically component included in the
header.
Payload
The payload is the second part of the token,
which contains the claims. Claims are
statements about a subject (usually the user)
and additional information.
Signature
The encoded payload, encoded header, a secret, and the algorithm mentioned in the header
must all be combined to generate the signature portion.
When a token is signed with a private key, it may also confirm that the sender of the JWT is wh
o they claim to be. The signature is used to ensure that the message wasn't altered along the
way.
JWT
How do JSON Web
Tokens work
Create LOGIN using JWT
Token
Tools => NuGet Package Manager => Manage NuGet Packages for Solution =>
[Link]
Tools => NuGet Package Manager => Manage NuGet Packages for Solution =>
[Link]
The Learning Hub Copyright
2022- All Right Reserved
Create Login package on SQL developer :
create or replace PACKAGE Login_Package
AS
PROCEDURE User_Login(User_NAME IN VARCHAR,PASS IN VARCHAR);
END Login_Package;
The Learning Hub Copyright
2022- All Right Reserved
create or replace PACKAGE body Login_Package
AS
PROCEDURE User_Login(User_NAME IN VARCHAR,PASS IN VARCHAR)
AS
c_all SYS_REFCURSOR;
BEGIN
open c_all for
The Learning Hub Copyright
2022- All Right Reserved
SELECT USERNAME,roleid FROM LOGIN WHERE USERNAME=User_NAME
AND PASSWORD=PASS;
DBMS_SQL.RETURN_RESULT(c_all);
end User_Login;
END Login_Package;
The Learning Hub Copyright
2022- All Right Reserved
Program => ConfigureServices => Add the following:
[Link](opt => {
[Link] =
[Link];
[Link] =
[Link];
})
.AddJwtBearer(options =>
{
[Link] = new
TokenValidationParameters
The Learning Hub Copyright
2022- All Right Reserved
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new
SymmetricSecurityKey([Link]("superSecre
tKey@345"))
};
});
The Learning Hub Copyright
2022- All Right Reserved
Program => Add the following:
[Link]();
➢ Right Click on Repository Folder in [Link] => Add => Class => Interface =>
ICourseRepository.
➢ Right Click on Repository Folder in [Link] => Add => Class =>
CourseRepository.
➢ Note:
➢ Make sure all created classes and interfaces are public.
The Learning Hub Copyright
2022- All Right Reserved
[Link] => Repository => Create [Link]
public interface IJWTRepository
{
Login Auth(Login login);
}
In [Link] => Repository => JWTRepository => make the class inherit the
interface IJWTRepository :
public class JWTRepository: IJWTRepository
The Learning Hub Copyright
2022- All Right Reserved
[Link] => Repositry => Create [Link]
private readonly IDBContext dBContext;
public JWTRepository(IDBContext dBContext)
{
[Link] = dBContext;
}
The Learning Hub Copyright
2022- All Right Reserved
[Link] => Repositry => Create [Link]
public Login Auth(Login login)
{
var p = new DynamicParameters();
[Link]("User_NAME", [Link], dbType:
[Link], direction: [Link]);
[Link]("PASS", [Link], dbType:
[Link], direction: [Link]);
IEnumerable<Login> result =
[Link]<Login>("Login_Package.User_Login",
p, commandType: [Link]);
return [Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
[Link] => Service => Create [Link]
public interface IJWTService
{
string Auth(Login login);
}
In [Link] => Service => JWTService => make the class inherit the
interface IJWTService :
public class JWTService: IJWTService
The Learning Hub Copyright
2022- All Right Reserved
[Link] => Service => Create [Link]
private readonly IJWTRepository reposiytory;
public JWTService(IJWTRepository reposiytory)
{
[Link] = reposiytory;
}
The Learning Hub Copyright
2022- All Right Reserved
public string Auth(Login login)
{
var result = [Link](login);
if (result == null)
{
return null;
}
else
{
The Learning Hub Copyright
2022- All Right Reserved
var secretKey = new
SymmetricSecurityKey([Link]("superSecre
tKey@345"));
var signinCredentials = new
SigningCredentials(secretKey,
SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>
The Learning Hub Copyright
2022- All Right Reserved
{
new Claim([Link], [Link]),
new Claim([Link], [Link]())
};
var tokeOptions = new JwtSecurityToken(
claims: claims,
expires:
[Link](24),
The Learning Hub Copyright
2022- All Right Reserved
signingCredentials: signinCredentials
);
var tokenString = new
JwtSecurityTokenHandler().WriteToken(tokeOptions);
return tokenString;
}
}
Note:
JWT supports several signing algorithms such as HMAC with SHA-256, HMAC with SHA-384,
HMAC with SHA-512, and RSA with SHA-256.
The size of the secret key used in a JWT (JSON Web Token) depends on the algorithm being
used to sign the token.
For example, if HMAC with SHA-256 is used, the secret key should be at least 256 bits (32
bytes) long. For RSA algorithms, the key size should be at least 2048 bits.
The Learning Hub Copyright
2022- All Right Reserved
In Program:
[Link]<IJWTRepository,
JWTRepository>();
[Link]<IJWTService, JWTService>();
The Learning Hub Copyright
2022- All Right Reserved
[Link] => Controller => Create [Link]
private readonly IJWTService jwtservice;
public JWTController(IJWTService jwtservice)
{
[Link] = jwtservice;
}
[HttpPost]
public IActionResult Auth([FromBody] Login login)
{
The Learning Hub Copyright
2022- All Right Reserved
var token = [Link](login);
if (token == null)
{
return Unauthorized();
}
else
{
return Ok(token);
}
}
Authorization
[Authorize] VS [AllowAnonymous] attributes:
To control the authorization in [Link] Core In its most basic form, applying the [Authorize] or
[AllowAnonymous] attribute to a controller or action, use the [Authorize] to limit access to that
component to authenticated users and the [AllowAnonymous] attribute to allow access to that
component to all users
[Authorize] VS [AllowAnonymous] attributes:
To control the authorization in [Link] Core In its most basic form, applying the [Authorize] or
[AllowAnonymous] attribute to a controller or action, use the [Authorize] to limit access to that
component to authenticated users and the [AllowAnonymous] attribute to allow access to that
component to all users
The Learning Hub Copyright
2022- All Right Reserved
In the Course Controller:
The Learning Hub Copyright
2022- All Right Reserved
In the Course Controller:
The Learning Hub Copyright
2022- All Right Reserved
To create role-based authorization:
In the controllers folder, create a new class called RequiresClaimAttribute
public class CheckClaimsAttribute : Attribute,
IAuthorizationFilter
{
private readonly string _claimName;
private readonly string _claimValue;
public CheckClaimsAttribute(string
claimName, string claimValue)
{
_claimName = claimName;
_claimValue = claimValue;
}
The Learning Hub Copyright
2022- All Right Reserved
public void
OnAuthorization(AuthorizationFilterContext context)
{
if
()
{
[Link] = new ForbidResult();
}
}
}
The Learning Hub Copyright
2022- All Right Reserved
In the Course Controller:
References
[1]. [Link]
architecture/#:~:text=Onion%20Architecture%20is%20based%20on,on%
Overview of Database
20the%20actual%20domain%20models
[2]. [Link]
us/dotnet/api/[Link]?view=efcore-
5.0
Web Application
Programming Interface
(API)
Tahaluf Training Center 2023
1 Authentication VS Authorization
2 JSON Web Token (JWT)
3 Create LOGIN using JWT Token
Authentication
VS
Authorization
Authentication VS Authorization
Authentication verifies the user before allowing them access, and authorization determines
what they can do once the system has granted them access .
Verifying that someone or anything is who they claim they are is done through the
authentication procedure. To secure access to a program or its data, technology systems
normally require some type of authentication. For example, you often need to enter your login
and password in order to access a website or service online. Then, in the background, it checks
your entered login and password to a record in its database. The system decides you are a valid
user and provides you access if the data you provided matches.
The security procedure known as authorization establishes a user's or service's level of access.
In technology, authorisation is used to provide users or services permission to access certain
data or perform specific tasks.
JSON Web Token (JWT)
What is JSON Web Token?
JSON Web Token (JWT) is an open standard (RFC 7519) that specifies a condensed and
independent method for sending information securely between parties as a JSON object. Due
to its digital signature, this information can be verified and trusted.
Uses of JSON Web Tokens:
1. Authorization: The most typical application of JWT is for authorization. The JWT will be
included in each request once the user logs in, enabling access to the routes, services, and
resources that are authorized with that token
Uses of JSON Web Tokens:
2. Information Exchange: Sending information securely between parties is made possible by
JSON Web Tokens. You can be certain that the senders are who they claim to be since JWTs can
be signed. You may also confirm that the content hasn't been altered because the signature is
created using the header and the payload.
JSON Web Token structure
1. Header
2. Payload
3. Signature
The three components of a JSON Web Token are separated by dots (.) like the following:
[Link]
Header
The type of the token, which is JWT, and
the signature algorithm being used, such
as HMAC SHA256 or RSA, are both
typically component included in the
header.
Payload
The payload is the second part of the token,
which contains the claims. Claims are
statements about a subject (usually the user)
and additional information.
Signature
The encoded payload, encoded header, a secret, and the algorithm mentioned in the header
must all be combined to generate the signature portion.
When a token is signed with a private key, it may also confirm that the sender of the JWT is wh
o they claim to be. The signature is used to ensure that the message wasn't altered along the
way.
JWT
How do JSON Web
Tokens work
Create LOGIN using JWT
Token
Tools => NuGet Package Manager => Manage NuGet Packages for Solution =>
[Link]
Tools => NuGet Package Manager => Manage NuGet Packages for Solution =>
[Link]
The Learning Hub Copyright
2022- All Right Reserved
Create Login package on SQL developer :
create or replace PACKAGE Login_Package
AS
PROCEDURE User_Login(User_NAME IN VARCHAR,PASS IN VARCHAR);
END Login_Package;
The Learning Hub Copyright
2022- All Right Reserved
create or replace PACKAGE body Login_Package
AS
PROCEDURE User_Login(User_NAME IN VARCHAR,PASS IN VARCHAR)
AS
c_all SYS_REFCURSOR;
BEGIN
open c_all for
The Learning Hub Copyright
2022- All Right Reserved
SELECT USERNAME,roleid FROM LOGIN WHERE USERNAME=User_NAME
AND PASSWORD=PASS;
DBMS_SQL.RETURN_RESULT(c_all);
end User_Login;
END Login_Package;
The Learning Hub Copyright
2022- All Right Reserved
Program => ConfigureServices => Add the following:
[Link](opt => {
[Link] =
[Link];
[Link] =
[Link];
})
.AddJwtBearer(options =>
{
[Link] = new
TokenValidationParameters
The Learning Hub Copyright
2022- All Right Reserved
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new
SymmetricSecurityKey([Link]("superSecre
tKey@345"))
};
});
The Learning Hub Copyright
2022- All Right Reserved
Program => Add the following:
[Link]();
➢ Right Click on Repository Folder in [Link] => Add => Class => Interface =>
ICourseRepository.
➢ Right Click on Repository Folder in [Link] => Add => Class =>
CourseRepository.
➢ Note:
➢ Make sure all created classes and interfaces are public.
The Learning Hub Copyright
2022- All Right Reserved
[Link] => Repository => Create [Link]
public interface IJWTRepository
{
Login Auth(Login login);
}
In [Link] => Repository => JWTRepository => make the class inherit the
interface IJWTRepository :
public class JWTRepository: IJWTRepository
The Learning Hub Copyright
2022- All Right Reserved
[Link] => Repositry => Create [Link]
private readonly IDBContext dBContext;
public JWTRepository(IDBContext dBContext)
{
[Link] = dBContext;
}
The Learning Hub Copyright
2022- All Right Reserved
[Link] => Repositry => Create [Link]
public Login Auth(Login login)
{
var p = new DynamicParameters();
[Link]("User_NAME", [Link], dbType:
[Link], direction: [Link]);
[Link]("PASS", [Link], dbType:
[Link], direction: [Link]);
IEnumerable<Login> result =
[Link]<Login>("Login_Package.User_Login",
p, commandType: [Link]);
return [Link]();
}
The Learning Hub Copyright
2022- All Right Reserved
[Link] => Service => Create [Link]
public interface IJWTService
{
string Auth(Login login);
}
In [Link] => Service => JWTService => make the class inherit the
interface IJWTService :
public class JWTService: IJWTService
The Learning Hub Copyright
2022- All Right Reserved
[Link] => Service => Create [Link]
private readonly IJWTRepository reposiytory;
public JWTService(IJWTRepository reposiytory)
{
[Link] = reposiytory;
}
The Learning Hub Copyright
2022- All Right Reserved
public string Auth(Login login)
{
var result = [Link](login);
if (result == null)
{
return null;
}
else
{
The Learning Hub Copyright
2022- All Right Reserved
var secretKey = new
SymmetricSecurityKey([Link]("superSecre
tKey@345"));
var signinCredentials = new
SigningCredentials(secretKey,
SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>
The Learning Hub Copyright
2022- All Right Reserved
{
new Claim([Link], [Link]),
new Claim([Link], [Link]())
};
var tokeOptions = new JwtSecurityToken(
claims: claims,
expires:
[Link](24),
The Learning Hub Copyright
2022- All Right Reserved
signingCredentials: signinCredentials
);
var tokenString = new
JwtSecurityTokenHandler().WriteToken(tokeOptions);
return tokenString;
}
}
Note:
JWT supports several signing algorithms such as HMAC with SHA-256, HMAC with SHA-384,
HMAC with SHA-512, and RSA with SHA-256.
The size of the secret key used in a JWT (JSON Web Token) depends on the algorithm being
used to sign the token.
For example, if HMAC with SHA-256 is used, the secret key should be at least 256 bits (32
bytes) long. For RSA algorithms, the key size should be at least 2048 bits.
The Learning Hub Copyright
2022- All Right Reserved
In Program:
[Link]<IJWTRepository,
JWTRepository>();
[Link]<IJWTService, JWTService>();
The Learning Hub Copyright
2022- All Right Reserved
[Link] => Controller => Create [Link]
private readonly IJWTService jwtservice;
public JWTController(IJWTService jwtservice)
{
[Link] = jwtservice;
}
[HttpPost]
public IActionResult Auth([FromBody] Login login)
{
The Learning Hub Copyright
2022- All Right Reserved
var token = [Link](login);
if (token == null)
{
return Unauthorized();
}
else
{
return Ok(token);
}
}
Authorization
[Authorize] VS [AllowAnonymous] attributes:
To control the authorization in [Link] Core In its most basic form, applying the [Authorize] or
[AllowAnonymous] attribute to a controller or action, use the [Authorize] to limit access to that
component to authenticated users and the [AllowAnonymous] attribute to allow access to that
component to all users
[Authorize] VS [AllowAnonymous] attributes:
To control the authorization in [Link] Core In its most basic form, applying the [Authorize] or
[AllowAnonymous] attribute to a controller or action, use the [Authorize] to limit access to that
component to authenticated users and the [AllowAnonymous] attribute to allow access to that
component to all users
The Learning Hub Copyright
2022- All Right Reserved
In the Course Controller:
The Learning Hub Copyright
2022- All Right Reserved
In the Course Controller:
The Learning Hub Copyright
2022- All Right Reserved
To create role-based authorization:
In the controllers folder, create a new class called RequiresClaimAttribute
public class CheckClaimsAttribute : Attribute,
IAuthorizationFilter
{
private readonly string _claimName;
private readonly string _claimValue;
public CheckClaimsAttribute(string
claimName, string claimValue)
{
_claimName = claimName;
_claimValue = claimValue;
}
The Learning Hub Copyright
2022- All Right Reserved
public void
OnAuthorization(AuthorizationFilterContext context)
{
if
()
{
[Link] = new ForbidResult();
}
}
}
The Learning Hub Copyright
2022- All Right Reserved
In the Course Controller:
References
[1]. [Link]
architecture/#:~:text=Onion%20Architecture%20is%20based%20on,on%
Overview of Database
20the%20actual%20domain%20models
[2]. [Link]
us/dotnet/api/[Link]?view=efcore-
5.0